◆ AI All-in-One

Level 2 Agentic Coding · Agentic Coding

Running Agents in Parallel and in the Background

Once one agent works reliably, the next step is several at once, in separate worktrees, in the background, in the cloud or inside CI. This chapter covers how to keep parallel agents from colliding, how to run them without a terminal open, how to coordinate and review what they produce, and how to keep the bill under control.

Level
●●●●● Intermediate
Reading
16 min
To learn it well
45 minutes to read, a week to find your own rhythm
↗ Plan a path here

Read first

Extending Your Agent: Skills, Hooks, MCP and SubagentsGit for Agent WorkMulti-Agent Systems

This leads to

—
The full path from zero — 26 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Python for AI
  4. How Machines Learn
  5. Dot Product, Norms and Similarity
  6. Setting Up Your Environment
  7. Large Language Models, Explained Simply
  8. AI Fluency: Working Well with AI
  9. Prompt Engineering
  10. Using LLM APIs
  11. Asking Well: Everyday Prompting
  12. Embeddings and Semantic Search
  13. Structured Output and JSON
  14. Chain-of-Thought and Reasoning Prompts
  15. What Is Agentic Coding?
  16. Retrieval-Augmented Generation
  17. Tool Use and Function Calling
  18. Planning and Specs: Telling an Agent What to Build
  19. Setting Up a Coding Agent
  20. Context Engineering and Memory
  21. Model Context Protocol
  22. AI Agents
  23. Project Context and Memory Files
  24. Git for Agent Work
  25. Multi-Agent Systems
  26. Extending Your Agent: Skills, Hooks, MCP and Subagents
  27. Running Agents in Parallel and in the Background

Read them roughly in this order. See it on the concept map →

Why it matters

Watch an agent work on a real task and you will notice how much of the time you are waiting. It reads files, edits, runs the tests, reads the failure, edits again. Five, fifteen, forty minutes. You could review its last change, or write the next spec, or start a second agent on a different task.

Running several agents at once is now routine for many developers, and every major tool supports it (as of late 2026): extra sessions in separate worktrees, background agents that keep working with no terminal open, cloud agents that turn a task into a pull request on someone else's machine, and headless runs inside scripts and CI pipelines. Done well, it turns waiting time into throughput.

Done badly, it multiplies every problem in this part of the guide. Two agents edit the same file and one overwrites the other. Five unreviewed branches pile up, each plausible, none checked. The token bill is five times larger and the finished, trustworthy work is not. Simon Willison, who was sceptical before adopting the habit, names the real limit: an agent can write code faster than you can review it. This chapter is about working within that limit.

The idea

A kitchen with several cooks

Picture a restaurant kitchen. One head chef could cook every dish alone, but at dinner rush the kitchen runs on several cooks working at once. It works because of three rules. Each cook has their own station, so nobody reaches into someone else's pan. Each gets a clear ticket: one dish, fully specified. And every plate passes the head chef before it goes out. The pass, not the stoves, decides how fast food leaves the kitchen.

Parallel agents need the same three things:

  1. Isolation. Each agent works in its own copy of the code: a separate worktree on your machine, or a separate sandbox in the cloud. Never two agents in one folder.
  2. Independent, well-specified tasks. Tasks that touch different files and can be judged on their own (Planning and Specs: Telling an Agent What to Build). If task B needs task A's result, they are one task, or two in sequence.
  3. A review queue you can keep up with. Every branch still gets read, tested and reviewed before it merges. That queue is the review bottleneck: the point where parallel work has to pass through one person in series.
You 3 small specs Terminal session worktree ../tally-export Background agent its own worktree, no terminal Cloud agent sandboxed clone, opens a PR 3 branches Review queue read, test, merge, one at a time main isolation: one copy of the code per agent the bottleneck one reviewer: you
Fig. 1 Three tasks run in parallel, each in its own isolated copy: one in a terminal worktree, one as a background session, one as a cloud agent. All three end up as branches in one review queue, which you work through one at a time before anything reaches main.

