Back to modules
Module 7

Multi-Agent Orchestration

Master parallel agents, agent teams, coordination patterns, and worktree isolation for complex autonomous systems.

šŸ“– 35 min
Parallel AgentsAgent TeamsCoordination PatternsWorktrees

Parallel Subagents (SDK Pattern)

How Parallelization Works

python
from concurrent.futures import ascompleted

import asyncio

agents = {

"securityreviewer": 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)
  • Performance analysis (different agent)
  • Test validation (third agent)
  • All happen at once
  • Don't parallelize:

  • Feature A development (takes 10 min)
  • Feature A's unit tests (depends on Feature A)
  • These are sequential
  • Real Example: Code Review Workflow

    python
    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:

    json
    {

    "env": {

    "CLAUDECODEEXPERIMENTALAGENTTEAMS": "1"

    }

    }

    Then in Claude Code CLI:

    bash
    $ 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

  • Create — Describe team and tasks
  • Distribute — Tasks added to shared list
  • Agents claim — Each agent picks available task
  • Work independently — Each agent does their task
  • Communicate — Agents message each other as needed
  • Lead synthesizes — Results assembled at end
  • Team Workflow

    plaintext
    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:

    plaintext
    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

    plaintext
    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

    plaintext
    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

    plaintext
    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

    plaintext
    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:

    bash

    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:

  • Two separate file systems (no conflicts)
  • Two separate Claude Code sessions
  • Both can work simultaneously
  • Pull requests from each worktree independently
  • When to use:

  • Large refactors
  • Long-running parallel features
  • Multiple people working simultaneously
  • ---

    Choosing the Right Pattern

    Use Subagents (SDK) When:

  • āœ“ Tasks are independent but short
  • āœ“ Results feed back to main agent
  • āœ“ Main agent makes final decisions
  • āœ“ Want context isolation for efficiency
  • Use Agent Teams (CLI) When:

  • āœ“ Tasks are large and independent
  • āœ“ Agents need to work autonomously
  • āœ“ Agents should communicate peer-to-peer
  • āœ“ Less supervision needed
  • Use Worktrees When:

  • āœ“ Completely separate code changes
  • āœ“ Want isolated test suites
  • āœ“ Multiple people working
  • āœ“ Need separate git histories
  • ---

    Gotchas

    Gotcha #1: File conflicts with parallel agents

  • Two agents editing same file = overwrites
  • Assign different files per agent
  • Use locking if necessary
  • Gotcha #2: Context grows in teams

  • Each agent has full context
  • 5 agents = ~5x token usage
  • Budget carefully
  • Gotcha #3: Team communication is eventual

  • Messages aren't instant
  • Design for asynchronous coordination
  • Don't expect immediate responses
  • Gotcha #4: Parallelization has overhead

  • Spawning agents takes time
  • Very short tasks may not benefit
  • Measure to see if it helps
  • Gotcha #5: Agent teams are experimental

  • Syntax may change
  • Some limitations (no resume, etc)
  • Check docs for latest status
  • ---

    Production Example: Refactoring Project

    python

    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

    PatternBest ForAgents
    ------------------------------------
    SubagentsShort independent tasks2-5Main agent decides
    Agent TeamsLarge autonomous work3+Self-coordinating
    WorktreesSeparate projectsHumans + AgentsIndependent sessions

    ---

    Next Steps

    You've mastered multi-agent coordination. Final module: Production Patterns — deploying agents at scale!