Sub topic 6
The orchestrator-worker pattern
This chapter assumes you have used a coding agent in a terminal or editor, know what a context window and a tool call are, can read basic Python, and are comfortable with Git branches. It also assumes you know what a subagent is: a separate agent instance with its own context. Here you will see how one agent coordinates several of them.
The pattern in one paragraph
In the orchestrator-worker pattern, one agent, the orchestrator, owns the overall goal. It splits the goal into units, hands each unit to a worker (a subagent), and combines what comes back. Workers do not talk to each other. Every message goes through the orchestrator. This keeps control in one place, which makes runs easier to reason about and to debug.
What each role owns
The two roles hold different responsibilities. Mixing them is the most common design mistake.
| Concern | Orchestrator | Worker |
|---|---|---|
| Goal | The whole task | One scoped unit |
| Context | User conversation, plan, summaries | Only its brief and what it reads itself |
| Tools | Spawning workers, reading results, running checks | The minimum for its unit |
| Output | Final, verified result | A short summary of what it did |
| Decisions | What to split, order, accept, retry | How to complete its unit within the brief |
The orchestrator should stay thin. If it starts editing files itself, its context fills with the same detail you were trying to keep out of it. Its job is planning, dispatching, checking, and merging.
The orchestrator's loop
The orchestrator follows a short cycle:
- Decompose. Break the goal into units that can be finished and checked on their own.
- Brief. Write a self-contained brief for each unit. The worker cannot see the parent's history, so the brief is its entire world.
- Dispatch. Start workers, in parallel when the units are independent and in sequence when one needs another's output.
- Collect. Gather each worker's summary or error.
- Verify. Run checks and review the changes before trusting any summary.
- Decide. Accept, retry with a corrected brief, or report a failure to the user.
Steps 5 and 6 are what separate an orchestrator from a script that just fans out work. A worker's summary describes what the worker believes it did. It is a claim, not proof.
A minimal orchestrator in Python
The example below runs independent workers concurrently. run_subagent is a placeholder. In real use you would replace it with a call to your agent runtime, passing only the brief.
import asyncio
from dataclasses import dataclass
@dataclass
class Task:
name: str
brief: str
async def run_subagent(task: Task) -> dict:
# Placeholder: replace with a call to your agent runtime.
# The subagent receives only the brief, not the parent's history.
await asyncio.sleep(0.1)
return {"name": task.name, "status": "ok", "summary": f"finished {task.name}"}
async def orchestrate(tasks: list[Task]) -> list[dict]:
outcomes = await asyncio.gather(
*(run_subagent(t) for t in tasks), return_exceptions=True
)
results = []
for task, outcome in zip(tasks, outcomes):
if isinstance(outcome, Exception):
results.append({"name": task.name, "status": "failed", "summary": str(outcome)})
else:
results.append(outcome)
return results
if __name__ == "__main__":
tasks = [
Task("update-docs", "Update README usage section for the new --verbose flag."),
Task("add-tests", "Add unit tests for parse_args in tests/test_cli.py."),
]
for result in asyncio.run(orchestrate(tasks)):
print(result)Three details matter here:
asyncio.gatherstarts all workers at once, so total time is close to the slowest worker, not the sum.return_exceptions=Truemakesgatherreturn exceptions as values instead of raising the first one. Without it, one failing worker would abort the collection step and you would lose the results of the others.- The loop turns each exception into a
failedrecord. The orchestrator can then decide what to do with it, rather than crashing.
This example only catches exceptions. A worker that returns "status": "ok" after doing the wrong thing is not caught here. That is what the verify step is for.
What the orchestrator sends: the brief
Because workers are isolated, the brief carries everything. A usable brief states the goal, context, scope, constraints, a checkable finish condition, and the reply format.
Goal: Add unit tests for the parse_args function in src/cli.py.
Context: parse_args builds an argparse parser with --verbose and --output options. Tests live in tests/ and use pytest.
Scope: Create or edit only tests/test_cli.py. Do not change files under src/.
Constraints: Do not add new dependencies. Tests must run offline.
Done when: pytest tests/test_cli.py passes.
Return: A short summary of the tests added, the command you ran to check them, and its result. Do not paste full file contents.Two lines do most of the work. "Done when" gives the worker a way to know it is finished and gives the orchestrator a command to re-run. "Return" caps the reply size, which protects the orchestrator's context. Later chapters cover briefs and aggregation in more detail. Here the point is that the brief is the interface between the two roles.
Parallel work needs separate workspaces
Workers that run at the same time and edit the same checkout can overwrite each other's files. One fix is to give each worker its own Git worktree, a separate directory with its own branch, backed by the same repository.
# Give each parallel subagent its own checkout and branch
git worktree add ../wt-docs -b agent/docs
git worktree add ../wt-tests -b agent/tests
# ...each subagent works inside its own directory...
# After reviewing and merging the branches, clean up
git worktree remove ../wt-docs
git worktree remove ../wt-testsThe orchestrator then merges branches one at a time and runs the project's checks after each merge. Separate worktrees prevent file collisions while the workers run. They do not prevent logical conflicts, such as two workers changing the same function's signature in different files. You find those at merge time.
Common errors
- Overlapping scopes. Two units both touch
src/cli.py. Fix this in decomposition, by assigning each file to one worker or running those units in sequence. - Thin briefs. A brief like "fix the tests" forces the worker to guess. It will either explore at length, spending cost, or guess wrong.
- Trusting summaries. Accepting "all tests pass" without running the tests yourself.
- A fat orchestrator. Pasting full worker output back into the orchestrator's context defeats isolation.
- Fan-out for its own sake. Three tiny edits are faster in one agent than in three workers plus a merge.
- No failure path. Treating a timeout or an exception as success because the collection code never checked.
When this pattern fits
Use orchestrator-worker when the task splits into units that are mostly independent, each unit has a checkable result, and the combined work would strain one context window. Prefer a single agent when the steps depend tightly on each other or the whole task is small. The coordination cost (writing briefs, merging, verifying) is real and has to be paid back by saved time or a cleaner context.
Exercise
An orchestrator dispatches three workers with asyncio.gather and return_exceptions=True. Worker B raises a TimeoutError, and A and C succeed. What does orchestrate return, and what should the orchestrator do next?
Show answer
It returns three records: A and C with their normal "ok" results, and B with status "failed" and the error text as its summary. The orchestrator should not accept the combined work yet. It should verify A and C independently, then decide whether to retry B with the same or a corrected brief, or report the failure to the user. Without return_exceptions=True, the TimeoutError would have propagated out of gather and the orchestrator would have lost the results from A and C.
Exercise
You plan to run two workers at once. One edits src/cli.py to add a flag, and the other edits src/cli.py to rename a helper function. Which decomposition problem is this, and what are two ways to handle it?
Show answer
It is an overlapping scope problem. Both workers would change the same file. You can run the two units in sequence so the second starts from the first one's merged result, or you can redefine the units so each worker owns different files. Giving each worker a separate git worktree would stop them overwriting each other during the run, but the changes would still conflict at merge time, so it does not remove the underlying overlap.