Key idea Parallel agents speed up the agent's part of the work, not yours. Start as many as you can review, not as many as you can launch. For most people that is two or three at a time, plus any number of read-only research tasks.

Why the review queue sets the pace

Suppose three tasks each take an agent 15, 20 and 30 minutes, and each takes you about 10 minutes to review properly. Done one after another, with you reviewing each before starting the next, that is 15+10+20+10+30+10=9515 + 10 + 20 + 10 + 30 + 10 = 95 minutes. Started together, the agents finish at minutes 15, 20 and 30, and you review them as they land: done at minute 45. Less than half the time.

Now add a fourth and fifth agent. The agents still finish within about half an hour, but your reviews now run to minute 65, and if you skim to keep up, you are back to merging unreviewed code. Past a small number of agents, the total time is roughly the slowest agent plus all the reviews:

Tparallel≈min⁡iai+∑iriT_{\text{parallel}} \approx \min_i a_i + \sum_i r_i

where aia_i is how long agent ii takes and rir_i how long you take to review its work. (The first review can start when the fastest agent finishes; after that, reviews follow one another as long as there is always one waiting.) The sum of the reviews grows with every agent you add. The way to go faster is to make each rir_i smaller: small tasks, tests that already pass, a clear spec to check against, and an automated first review.

One after another agent A B C you review A review B review C In parallel agent A A agent B B agent C C you review A review B review C 0 15 30 45 60 75 90 minutes (illustrative) done at 95 done at 45 your reviews are now the critical path: each extra agent adds a review but saves little waiting agent working you reviewing
Fig. 2 The same three tasks done one after another (top) and in parallel (bottom), in illustrative minutes. In parallel, the agents' work overlaps, but your reviews still happen one at a time, so they become the critical path.

Where the agents can run

Where How it works Good for Watch out for
Extra sessions on your machine One terminal per agent, each in its own worktree Tasks you want to watch or steer Each worktree needs its own setup (virtual environment, .env)
Background agents on your machine Sessions that run with no terminal attached, managed from one list Several independent tasks you check on later Machine must stay on; each session uses your quota
Cloud agents A sandboxed copy of the repository on the provider's machines; result arrives as a pull request Well-specified tasks from anywhere, even a phone The sandbox needs its own setup and has none of your local secrets
Headless, in scripts and CI The agent runs one prompt non-interactively and exits Repeatable jobs: fan-out over many files, nightly checks, reacting to issues Nobody is watching: permissions and budgets must be set in advance

Subagents (Extending Your Agent: Skills, Hooks, MCP and Subagents) are a fifth kind of parallelism, inside one session: the main agent sends several helpers off at once and collects their summaries. They suit research and review. They are not a way to build three features at once, because their results all come back into one conversation.

In practice

Several sessions in worktrees

The basic setup needs only git. One worktree per task, one agent per worktree:

git worktree add ../tally-export -b export-json main
git worktree add ../tally-top    -b top-command main
cd ../tally-export && claude     # terminal 1
cd ../tally-top    && codex      # terminal 2: the tools can even differ

Claude Code shortens this to claude --worktree export-json (or -w), which creates .claude/worktrees/export-json/ on a new branch and starts a session there. A worktree is a fresh checkout, so files that git ignores, such as .venv/ and .env, are not there. Either ask the agent to set up the environment first, or list the files to copy in a .worktreeinclude file at the project root (same syntax as .gitignore). Also watch for shared resources outside the folder: two copies of a web app can't both listen on port 8000, and two test runs writing to the same database will interfere.

Background agents

A background agent is an agent session that runs without a terminal attached and reports back when it finishes or needs you. In Claude Code (as of late 2026):

claude --bg "fix the crash when report runs on an empty file; add a test"
claude --bg --name readme "add a Usage section to README.md"
claude agents            # one screen: Working, Needs input, Ready for review
claude attach readme     # step into a session; detaching leaves it running
claude logs readme       # recent output without attaching

