Multi-Agent Orchestration Guide

Your comprehensive guide to implementing multi-agent systems in Claude Code. Learn how to orchestrate multiple agents for parallel processing, complex task decomposition, and team collaboration patterns.

Note: This guide focuses on practical implementation. For advanced architectural patterns and technical deep-dives, see the Multi-Agent Collaboration Patterns.

Quick Navigation

Table of Contents

  1. Understanding Subagents
  2. When to Use Multi-Agent Patterns
  3. Core Patterns
  4. Team Coordination
  5. Advanced Orchestration
  6. Best Practices
  7. Troubleshooting
  8. Examples and Templates

Understanding Subagents

What are Subagents?

Subagents in Claude Code are lightweight instances that run inside tasks, each with their own context window. They appear in the output as “Task(Performing task X)” and operate as independent Claude instances that can:

  • Run independently with their own context window
  • Use any tools that Claude Code can use (except spawning other sub-tasks)
  • Process tasks in parallel (up to 10 concurrent tasks)
  • Return results to the main orchestrator

Core Architecture

// Conceptual representation of subagent execution
interface SubagentTask {
  id: string;
  description: string;
  prompt: string;
  status: 'pending' | 'running' | 'completed';
  result?: string;
}
 
// Claude Code manages up to 10 concurrent subagents
const MAX_CONCURRENT_TASKS = 10;

When to Use Multi-Agent Patterns

✅ Ideal Use Cases

  1. Large Codebase Exploration

    • Investigating different directories or modules in parallel
    • Breadth-first search across complex systems
    • Finding patterns across multiple files
  2. Multi-Perspective Analysis

    • Security review + Performance analysis + Code quality assessment
    • Different “expert personas” examining the same code
    • Comprehensive architectural reviews
  3. Parallel Implementation Tasks

    • Creating multiple components simultaneously
    • Writing tests while implementing features
    • Updating documentation alongside code changes
  4. Complex Migrations

    • Converting multiple files to TypeScript
    • Updating API endpoints across services
    • Refactoring with consistent patterns

❌ When NOT to Use Subagents

  • Simple, sequential tasks
  • Tasks requiring extensive shared context
  • Operations needing precise ordering
  • When debugging specific issues

Core Patterns

1. The 7-Parallel-Task Pattern

Maximize parallelism for comprehensive feature development. This pattern launches up to 7 parallel tasks for implementing complete features.

See Full Implementation: View the complete shopping cart example and detailed usage in the Patterns Quick Reference

2. Map-Reduce Pattern

Process multiple items independently, then combine results. Ideal for analyzing multiple components or endpoints in parallel.

See Implementation: For code examples and detailed usage, see the Map-Reduce Pattern in Deep Dive

3. Pipeline Pattern

Sequential processing with parallel stages. Useful for multi-stage workflows where each stage can parallelize its work.

See Implementation: For the complete pipeline implementation with code examples, see the Pipeline Pattern in Deep Dive

4. Scatter-Gather Pattern

Distribute work and collect comprehensive results:

// Example: Comprehensive testing strategy
const scatterGatherPrompt = `
Scatter Phase - Create different test types:
Task 1: Unit tests for utility functions
Task 2: Integration tests for API endpoints
Task 3: Component tests for React components
Task 4: E2E tests for critical user flows
Task 5: Performance tests for data operations
 
Gather Phase: Consolidate into test suite with coverage report
`;

5. Expert Panel Pattern

Multiple specialized agents analyzing the same target from different expert perspectives.

See Full Pattern: View the complete expert panel implementation and examples in the Patterns Quick Reference

Team Coordination

Orchestrator-Worker Pattern

The most common pattern for Claude Code agent teams uses a hierarchical structure with a lead orchestrator managing specialized worker agents.

Architecture Details: For the complete orchestrator-worker implementation with configuration examples, see the Orchestrator Agent section in Deep Dive

GitHub Integration

Use GitHub for task distribution and coordination:

# .github/ISSUE_TEMPLATE/agent-task.yml
name: Agent Task
description: Task template for Claude Code agents
labels: ["agent-task"]
body:
  - type: dropdown
    attributes:
      label: Target Agent
      options:
        - Frontend Agent
        - Backend Agent
        - Test Agent
        - Any Available
  - type: textarea
    attributes:
      label: Task Description

Communication Protocols

Structure inter-agent communication:

interface AgentMessage {
  from: string;
  to: string | string[];
  type: 'task' | 'update' | 'query' | 'response';
  priority: 'low' | 'normal' | 'high' | 'critical';
  content: {
    subject: string;
    body: string;
    metadata?: Record<string, any>;
  };
  timestamp: Date;
}

Conflict Prevention

Implement ownership rules to prevent conflicts:

# .claude/ownership.yml
ownership:
  rules:
    - path: src/components/**
      owner: frontend-agent
      backup: ui-agent
    - path: api/**
      owner: backend-agent
      backup: api-agent
    - path: "**/*.test.ts"
      owner: test-agent
      shared: true

Advanced Orchestration

Dynamic Task Generation

// Discover and process dynamically
const dynamicPrompt = `
Phase 1 - Discovery:
Task 1: Find all React components in src/components
 
Phase 2 - Dynamic Processing:
Based on discovered components, create tasks to:
- Add TypeScript types to each component
- Create tests for components lacking coverage
- Update documentation for public APIs
`;

Hierarchical Decomposition

