Parallel Subagents (SDK Pattern)
How Parallelization Works
from concurrent.futures import ascompleted
import asyncio
agents = {
"security
reviewer": AgentDefinition(...),
"performanceanalyst": AgentDefinition(...),
"testvalidator": AgentDefinition(...)
}
All agents work on same codebase in parallel
async for message in query(
prompt="Audit auth.ts: review security, analyze performance, validate tests",
options={"agents": agents}
):
# Claude decides to use all 3 agents
# Each runs in parallel on their task
if isinstance(message, ResultMessage):
print(f"Security issues: {message.result}")
Best For Parallelization
Yes, parallelize:
- Security review (one agent)
Don't parallelize:
Real Example: Code Review Workflow
async for message in query(
prompt="""Review the new authentication module:
1. Security reviewer: audit for vulnerabilities
2. Performance reviewer: check for bottlenecks
3. Style reviewer: verify it matches code style
4. Test reviewer: confirm tests are comprehensive
""",
options={
"agents": {
"securityreviewer": securityagent,
"performancereviewer": perfagent,
"stylereviewer": styleagent,
"testreviewer": testagent
}
}
):
if isinstance(message, ResultMessage):
print(message.result)
# Output might be:
# Security: Found 2 issues with password hashing
# Performance: No bottlenecks found
# Style: Follows conventions
# Tests: 95% coverage, good!
---
Agent Teams (CLI Pattern)
Agent teams enable large-scale autonomous work. Enable with:
{
"env": {
"CLAUDECODEEXPERIMENTALAGENTTEAMS": "1"
}
}
Then in Claude Code CLI:
$ claude "Create an agent team to refactor the database layer.
Spawn an architect to design changes,
an implementer to code them,
and a reviewer to validate."
How Teams Work
Team Workflow
Lead: "We need to migrate the payment processor from Stripe to PayPal"
Creates team with tasks:
ā” Research PayPal API and authentication
ā” Design new payment flow
ā” Implement new PayPal integration
ā” Migrate existing payment records
ā” Write integration tests
ā” Update documentation
Team members:
Architect: Takes "Design new payment flow"
Developer: Takes "Implement new PayPal integration"
QA: Takes "Write integration tests"
...they work in parallel...
Results come back to Lead
Inter-Agent Communication (SendMessage)
Agents can message each other:
Developer: "I'm implementing the PayPal integration.
@Architect, can you clarify the retry logic for failed charges?"
Architect: "@Developer, for failed charges:
1. Retry up to 3 times with exponential backoff
2. Log each failure
3. Alert admin after 3 failures"
Developer: "Got it, implementing now..."
---
Coordination Patterns
Pattern 1: Fork & Join
Main agent:
"I need to solve this problem"
Forks:
āā Agent A: "Try approach 1"
āā Agent B: "Try approach 2"
āā Agent C: "Try approach 3"
Joins:
Approach 1 result
Approach 2 result
Approach 3 result
Main: "Approach 2 is best because..."
Use for: Comparing different solutions, A/B testing approaches
Pattern 2: Pipeline
Input ā Agent A ā Agent B ā Agent C ā Output
Example:
Raw log data ā Parser agent ā Analyzer agent ā Report agent ā Summary
Use for: Sequential processing, each step depends on previous
Pattern 3: Map-Reduce
Data chunks:
[Chunk 1] ā Agent A (parallel)
[Chunk 2] ā Agent B (parallel)
[Chunk 3] ā Agent C (parallel)
Results ā Aggregator agent ā Final summary
Use for: Processing large datasets in parallel
Pattern 4: Hierarchical
Lead agent
āā Team A (3 agents): Works on Feature A
āā Team B (3 agents): Works on Feature B
āā Team C (2 agents): Works on Integration
Lead coordinates across teams
Use for: Large projects with multiple workstreams
---
Worktree Isolation (CLI Only)
For truly parallel work in Claude Code CLI, use Git worktrees:
Terminal 1: Work on feature-a
$ cd cc-agents
$ git worktree add ../cc-agents-feature-a feature-a
$ cd ../cc-agents-feature-a
$ claude "Implement user authentication"
Terminal 2: Work on feature-b (different directory)
$ cd cc-agents
$ git worktree add ../cc-agents-feature-b feature-b
$ cd ../cc-agents-feature-b
$ claude "Implement payment processing"
Benefits:
When to use:
---
Choosing the Right Pattern
Use Subagents (SDK) When:
Use Agent Teams (CLI) When:
Use Worktrees When:
---
Gotchas
Gotcha #1: File conflicts with parallel agents
Gotcha #2: Context grows in teams
Gotcha #3: Team communication is eventual
Gotcha #4: Parallelization has overhead
Gotcha #5: Agent teams are experimental
---
Production Example: Refactoring Project
Scenario: Refactor authentication from JWT to OAuth2
async for message in query(
prompt="""Lead a multi-agent refactoring:
1. Researcher: Investigate current JWT implementation,
identify all files that use it
2. Designer: Design OAuth2 integration, write migration plan
3. Implementer: Code the OAuth2 provider integration
4. Migrator: Move existing JWT auth to OAuth2
5. Tester: Write integration tests for new auth
6. Reviewer: Verify no regressions, performance is good
Coordinate to complete all work in parallel where possible.
""",
options={
"agents": {
"researcher": researcheragent,
"designer": designeragent,
"implementer": implementeragent,
"migrator": migratoragent,
"tester": testeragent,
"reviewer": revieweragent
}
}
):
if isinstance(message, ResultMessage):
print(message.result)
---
Summary
| Pattern | Best For | Agents | |
|---|---|---|---|
| --------- | ---------- | -------- | --------- |
| Subagents | Short independent tasks | 2-5 | Main agent decides |
| Agent Teams | Large autonomous work | 3+ | Self-coordinating |
| Worktrees | Separate projects | Humans + Agents | Independent sessions |
---
Next Steps
You've mastered multi-agent coordination. Final module: Production Patterns ā deploying agents at scale!