Claude Code Subagents: Optimization Guide

claude-code subagents optimization performance advanced best-practices

Performance Optimization Strategies

1. Token Usage Optimization

Subagents consume 3-4x more tokens than single-threaded operations. Here’s how to optimize:

// Token-efficient prompt structure
interface OptimizedPrompt {
  task: string;           // Concise task description
  context: string[];      // Only essential context
  constraints: string[];  // Clear boundaries
  output: string;        // Expected format
}
 
// Example: Optimized vs Unoptimized
const unoptimizedPrompt = `
Please analyze the entire authentication system including all files,
dependencies, tests, documentation, and provide a comprehensive report
about security vulnerabilities, performance issues, code quality...
[continues for 500+ words]
`;
 
const optimizedPrompt = `
Analyze auth module security:
- Check: SQL injection, XSS, CSRF
- Files: src/auth/*.ts only
- Output: List of vulnerabilities with severity
`;

2. Parallelism Optimization

Maximize efficiency with proper task distribution:

// Optimal parallelism patterns
const parallelismPatterns = {
  // Good: Independent tasks that can truly run in parallel
  optimal: `
    Task 1: Analyze /src/components
    Task 2: Analyze /src/services  
    Task 3: Analyze /src/hooks
    Task 4: Analyze /src/utils
  `,
  
  // Better: Let Claude decide parallelism level
  adaptive: `
    Analyze all source directories for memory leaks.
    Deploy multiple subagents as needed.
  `,
  
  // Avoid: Forced parallelism with dependencies
  suboptimal: `
    Task 1: Find all API calls
    Task 2: Analyze the API calls found in Task 1
    Task 3: Refactor based on Task 2 analysis
  `
};

3. Context Window Management

Each subagent has its own context window. Use this strategically:

// Context distribution strategy
interface ContextStrategy {
  mainAgent: {
    role: 'orchestrator';
    preserveFor: ['synthesis', 'decision-making', 'integration'];
  };
  subagents: {
    role: 'explorers';
    useFor: ['search', 'analysis', 'data-gathering'];
  };
}
 
// Example implementation
const contextOptimizedApproach = `
Main Agent Instructions:
1. Deploy subagents for exploration (preserves main context)
2. Receive summarized results
3. Make architectural decisions
4. Deploy new subagents for implementation
 
Subagent Instructions:
- Focus only on assigned directory/module
- Return structured summary (max 500 words)
- Include specific file:line references
`;

4. Batch Processing Optimization

Work around the batch processing limitation:

// Current limitation: Tasks wait for entire batch completion
// Optimization: Structure tasks to minimize wait times
 
const batchOptimization = {
  // Group by estimated completion time
  fastBatch: [
    'Check package.json',
    'List directory structure',
    'Count test files'
  ],
  
  slowBatch: [
    'Analyze entire codebase',
    'Generate documentation',
    'Run comprehensive tests'
  ],
  
  // Better: Mix fast and slow tasks
  balancedBatch: [
    'Quick file check',
    'Deep analysis of auth module',
    'List API endpoints',
    'Complex refactoring task'
  ]
};

5. Task Granularity Optimization

Find the sweet spot between too many small tasks and too few large ones:

// Task sizing guidelines
interface TaskSizing {
  tooSmall: {
    example: 'Read line 42 of file.ts';
    problem: 'Overhead exceeds benefit';
  };
  
  tooLarge: {
    example: 'Refactor entire application';
    problem: 'Loses parallelism benefit';
  };
  
  optimal: {
    example: 'Analyze and refactor auth module';
    characteristics: [
      '5-15 minutes estimated completion',
      'Clear, measurable output',
      'Independent execution possible'
    ];
  };
}
 
// Practical example
const wellSizedTasks = `
Feature: Shopping Cart Implementation
 
Task 1: Cart state management (Redux slice + tests)
Task 2: Cart UI components (3-4 components)  
Task 3: Cart API integration (2-3 endpoints)
Task 4: Cart persistence (localStorage/session)
Task 5: Cart calculations (tax, shipping, totals)
`;