// Break down complex features
const hierarchicalPrompt = `
Main Task: Implement user authentication system
 
Level 1 Decomposition:
Task 1: Frontend - Login/Register UI
Task 2: Backend - Authentication API
Task 3: Database - User schema and migrations
 
Level 2 (Task 1 subtasks):
Task 1.1: Create login form component
Task 1.2: Create registration form component
Task 1.3: Implement form validation
Task 1.4: Add authentication context
`;

Conditional Orchestration

// Adaptive workflow based on findings
const conditionalPrompt = `
Initial Analysis:
Task 1: Scan codebase for deprecated patterns
 
Conditional Actions:
- If deprecated APIs found: Launch tasks to update each occurrence
- If security issues found: Create priority fix tasks
- If performance issues found: Create optimization tasks
 
Follow-up based on initial findings.
`;

Best Practices

1. Task Design

  • Keep tasks focused: Each subagent should have a single, clear objective
  • Minimize dependencies: Design tasks to run independently when possible
  • Provide clear context: Include necessary information in each task prompt
  • Specify output format: Tell subagents exactly what to return

2. Context Management

// Good: Self-contained task with context
const goodTask = `
Task: Update ProductCard component
Context: Located at src/components/ProductCard.tsx
Requirements:
- Add loading state with skeleton UI
- Use existing LoadingSpinner component
- Follow project's TypeScript conventions
- Update tests in ProductCard.test.tsx
`;
 
// Bad: Assumes shared context
const badTask = `
Task: Update the component we discussed
Make it better
`;

3. Error Handling

  • Design tasks to fail gracefully
  • Include validation steps
  • Plan for partial completion scenarios
  • Use the main agent to handle failures

4. Performance Optimization

  1. Batch Similar Operations

    Good: Task 1: Update all import statements in src/components
    Bad: 10 tasks to update individual imports
    
  2. Balance Granularity

    • Too fine: Overhead exceeds benefit
    • Too coarse: Loses parallelization advantage
  3. Consider Context Windows

    • Each subagent has its own context
    • Avoid tasks requiring extensive file reading

5. Communication Patterns

// Structured output format
const structuredTaskPrompt = `
Task: Analyze security vulnerabilities in auth module
 
Return results in this format:
{
  "vulnerabilities": [
    {
      "severity": "high|medium|low",
      "type": "vulnerability type",
      "location": "file:line",
      "description": "what was found",
      "recommendation": "how to fix"
    }
  ],
  "summary": "overall assessment"
}
`;

6. Load Balancing

Distribute tasks efficiently across agents:

// Dynamic load balancing
function balanceLoad(agents: Agent[], tasks: Task[]) {
  const agentLoad = new Map<string, number>();
  
  // Sort tasks by estimated complexity
  tasks.sort((a, b) => b.complexity - a.complexity);
  
  // Assign tasks to least loaded agents
  for (const task of tasks) {
    const agent = findLeastLoadedAgent(agents, agentLoad);
    agent.assignTask(task);
    agentLoad.set(
      agent.id, 
      (agentLoad.get(agent.id) || 0) + task.complexity
    );
  }
}

7. Monitoring and Observability

Track team performance:

interface TeamMetrics {
  activeAgents: number;
  tasksInProgress: number;
  tasksCompleted: number;
  averageTaskTime: number;
  conflictsResolved: number;
  performance: {
    throughput: number;  // tasks/hour
    efficiency: number;  // actual vs estimated time
  };
}

Troubleshooting

Common Issues

  1. Tasks Not Running in Parallel

    • Ensure using the Task tool properly
    • Check for sequential dependencies
    • Verify within 10-task limit
  2. Incomplete Results

    • Add explicit success criteria
    • Include validation steps
    • Check subagent prompts for clarity
  3. Context Confusion

    • Each subagent starts fresh
    • Pass all necessary context explicitly
    • Don’t assume shared knowledge

Debugging Strategies

// Add debug information to tasks
const debuggableTask = `
Task: Process user data
Debug: Log start time, file paths accessed, operations performed
Requirements: [actual task requirements]
Output: Include debug info in response
`;

Common Pitfalls and Solutions

1. Race Conditions

Problem: Multiple agents modifying the same file simultaneously. Solution: Implement file-level locking or use branch strategies.

2. Communication Overhead

Problem: Too much inter-agent communication slowing progress. Solution: Batch communications and use event-driven patterns.

3. Task Starvation

Problem: Some agents overwhelmed while others idle. Solution: Dynamic load balancing with work stealing.

4. Context Explosion

Problem: Sharing entire context with all agents. Solution: Share only necessary context relevant to each task.

Examples and Templates

Full Feature Implementation Template

const featureTemplate = `
Implement [FEATURE NAME] with parallel tasks:
 
Task 1 - API Design: Create OpenAPI spec for new endpoints
Task 2 - Database: Design schema and write migrations
Task 3 - Backend: Implement API endpoints with tests
Task 4 - Frontend: Create UI components with tests
Task 5 - Integration: Wire frontend to backend
Task 6 - Documentation: Update API docs and README
Task 7 - DevOps: Update CI/CD and deployment configs
 
Each task should follow project conventions and include tests.
`;

Codebase Analysis Template

const analysisTemplate = `
Comprehensive analysis of [MODULE/FEATURE]:
 
Task 1 - Structure: Map architecture and dependencies
Task 2 - Quality: Run linting, find code smells
Task 3 - Security: Identify vulnerabilities
Task 4 - Performance: Find bottlenecks
Task 5 - Testing: Assess coverage and quality
Task 6 - Documentation: Check completeness
 
Synthesize findings into actionable recommendations.
`;

Core Documentation

Advanced Patterns

External Resources