Why Subagent Orchestration?
If you use Claude Code regularly, you've probably wondered whether there's a way to make it run faster and smarter. A single agent working sequentially is already powerful — but real-world software development is full of tasks that are naturally parallel.
Subagent orchestration means using Claude Code's Task tool to launch multiple subagents simultaneously, delegate specialized work to each, and coordinate their results. In practice, this can complete the same work in 3–10x less time.
This guide shares what I've learned through hands-on experimentation across real projects: the design philosophy, implementation patterns, error handling strategies, and quantified outcomes of subagent orchestration.
Chapter 1: The Task Tool and Its Design Philosophy
What Is the Task Tool?
The Task tool lets Claude Code spin up a subagent — another independent Claude instance — and hand it a specific job. The subagent completes the work and returns its result to the parent.
Here's the basic structure:
Parent Agent
├─ Task("Write tests for Component A") ─→ Subagent 1
├─ Task("Write tests for Component B") ─→ Subagent 2
└─ Task("Update API documentation") ─→ Subagent 3
↓ (after all complete)
Aggregate & verify results
A crucial design detail: subagents have independent contexts — they can't see each other. This is a feature (no interference) but also a constraint (explicit information sharing is required).
Orchestration vs. Sequential Processing
Sequential (the traditional approach):
Task A → done → Task B → done → Task C → done
Total time: A + B + C
Orchestration:
Task A ─┐
Task B ─┼─→ Concurrent execution → All complete → Aggregate
Task C ─┘
Total time: max(A, B, C) + aggregation time
For tasks without dependencies, parallelization can theoretically complete $N$ tasks in $1/N$ the time (realistically around $1/(N \times 0.7)$ due to overhead).
Chapter 2: Core Orchestration Patterns
Pattern 1: Fan-Out
The most fundamental pattern. A single input is distributed across multiple subagents for parallel processing.
Use cases: Bulk refactoring of multiple files, multi-language translation, test creation across modules.
Sample prompt to Claude:
Please launch independent subagents for each of these 8 components
and create unit tests in parallel:
- src/components/Button.tsx
- src/components/Input.tsx
- src/components/Modal.tsx
- src/components/Table.tsx
- src/components/Card.tsx
- src/components/Dropdown.tsx
- src/components/Tooltip.tsx
- src/components/Badge.tsx
Instructions for each subagent:
- Read the target file and understand the component's spec
- Create a test file using Jest + React Testing Library
- Include edge cases (empty strings, null values, boundary conditions)
- Report the number of tests written and the cases covered
Outcome: Tests for all 8 components completed in approximately 7–8x less time than sequential execution.
Pattern 2: Pipeline
Chain stages together so the output of one feeds the next, while parallelizing work within each stage.
Use cases: Data collection → analysis → report generation and other multi-stage workflows.
Stage 1 (parallel): Collect data from each source
↓ Aggregate
Stage 2 (parallel): Analyze different facets of the data
↓ Aggregate
Stage 3 (parallel): Generate each section of the report
↓ Final aggregation
Real-world case:
The automated content generation system I built for four AI blog sites (including claudelab.net) uses this pattern:
- Stage 1: Collect existing article slugs from each site (4 parallel)
- Stage 2: Duplicate check + SEO keyword analysis (4 parallel)
- Stage 3: Generate JA + EN article content (8 parallel = 4 sites × 2 languages)
- Stage 4: Run generate-content.mjs + push (4 parallel)
This pipeline reduced 4 sites × 2 languages = 8 articles from roughly 3 hours (sequential) to about 45 minutes.
Pattern 3: Map-Reduce
Distribute large-scale processing across parallel agents (Map), then aggregate the results (Reduce).
Use cases: Static analysis of an entire codebase, impact assessment for large-scale refactors.
Input: Codebase with 500 files
Map (50 agents × 10 files each):
- Analyze dependencies
- Detect code smells
- Collect TypeScript errors
Reduce:
- Aggregate results
- Sort by impact severity
- Generate prioritized fix report
Key implementation note: Standardize the output format for each subagent. If formats vary, the parent's aggregation step becomes unnecessarily complex.
// Example standardized output spec to include in subagent instructions
Output format (required):
{
"file": "file path",
"issues": [
{"type": "error|warning|info", "line": lineNumber, "message": "description"}
],
"summary": "one-line summary"
}
Pattern 4: Specialist Delegation
Delegate different aspects of a task to "specialist" subagents, each focused on their area.
Parent Agent (Coordinator)
├─ Security Specialist → Review auth/permission logic
├─ Performance Specialist → Bottleneck analysis + optimization
├─ Test Specialist → Coverage check + write missing tests
└─ Documentation Specialist → Comment cleanup + API doc generation
Each specialist agent receives a system prompt and context tailored to their domain, enabling deeper expertise than a generalist agent.
Chapter 3: Information Sharing and State Management
Since subagents have independent contexts, sharing information between them requires deliberate design.
File-Based Shared State
The simplest and most reliable approach: use shared files as the communication channel.
/tmp/work/
├── input/ # Input data (prepared by parent)
├── intermediate/ # Partial results (each agent writes here)
│ ├── agent1_result.json
│ ├── agent2_result.json
│ └── agent3_result.json
└── output/ # Final output (parent aggregates here)
Prompt pattern:
Each subagent should save its result to the following path upon completion:
/tmp/work/intermediate/{agentID}_result.json
Once all subagents have completed, read all files in intermediate/
and aggregate them into output/final_report.json.
Avoiding Write Conflicts
Multiple agents writing to the same file simultaneously causes conflicts. To prevent this:
- Assign each agent its own unique file path (recommended)
- Include the agent ID or timestamp in the filename
- Use separate output directories per agent
Another Axis of Parallelism: Isolating Agents Physically with git Worktrees
The previous section avoided write conflicts by separating file paths. Take it one step further and you can separate the working directory itself — with git worktrees.
Subagents launched through the Task tool share the same working tree (the same checkout). That is fine for read-heavy tasks. But once you run implementation work that spans multiple branches or installs dependencies in parallel, the agents start fighting over the same directory.
A git worktree lets a single repository have several working directories at once. Where git checkout swaps the contents of one directory, a worktree creates a physically separate folder. Each holds its own branch, so you can edit different code at the same time.
# Cut a worktree per feature
git worktree add ../wt-auth -b feature/auth
git worktree add ../wt-payments -b feature/payments
# Check the current worktrees
git worktree listRun Claude Code separately in each worktree and the auth work never touches the payment files. You think less about per-file locking, and integration falls back to the mechanism git already has: the merge.
Give Each Worktree Its Own CLAUDE.md
Because a worktree is an independent directory, each can carry its own CLAUDE.md. Put task-specific rules in the auth worktree — "don't touch the schema," "keep coverage above 90%" — and the subagent is far less likely to wander. Use the parent repo's CLAUDE.md for the overall direction and each worktree's CLAUDE.md for the task at hand, and your instructions gain resolution.
Always Clean Up Finished Worktrees
The weakness of worktrees is that they multiply if you ignore them. Forget to remove a merged worktree and it eats disk and clutters git worktree list.
# Remove a worktree after integration
git worktree remove ../wt-auth
git branch -d feature/auth
# Sweep up leftover worktrees from a failed removal
git worktree prune
git worktree remove --force ../wt-orphanedAs an indie developer working across the Dolice sites, I once left worktrees lying around and, half a day later, lost track of which folder was the production one. Rather than memorizing the create command, making cleanup a habit is what actually keeps you fast.
There are two axes of parallelism: the logical separation the Task tool gives you among subagents inside one tree, and the physical separation worktrees give you across directories. Reach for the former for reading and analysis, the latter for implementation that crosses branches — and the conflicts largely stop happening in the first place.
Chapter 4: Error Handling and Resilience
Distributed processing introduces more failure points than single-agent execution. Robust error handling is essential.
Retry Strategy
Include in your subagent instructions:
If the operation fails, retry up to 2 times.
On each retry, adjust your approach based on the previous failure.
After 3 failures, record the error details in result.json under the "error" field and exit.
Handling Partial Failures
Design the orchestrator to expect partial failures, not universal success:
Wait for all 10 subagents to complete.
Evaluate results:
- 8+ successes → Re-run only the failed agents' tasks
- 5–7 successes → Re-run failures, then aggregate after full completion
- 4 or fewer successes → Pause and request human review
All subagent outputs must include a success: true/false flag.
Timeout Management
For long-running subagents:
Expected processing time per agent: 10–15 minutes.
If 20 minutes pass without completion, save partial results and exit.
Timeout output: {"status": "timeout", "partial_result": {...}}
Chapter 5: Real-World Project Case Studies
Case 1: Full Type Safety Migration for a Next.js Project
Context: A 50,000-line Next.js project needed any types eliminated throughout.
Orchestration design:
Phase 1 (Analysis):
20 parallel agents × directory units
→ List all any type occurrences
→ Score by impact (length of type chain)
Phase 2 (Fixes):
Top 50 locations processed by 10 parallel agents
→ Each agent handles 5 locations
→ Auto-fix inferrable types
→ Flag ambiguous cases with comments
Phase 3 (Validation):
5 parallel agents × directory units
→ TypeScript compile error check
→ Unit tests for modified code
Results:
- Time: Estimated 6 days → Actual 8 hours (~18x speedup)
anytype reduction: 82%- New bugs introduced: 0
Case 2: Multi-Language Documentation Sync
Context: Documentation maintained in Japanese, English, Chinese, and Spanish. Syncing after each Japanese update was a significant overhead.
Orchestration design:
Input: Japanese diff (git diff)
Stage 1: 3 parallel agents (EN / ZH / ES translators)
→ Each generates a translation of the changed sections
→ Includes localization (idioms, cultural adaptation)
Stage 2: 1 quality-checker agent
→ Cross-reads all 3 translations for consistency
→ Flags anything unnatural
Stage 3: 3 parallel agents (file writers for each language)
→ Apply reviewed translations
Results:
- Sync time: 2–4 hours → ~12 minutes (up to 20x faster)
- Translation quality: 4.2/5.0 satisfaction from native reviewers (compared to human translation)
Case 3: Automated Code Review
Context: PR review wait time became a development bottleneck.
Orchestration design:
Input: PR diff
Parallel review team:
├─ Security Agent: Vulnerabilities, privilege escalation, injection risks
├─ Performance Agent: N+1 queries, memory leaks, unnecessary re-renders
├─ Test Agent: Coverage gaps, missing edge cases
├─ Architecture Agent: SOLID violations, separation of concerns
└─ Style Agent: Coding standards, naming, comment quality
Aggregation Agent:
→ Merge all reviews
→ Sort by severity (Critical / Major / Minor)
→ Output as GitHub PR comments
Results:
- Review time: Average 3.5 hours → Average 18 minutes
- Critical issue detection rate: 94% match with human reviewers
- Developer feedback: "Catching basic mistakes upfront lets human review focus on higher-level design discussions"
Chapter 6: Orchestration Design Best Practices
1. Draw the Dependency Graph Explicitly
Without a clear dependency graph, you'll accidentally serialize tasks that could run in parallel.
A(Data collection) --> C(Aggregated analysis)
B(Config loading) --> C
C --> D(Report generation)
C --> E(Alert generation)
A and B are independent → run in parallel. D and E are independent → run in parallel.
2. Right-Size Your Tasks
Too granular: overhead dominates and parallelization gains shrink. Too coarse: limited parallelization benefit.
Rule of thumb: Target 5–20 minutes per subagent task.
3. Define Intermediate Artifacts Upfront
Specify each agent's input and output format in advance. Ambiguous output formats make aggregation painful.
4. Scale Up Gradually
When first implementing orchestration, start with 3–5 agents. Once it's stable, increase from there.
5. Build In Progress Monitoring
For long-running orchestrations, have agents emit progress logs periodically so you can identify which are running slow.
Chapter 7: Common Failure Patterns and Fixes
Failure 1: Vague Subagent Instructions
Symptom: Subagents return unexpected outputs.
Fix: Include a concrete output example in your instructions. Not "Please do X" but "Please do X. Example output: [specific example]."
Failure 2: Parent Agent Context Overflow
Symptom: Receiving full outputs from many subagents bloats the parent's context window.
Fix: Have subagents return summaries, not full results. Store details in files and return only the path.
// Bad: Full text
"Analysis result: [5000 lines of data]"
// Good: Summary + path
"Analysis complete. Summary: 12 errors, 34 warnings. Details: /tmp/work/result_001.json"
Failure 3: Unhandled Race Conditions
Symptom: Multiple agents modify the same resource simultaneously, causing conflicts.
Fix: Partition resources (give each agent a clearly bounded scope) or designate the parent as the sole writer.
Failure 4: No Error Propagation Design
Symptom: A subagent fails silently and processing continues in a broken state.
Fix: Require all agents to include a success: true/false flag in their output, and have the parent always check it.
Conclusion: Enter the Next Stage of Development
Claude Code's subagent orchestration isn't just "more advanced automation" — it's a paradigm shift that lets individuals and small teams achieve development velocity that rivals much larger organizations.
The four patterns covered here — Fan-Out, Pipeline, Map-Reduce, and Specialist Delegation — are immediately applicable to real projects. Start small, with 3–5 agents on a simple task, then grow your orchestration capability from there.
The journey to unlocking the full power of AI agents is just beginning. Let's look at it together.
About Claude Lab Premium Membership
This article is published as a free taste of premium-quality content. Claude Lab premium members get articles at this level of depth 3 times every day.
What premium membership includes:
- In-depth practical guides on Claude Code, Claude API, and Cowork (3 articles/day)
- Complete guides to agent design and automation system architecture
- Code examples and prompt template collections exclusive to members
- Same-day coverage of new features (within 24 hours of Anthropic announcements)
Lifetime Premium: ¥1,480 / Pro Monthly: ¥280
One registration gives you permanent access to all content, including the full back catalog. For less than the price of a coffee, experience what it feels like when your work with Claude reaches the next level.