To stop one, select it in claude agents and press Ctrl+X, or run claude stop with its session ID. Inside a running session, /bg sends the current conversation to the background. Sessions started with --bg move into their own worktree before they edit anything, so they don't collide. The agent view list (a research preview as of late 2026) is the important part: it shows at a glance which agents are waiting for an answer and which have finished, so you spend your attention only where it is needed. Desktop apps and IDEs offer similar session lists. Codex's app, for example, runs parallel threads in worktrees.

Two built-in shortcuts are worth knowing. /batch asks Claude Code to split one large mechanical change (a rename across the codebase, a library migration) into between 5 and 30 subagents, each in its own worktree. Agent teams, an experimental feature that is off by default, go further: an agent team is a group of sessions led by one agent that splits a project, assigns the pieces and lets the workers message each other and share a task list. Teammates don't get separate worktrees, so the lead must give each one different files.

Cloud agents

Cloud agents (Claude Code on the web, Codex cloud, the GitHub Copilot cloud agent, Cursor's cloud agents, Google's Jules) take the machine out of the picture. You describe a task in a web page, a chat app, or by assigning a GitHub issue. The agent clones the repository into a sandbox, works, runs the tests, and opens a pull request. You can start five before lunch and review them after.

They work only as well as the sandbox is set up. Each provider lets you configure the environment: a setup script that installs dependencies, which network access to allow, which secrets to provide. Before handing out real tasks, give the cloud agent a trivial one ("run the tests and report the result") to check that the sandbox can build and test your project. A cloud agent that can't run your tests will still open a confident pull request.

Headless: agents in scripts and CI

Headless mode means running an agent non-interactively: one prompt in, the agent works with no one to answer questions, the result comes out, the process exits. This is how agents run in scripts, scheduled jobs and continuous integration.

# Claude Code
claude -p "Find and fix the bug in parse_amount; run the tests" \
  --allowedTools "Read,Edit,Bash(python -m pytest *)" \
  --max-turns 20 --output-format json
# Codex CLI: read-only sandbox by default; allow edits explicitly
codex exec --sandbox workspace-write "Fix the failing test in test_tally.py"

Because no human approves anything, the permissions must be decided up front: list exactly the tools the job needs (--allowedTools), or set a permission mode. With --output-format json, Claude Code's result includes the text, a session_id for continuing later, and total_cost_usd, an estimate of what the run cost. Codex's --json prints machine-readable events.

Both agents also come as GitHub Actions. With Anthropic's action, a workflow can respond whenever someone writes @claude in an issue or pull request comment, or run a fixed prompt on a schedule or on every pull request:

# .github/workflows/claude.yml (abridged)
on:
  issue_comment: { types: [created] }
jobs:
  claude:
    if: contains(github.event.comment.body, '@claude')
    runs-on: ubuntu-latest
    timeout-minutes: 30
    permissions: { contents: write, pull-requests: write, issues: write, id-token: write }
    steps:
      - uses: actions/checkout@v7
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          claude_args: "--max-turns 10"

Running /install-github-app inside Claude Code sets this up for you. OpenAI publishes openai/codex-action for the same purpose.

In code

Headless agents make fan-out easy: one script, many tasks, one agent and one worktree each. This script runs three tally tasks at once, commits each agent's work on its own branch, and prints the size of each change and the total cost.

# fan_out.py: run one headless agent per task, each on its own branch and worktree
import json, os, shlex, subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

TASKS = {
    "export-json": "Add `tally export --json` that prints all expenses as JSON. Test it.",
    "top-command": "Add `tally top` that prints the 3 biggest expenses this month. Test it.",
    "readme-usage": "Add a Usage section to README.md with one example per command.",
}
AGENT = shlex.split(os.environ.get("AGENT",
    "claude -p --permission-mode acceptEdits --allowedTools 'Bash(python -m pytest *)'"
    " --max-turns 30 --max-budget-usd 2 --output-format json"))

def sh(*cmd, cwd="."):
    return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, check=True).stdout

