Lesson 9 of 9 8 minAI Builder

Claude Code Lesson 6: Multi-Agent Orchestration — Delegating Complex Tasks to Subagents

Go beyond single-session tasks. Learn how to design multi-agent workflows where a coordinator agent delegates to specialized subagents, enabling parallel execution across large codebases.

Reading Mode

Hide the curriculum rail and keep the lesson centered for focused reading.

Premium outcome

From AI curiosity to agentic engineering workflows that actually ship.

Developers building agentic workflows, local AI tooling habits, and modern developer-experience systems.

What you unlock

  • A concrete workflow for research, strategy, execution, and validation with AI agents
  • Safer operating habits around rules, secrets, tool use, and repo-level context management
  • A stronger sense for where agentic coding improves speed versus where human judgment matters most

From Single Agent to an Engineering Team

Mental Model

Running a single Claude Code session on a large task is like asking one developer to do everything solo. Multi-agent orchestration is like running a well-managed sprint: a tech lead coordinates, specialists focus, and the work gets done faster with higher quality.

When a task exceeds a few hundred lines of changes, spans multiple subsystems, or requires research and implementation to happen simultaneously, a single Claude Code session hits its limits:

  1. Context saturation: The context window fills with research and previous edits, reducing accuracy
  2. Sequential bottleneck: One agent can only do one thing at a time
  3. Error propagation: A mistake early in a long session affects all subsequent reasoning

Multi-agent orchestration solves all three problems.


The Core Pattern: Coordinator → Specialist

The most reliable multi-agent pattern has a Coordinator agent that understands the full task, breaks it down, and delegates to Specialist agents that have narrow, well-scoped jobs.

Coordinator Agent
├── Specialist: Research (reads codebase, never writes)
├── Specialist: Implementation A (works on auth module)
├── Specialist: Implementation B (works on payment module)
└── Specialist: Verification (runs tests, linting, type checking)

Each specialist has:

  • A focused role description that defines what it does
  • An explicit scope (which directories/files it can touch)
  • A clear output format (what it reports back to the coordinator)

Designing the Coordinator Prompt

The coordinator's system prompt must include the full architectural context and the delegation strategy:

You are the Engineering Coordinator for a payment system refactor.

## Your Job
1. Break the overall task into discrete sub-tasks
2. Delegate each sub-task to a specialist via the invoke_subagent tool
3. Collect and validate results before declaring the task complete
4. Handle inter-dependencies: Task B must not start until Task A is verified

## The Full Task
Migrate our Stripe Charges API implementation to Stripe PaymentIntents API.
Affected services: CheckoutService, WebhookHandler, RefundService.

## Delegation Strategy
- Step 1: Research Agent → map all Charges API usages. Report findings before proceeding.
- Step 2: Implementation Agents A & B (can run in parallel after Step 1)
  - Agent A: Migrate CheckoutService only
  - Agent B: Migrate WebhookHandler only
- Step 3: Verification Agent → run full test suite, report results
- Step 4: If tests pass, generate a migration summary report

## Non-Negotiables
- No agent may touch database migrations or CI/CD configuration
- No agent may run git commit or git push
- If any agent fails, halt and report to human

Implementing Subagents in Practice

Pattern 1: Research-Only Subagent

Use this for the investigation phase. It reads but never writes:

SPECIALIST ROLE: Research Agent

Your task is to map all usages of the deprecated Stripe Charges API.

SCOPE: Read-only access to src/services/ and src/api/ directories.
You may not modify any files.

REQUIRED OUTPUT (JSON format):
{
  "files_affected": ["path/to/file.ts", ...],
  "usage_count": 42,
  "patterns_found": ["stripe.charges.create", "stripe.charges.retrieve"],
  "risks": ["StripeService.ts has 15 usages, will need careful migration"],
  "estimated_complexity": "medium"
}

Report this JSON when done. Do not proceed beyond research.

Pattern 2: Scoped Implementation Subagent

Each implementation agent has a strict file scope:

SPECIALIST ROLE: Implementation Agent — CheckoutService

Your task: Migrate CheckoutService.ts from Stripe Charges to PaymentIntents.

PERMITTED FILES (you may ONLY read/write these):
- src/services/CheckoutService.ts
- src/services/CheckoutService.test.ts
- src/types/stripe.types.ts (read-only)

FORBIDDEN: Do not touch WebhookHandler, RefundService, or any other file.

MIGRATION RULES (from the research agent):
- Replace stripe.charges.create() with stripe.paymentIntents.create()
- Replace status: 'succeeded' checks with status === 'succeeded' && payment_method_attached
- All PaymentIntent IDs start with 'pi_' instead of 'ch_'