6. Result Processing Optimization

Efficiently handle subagent outputs:

// Structured output format for easy processing
interface SubagentOutput {
  taskId: string;
  status: 'success' | 'partial' | 'failed';
  summary: string;  // Max 200 words
  details: {
    filesModified: string[];
    issuesFound: Issue[];
    recommendations: string[];
  };
  metrics: {
    filesScanned: number;
    timeElapsed: number;
    tokensUsed: number;
  };
}
 
// Example instruction for structured output
const structuredOutputPrompt = `
Return results in this format:
STATUS: success/partial/failed
SUMMARY: [50 words max]
FILES_MODIFIED: [list]
ISSUES: [severity:description]
METRICS: files=X time=Ys
`;

7. Error Handling and Recovery

Optimize for resilience:

// Robust task design
const resilientTaskPattern = `
Implement error recovery in subagents:
 
Each task should:
1. Validate inputs before processing
2. Handle missing files gracefully
3. Return partial results if possible
4. Include error details in output
5. Suggest alternative approaches
 
Example task with error handling:
"Find and analyze user.service.ts. If not found, search for 
similar files (*user*.ts, *service*.ts) and report findings."
`;

8. Caching and Reuse Patterns

Minimize redundant work across subagents:

// Shared resource optimization
const cachingStrategy = `
Before deploying subagents:
1. Create summary.md with discovered project structure
2. Have each subagent read summary.md first
3. Subagents append their findings to shared docs
4. Later subagents can skip already-analyzed areas
 
Task 1: Create project-structure.md
Task 2-5: Read project-structure.md, analyze assigned area
Task 6: Synthesize all findings from shared docs
`;

Performance Monitoring

Track and optimize subagent performance:

// Performance tracking pattern
interface PerformanceMetrics {
  totalTokens: number;
  parallelEfficiency: number;  // (1 / completion_time) * num_tasks
  contextUtilization: number;   // useful_output / total_context
  errorRate: number;           // failed_tasks / total_tasks
}
 
const performanceMonitoring = `
Include in each subagent prompt:
"Report: start time, end time, files processed, tokens estimate"
 
Main agent tracks:
- Total elapsed time
- Parallel speedup achieved
- Token usage per task type
- Success/failure rates
`;

Optimization Checklist

Before Using Subagents

  • Can this be done with direct tool usage?
  • Are tasks truly independent?
  • Is the complexity worth 3-4x token cost?
  • Have I minimized context per subagent?
  • Are outputs structured for easy processing?

During Execution

  • Monitor token usage trends
  • Check for subagent drift
  • Validate outputs are actionable
  • Ensure no duplicate work
  • Track completion times

After Completion

  • Measure actual vs expected performance
  • Identify bottlenecks
  • Refine task granularity
  • Update patterns based on results
  • Document lessons learned

Anti-Patterns to Avoid

  1. Context Bloat: Giving every subagent the entire project context
  2. Micro-Tasks: Creating subagents for trivial operations
  3. Serial Dependencies: Tasks that must wait for each other
  4. Vague Instructions: Subagents guessing at requirements
  5. No Success Criteria: Tasks without clear completion conditions

Advanced Optimization Techniques

Dynamic Task Scheduling

const dynamicScheduling = `
Start with 3 exploration tasks
Based on findings, spawn 2-7 implementation tasks
Adjust parallelism based on remaining context
`;

Progressive Refinement

const progressiveRefinement = `
Round 1: Broad analysis (5 subagents)
Round 2: Deep dive on problem areas (3 subagents)
Round 3: Targeted fixes (2 subagents)
`;

Hybrid Approaches

const hybridApproach = `
Use subagents for exploration
Use main agent for critical decisions
Use direct tools for simple operations
`;