def run(name, prompt):
    tree = Path("..") / f"tally-{name}"
    sh("git", "worktree", "add", str(tree), "-b", name)
    out = subprocess.run(AGENT + [prompt], cwd=tree, capture_output=True, text=True)
    cost = json.loads(out.stdout or "{}").get("total_cost_usd", 0)
    sh("git", "add", "-A", cwd=tree)
    sh("git", "commit", "-qm", f"agent: {name}", cwd=tree)
    stat = sh("git", "diff", "--shortstat", "main", cwd=tree).strip()
    return name, out.returncode, cost, stat

with ThreadPoolExecutor(max_workers=3) as pool:
    results = list(pool.map(lambda task: run(*task), TASKS.items()))
for name, code, cost, stat in results:
    print(f"{name:13} exit={code} ${cost:.2f}  {stat}")
print(f"total ${sum(r[2] for r in results):.2f}")

Run it from tally's folder. The --max-turns and --max-budget-usd flags put a ceiling on each agent, so a confused agent can't loop all night. To test the plumbing without spending anything, point AGENT at a stand-in script that edits a file and prints {"total_cost_usd": 0.0}. That is how the output below was produced, so the costs are zero and the changes tiny:

$ AGENT="python3 fake_agent.py" python3 fan_out.py
export-json   exit=0 $0.00  1 file changed, 5 insertions(+)
top-command   exit=0 $0.00  1 file changed, 1 insertion(+)
readme-usage  exit=0 $0.00  1 file changed, 5 insertions(+)
total $0.00

The script deliberately stops at three branches. Merging is your job, after review.

Worked example: merging three agents' work

The three branches are ready. The stand-in agents did what real ones often do: both export-json and top-command registered their new subcommand on the same line of main(). Merge in order of least risk first:

git merge readme-usage        # docs only, touches no code
# Fast-forward
#  README.md | 5 +++++
git merge export-json
# Merge made by the 'ort' strategy.
#  tally.py | 5 +++++
git merge top-command
# Auto-merging tally.py
# CONFLICT (content): Merge conflict in tally.py
# Automatic merge failed; fix conflicts and then commit the result.

git diff shows the clash:

      sub.add_parser("report")
++<<<<<<< HEAD
 +    sub.add_parser("export")
++=======
+     sub.add_parser("top")
++>>>>>>> top-command

Both lines should stay. Delete the three marker lines, keep both add_parser calls, run the full test suite (each branch passed alone; together they have never been tested), then git add tally.py && git commit. You can also ask an agent: "resolve the merge conflict in tally.py, keeping both commands, then run the tests and explain what you did". Conflicts like this one are easy. The dangerous ones merge cleanly but break: branch A renames a function that branch B, written in parallel, still calls. Only running the tests after every merge catches those.

Three habits come out of this example. Plan for overlap: when two tasks must touch the same file, say so in their specs, or run them one after the other. Merge the least risky branch first, and rebase or re-test the rest on top of it. Delete finished worktrees (git worktree remove ../tally-export-json) so stale copies don't pile up.

Keeping the bill under control

Every agent you add multiplies the tokens spent. Anthropic's report on its multi-agent research system found multi-agent runs used about 15 times the tokens of a chat (Multi-Agent Systems works through when that pays). On a subscription, parallel sessions share one usage allowance and hit its limits sooner. On an API key, they simply cost more. Practical controls:

  • Cap every unattended run: --max-turns, --max-budget-usd (Claude Code), job timeouts and concurrency limits in CI.
  • Log the cost: collect total_cost_usd from JSON output, or the provider's usage dashboard, and look at the cost of merged work, not of runs.
  • Use cheaper models for narrow jobs: research and review subagents often work fine on a smaller model.
  • Kill early. An agent that is clearly off course after five minutes will rarely recover by minute thirty. Stop it, sharpen the spec, restart.