VALIDATION STEP: After making changes, run:
  npx ts-node -e "require('./src/services/CheckoutService')"
This verifies the module loads without TypeScript errors.

Report back: list of changed lines, any ambiguities encountered.

Pattern 3: Verification Subagent

Never start this until all implementation agents finish:

SPECIALIST ROLE: Verification Agent

All implementation agents have completed. Your job is quality assurance only.

TASKS (in order):
1. Run `npx tsc --noEmit` — report any TypeScript errors
2. Run `npm run lint` — report any lint errors  
3. Run `npm test -- --testPathPattern="checkout|webhook|refund"` — report failures
4. Verify that no 'ch_' prefixed strings remain in the changed files
5. Check that each changed file has at least one updated test

SCOPE: Read-only for all source files. You may run shell commands.
DO NOT make any file edits. Report findings only.

Visualizing the Orchestration Flow

sequenceDiagram participant H as Human participant C as Coordinator participant R as Research Agent participant A as Impl Agent A participant B as Impl Agent B participant V as Verification Agent
H->>C: "Migrate Stripe Charges to PaymentIntents"
C->>R: Delegate: Map all usages
R-->>C: Report: 3 files, 42 usages, medium complexity

par Parallel Implementation
    C->>A: Delegate: Migrate CheckoutService
    C->>B: Delegate: Migrate WebhookHandler
end

A-->>C: Done: 15 lines changed, 0 ambiguities
B-->>C: Done: 8 lines changed, 1 question

C->>H: Agent B has a question about error handling
H->>C: Use the existing error handling pattern

C->>V: Delegate: Run full test suite
V-->>C: 47 tests passed, 0 failures, 0 lint errors

C->>H: Migration complete. Summary report attached.

Common Pitfalls and How to Avoid Them

Pitfall 1: Agents Stomping Each Other's Work

Problem: Two agents writing to the same file simultaneously creates conflicts.

Solution: The coordinator must enforce strict file ownership:

Agent A owns: src/services/CheckoutService.ts
Agent B owns: src/api/WebhookHandler.ts
Shared types file: src/types/stripe.types.ts — READ ONLY for both

Pitfall 2: Context Leakage Between Agents

Problem: Implementation Agent B accidentally applies research findings meant for Agent A.

Solution: Each specialist prompt must be fully self-contained. Never say "as we discussed" — always repeat the relevant context inline.

Pitfall 3: Verification Gaps

Problem: Each agent validates its own work, but nobody checks cross-cutting concerns.

Solution: Always run a dedicated Verification Agent that knows nothing about the implementation details. Its job is purely adversarial — find what the implementation agents missed.

Pitfall 4: Unbounded Scope Creep

Problem: An implementation agent sees a related bug and "helpfully" fixes it.

Solution: Include an explicit "Forbidden Actions" list in every specialist prompt:

FORBIDDEN:
- Do not fix any bugs not listed in this task
- Do not refactor code that is not directly related to the migration
- Do not update dependencies

When to Use Multi-Agent vs Single-Agent

Scenario Single Agent Multi-Agent
Fix a single bug in one file Overkill
Add a new API endpoint Overkill
Migrate authentication across 5 services
Research + implementation + testing
Large-scale refactor (>500 lines)
Parallel work on independent subsystems

Rule of thumb: If the task requires more than 3 distinct phases of work, or touches more than 2 independent subsystems, reach for multi-agent orchestration.


Building a Reusable Orchestration Template

Save this template in CLAUDE.md for your complex tasks:

## Multi-Agent Task Template

### Phase 1: Research
Delegate to a read-only research agent. Required output:
- Files affected (paths)
- Estimated complexity (low/medium/high)
- Risks and dependencies
- Questions that need human clarification

### Phase 2: Human Checkpoint
Review the research output before implementation begins.
Clarify any ambiguities. Approve the plan.

### Phase 3: Parallel Implementation
Each agent gets:
- A file ownership list (no overlap)
- A validation command to run after its changes
- Specific "forbidden" actions

### Phase 4: Verification
A fresh agent runs the full test suite and reports.

### Phase 5: Summary Report
Coordinator generates a change log with:
- Lines changed per file
- Tests added or updated
- Any remaining risks or follow-up work

Key Takeaways

  • The Coordinator → Specialist pattern mirrors how senior engineers delegate to focused team members.
  • Subagents have isolated context windows — preventing cross-contamination is the key benefit of delegation.
  • Always scope subagents with explicit boundaries: which files they can touch and what they must report back.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.