Sub topic 6
The orchestrator-worker pattern
This chapter assumes you have used an AI coding agent in a terminal, know what a context window and a tool call are, and can read basic Python. It builds on the earlier chapters on what a subagent is and how to split a task into delegable units.
The two roles
In the orchestrator-worker pattern, one agent coordinates and several others do the work.
- The orchestrator owns the overall goal. It splits the task, writes a brief for each unit, starts the workers, collects their replies, and decides what to do next.
- A worker is a subagent that receives one brief, works in its own context, and returns a short result.
The orchestrator does not do the detailed work itself. If it reads every file and edits every line, its context grows as fast as a single agent's would, and you lose the benefit of delegating. Its context should hold the plan, the briefs, and the summaries that come back.
Workers are also not peers. They do not talk to each other, and each one sees only its brief. Any information a worker needs must be in the brief or in the workspace it can read.
How a run flows
The loop has four steps: decompose, delegate, collect, verify. The orchestrator may repeat it. For example, it can start a second round of workers to fix problems that verification found.
A minimal orchestrator
The Python below shows the control flow. run_subagent is a placeholder for your agent runtime. The orchestrator starts independent tasks together and keeps going if one fails.
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)Two details matter here. return_exceptions=True makes asyncio.gather return a raised exception as a value instead of cancelling the whole run. The loop then records a failed status for that task, so the orchestrator can retry it or report it. Each result also has the same shape (name, status, summary), which makes aggregation simple.
Common errors
- Thin briefs. A one-line brief forces the worker to guess. The worker cannot see the parent's conversation, so it fills gaps with assumptions.
- Overlapping scopes. Two workers that edit the same file produce conflicts. Give each worker separate files, or separate checkouts.
- Orchestrator doing worker jobs. Once the orchestrator starts reading large files, its context fills with detail it should have delegated.
- Trusting summaries. A worker reports what it believes it did. The orchestrator should check the result, for example by running the tests.
- No failure path. Without a status field, a crashed worker looks the same as a worker that had nothing to report.
Exercise
In the code above, why does orchestrate pass return_exceptions=True to asyncio.gather, and what would happen without it?
Show answer
With return_exceptions=True, an exception raised by one worker is returned in the outcomes list instead of being raised from gather. The orchestrator can then mark that task as failed and still use the other results. Without it, the first exception would propagate out of await asyncio.gather(...), and the orchestrator would lose the results of the workers that succeeded.