Common mistakes

  • More agents than reviews. Branches that nobody reads are not progress; they are risk waiting to be merged.
  • Two agents in one folder. They overwrite each other's edits and confuse each other's test runs. One worktree or sandbox per agent.
  • Dependent tasks in parallel. "Add budgets" and "show budgets in the report" in parallel means the second agent invents its own version of the first.
  • Testing branches only alone. Each passed its tests; the merge of all three may not. Re-run everything after each merge.
  • A different setup per worktree. Three worktrees with three slightly different environments produce results you can't compare. Script the setup, and keep the shared memory file current so every agent gets the same briefing.
  • Forgetting background agents exist. Unattended sessions keep spending. Check the list daily and stop what you no longer need.

Watch out Headless and background agents work with no one watching, so whatever they can do, they will do unseen. Give them the narrowest permissions the task needs, never --dangerously-skip-permissions outside a disposable container, and keep secrets out of their reach. Be especially careful with untrusted input: an agent triggered by a public issue or pull request reads text written by strangers, which is the classic setting for Prompt Injection and LLM Security. Claude Code's documentation also warns that a claude -p run executes a repository's project hooks and connects its .mcp.json servers even in a folder you have never trusted, with no prompt. In CI on code you didn't write, use --bare, which skips them.

Where it leads

A bit of history

Running several coding agents at once became common in 2025. Developers first did it by hand with git worktrees and several terminal windows, a pattern Anthropic's best-practice guidance described that spring. Cloud agents arrived in the same period: OpenAI's Codex cloud and Google's Jules in May 2025, GitHub's Copilot coding agent (since renamed the cloud agent) the same month, then Cursor's background agents in mid-2025 and Claude Code on the web that October. Headless modes (claude -p, codex exec) and official GitHub Actions turned agents into ordinary CI steps. Through 2026 the tools added the management layer that had been missing: background-session lists, automatic worktree isolation and experimental agent teams. The tools change quickly; the three kitchen rules haven't.

Try it

  1. Pick two small, independent tasks on a project of yours. Run them at the same time in two worktrees, then time yourself: how long did the agents take, and how long did your reviews take?
  2. Run fan_out.py with a stand-in agent first, then with a real one on two genuinely independent tasks. Compare total_cost_usd with what you expected.
  3. Deliberately give two parallel agents tasks that touch the same function. Merge both and resolve the conflict. Did the tests still pass after the merge?

Hint for 1: if your reviews took longer than the agents, you have found your bottleneck. Smaller tasks with tighter specs and passing tests shorten reviews more than any extra agent will.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Three agents take 15, 20 and 30 minutes and you need 10 minutes to review each. Started together, roughly when are all three reviewed?

  2. You can launch ten agents at once. What does the chapter say should limit how many you start?

  3. You want one agent to add budgets and another to show budgets in the report, both at the same time. What is likely to go wrong?

  4. Three branches each passed their tests alone and merged without conflicts. What should you still do?

  5. You run an agent headless in CI with claude -p. Which setting matters most because nobody is there to answer approval prompts?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Embracing the parallel coding agent lifestyle

Simon Willison · 2025 · Beginner · Free

A sceptic's account of running several coding agents at once: which kinds of task suit it (research, explanations, small fixes, well-specified changes) and why review remains the bottleneck.

Docs

Claude Code: run agents in parallel

Anthropic · Intermediate · Free

Compares subagents, background sessions in agent view, agent teams, dynamic workflows and cloud projects, with worktrees for isolation and advice on choosing between them.

Docs

Claude Code GitHub Actions

Anthropic · Intermediate · Free

Run Claude Code in GitHub workflows: mention @claude in an issue or pull request, set up with /install-github-app, and configure the claude-code-action.

Tool

Codex CLI

OpenAI · Beginner · open source; needs a ChatGPT plan or API key

OpenAI's open-source terminal coding agent. Reads AGENTS.md, runs in a sandbox with configurable approval policies, and has a non-interactive codex exec mode.

Article

How we built our multi-agent research system

Anthropic · 2025 · Intermediate · Free

An unusually candid engineering write-up of an orchestrator with parallel sub-agents: architecture, prompting lessons, token costs, evaluation and production reliability.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/agentic/parallel-agents.md