Sub topic 9
Running subagents in parallel or in sequence
This chapter assumes you have read the earlier chapters on what a subagent is, how to decompose a coding task, and how to write a delegation brief. You should also be comfortable with Git branches, basic Python, and the idea of a tool call.
Once you have split a task into units, you must decide when each unit runs. Some units can run at the same time. Others must wait for an earlier unit to finish. This choice affects speed, cost, and the risk of broken output.
The deciding question: what does each task depend on?
Two tasks are independent when neither needs the other's output and neither writes to something the other reads or writes. Independent tasks are candidates for parallel execution. If one task needs another's output, or both modify the same file, the tasks are dependent and need a different arrangement.
Check three kinds of dependency before you choose.
- Data dependency. Task B needs a result from task A. For example, "write tests for the new function" needs the function to exist first.
- Resource dependency. Both tasks write to the same file, the same database, or the same port. They do not need each other's results, but they can still clobber each other.
- Decision dependency. Task A's outcome could change whether or how task B should be done. For example, a investigation of why a build fails decides which fix tasks you create.
Only tasks with none of these dependencies are safe to run in parallel without extra protection.
In this graph, "Change the config schema" runs first. "Update docs" and "Add tests" depend on it, but not on each other, so they can run together once it finishes. The typo fix has no dependencies at all and can run at any time. "Review and merge" waits for everything.
Sequential execution
In sequential execution, the orchestrator starts one subagent, waits for its result, and then starts the next. Use it when:
- A later task needs data from an earlier one, such as an API shape or a list of files to change.
- You are exploring. The first result tells you what the next task should be.
- Tasks touch the same files and you do not want to set up separate workspaces.
- You want to catch problems early. A failed first step stops you from spending money on steps that would have been wasted.
The main cost is wall-clock time. Total time is the sum of all tasks. The main benefit is that the orchestrator can use each result to write a better brief for the next subagent. Remember that a subagent sees only its brief, so a sequential chain works well when each brief includes the relevant facts from the previous result.
Parallel execution
In parallel execution, the orchestrator starts several subagents at once and collects the results when they finish. Total time is close to the time of the slowest task, plus overhead. Use it when:
- Tasks are independent by all three dependency checks above.
- Each task is large enough that the time saved outweighs the cost of writing briefs and merging results.
- You can give each task its own workspace, or the tasks write to clearly separate files.
Parallel execution has costs that are easy to miss. Token usage adds up because each subagent builds its own context. Several subagents may also hit the same API rate limits. Finally, you must merge the results, and that merge is where hidden conflicts appear.
A parallel orchestrator in Python
The example below runs two subagents with asyncio.gather. Setting return_exceptions=True matters. Without it, the first exception propagates out of gather immediately, and you lose the results of tasks that were still running or had already finished. With it, each exception is returned as a value, and the orchestrator can record a failed status for that task and keep the rest.
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)gather returns outcomes in the same order as the tasks you passed in, which is why zip(tasks, outcomes) pairs them correctly. The two example tasks write to different files (README and tests/test_cli.py), so they do not collide.
Mixed plans: stages of parallel work
Real tasks are rarely fully parallel or fully sequential. A common shape is a series of stages. Tasks inside a stage run in parallel. Each stage starts after the previous one finishes.
- Stage 1 (sequential, one task): make the shared change, such as a schema or an interface.
- Stage 2 (parallel): update the callers, docs, and tests that depend on that change.
- Stage 3 (sequential, one task): review the combined result and run the full test suite.
The diagram above is this shape. To build stages from a dependency graph, put every task whose dependencies are all complete into the next stage. The orchestrator can also start a task as soon as its own dependencies finish, without waiting for the whole stage, but stages are easier to reason about and to debug.
Protecting parallel work from file conflicts
Parallel subagents that edit the same working directory can overwrite each other. One agent may also read a file while another is halfway through changing it, and then reason about a state that never existed on its own. There are two defenses.
- Disjoint scopes. Assign each subagent a list of files it may edit, and state it in the brief ("Create or edit only tests/test_cli.py"). This is cheap but relies on the subagent obeying the limit. Check it afterward by inspecting the diff.
- Separate workspaces. Give each subagent its own checkout. Git worktrees let several branches of one repository live in separate directories.
# 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-testsSeparate workspaces prevent live overwrites, but they do not prevent merge conflicts. If both branches change the same lines, Git reports a conflict when you merge. Isolation moves the conflict from runtime to merge time, where it is visible and fixable. Shared resources outside Git, such as a local database or a fixed port, are not isolated by worktrees. Give each workspace its own port or database name if tasks use them.
Choosing: a decision table
| Situation | Choose | Reason |
|---|---|---|
| Task B needs A's output | Sequential | Data dependency |
| Several read-only investigations (search, review, analysis) | Parallel | No writes, so no conflicts |
| Edits to different files in different modules | Parallel | Disjoint scopes |
| Edits to the same file | Sequential, or one subagent | Merge conflicts are likely |
| Unknown next step after a diagnosis | Sequential | Decision dependency |
| Tight budget or rate limits | Sequential, or limit concurrency | Parallel runs spend tokens faster |
Common errors
- Parallelizing too early. Splitting a task before you know its dependencies produces subagents that make incompatible assumptions. When unsure, run a short investigation first.
- Assuming "different files" means independent. Two agents can edit different files that must agree, such as a function and its caller. That is a data dependency even without a file overlap.
- No concurrency limit. Launching twenty subagents at once can exceed rate limits and make the orchestrator's merge step the bottleneck. Cap the number running at once, for example with
asyncio.Semaphore. - Dropping failures. If one parallel task fails, decide explicitly whether the others' results are still usable. Their output may be valid on its own, or it may depend on the failed piece.
- Skipping verification after the merge. Each subagent may pass its own checks, but the combined result can still fail. Run the full test suite on the merged branch.
Exercise
You need to (1) rename a function load_cfg to load_config across the repository, (2) update the user guide to use the new name, and (3) add a changelog entry. Which tasks can run in parallel, and what should run first? Explain your answer.
Show answer
Run the rename first. The guide update refers to the new name, so it has a data dependency on the rename being decided, and the rename may also touch documentation files that contain code samples, which creates a resource dependency. After the rename is done and merged, the guide update and the changelog entry can run in parallel, because they edit different files and neither needs the other's output. If the brief for the guide update states the new name explicitly, the guide task could start earlier, but only if the rename does not edit the same documentation files.
Exercise
In the Python orchestrator, what would change if you removed return_exceptions=True from asyncio.gather, and why does that matter for a multi-agent run?
Show answer
If any subagent raised an exception, gather would raise it immediately to the caller, and the orchestrator would not get the outcomes of the other tasks as normal values. The other tasks could keep running without anyone collecting their results. You would lose the ability to report a per-task failed status and keep the successful work, so one failure would abort the whole run.