On this page
Lesson 16 of 30

Lesson 15: Parallelization

Why This Matters

A single Claude session is powerful, but real-world development often demands working on multiple things at once. Claude Code offers three distinct parallelization mechanisms --- subagents within a session, agent teams across sessions, and headless mode for scripted automation. Understanding when and how to use each one can turn hour-long tasks into minutes.


The Three Levels of Parallelism

Before diving into details, here is the mental model:

Level Mechanism What It Does
Within a session Subagents (Task tool) Claude spawns child agents that work in parallel inside your conversation
Across sessions Agent teams / Multi-Claude Multiple independent Claude instances coordinate on shared tasks
Non-interactive Headless mode (-p flag) Claude runs from scripts, CI/CD, or pipelines with no human in the loop

Each level builds on the previous one. Most developers start with subagents, graduate to multi-session workflows for large features, and eventually wire Claude into their CI/CD with headless mode.


Subagents: Parallel Work Within a Session

When Claude encounters a task that benefits from delegation, it can spawn subagents --- child agents that each run in their own context window with their own tools and system prompt. The parent waits for results and synthesizes them.

How It Works

Ask Claude to do multiple independent things at once:

I need you to do these three things in parallel:
1. Search for all files that import from `utils/crypto`
2. Check if we have any tests for the crypto module
3. Read the CHANGELOG for recent crypto-related changes

Then combine your findings.

Claude launches subagents for each task and reports back when all are done. You can also be explicit:

Use separate subagents to investigate each of these modules in parallel.

Built-In Agent Types

Claude Code ships with several built-in subagents that it delegates to automatically:

Agent Model Purpose
Explore Haiku (fast, cheap) Read-only codebase search and analysis. Claude uses this when it needs to look around without modifying anything.
Plan Inherits from parent Research agent for plan mode. Gathers context before presenting a plan to you.
General-purpose Inherits from parent Complex multi-step tasks that require both reading and writing.
Bash Inherits from parent Running terminal commands in a separate context.

The Explore agent is especially useful --- it runs on Haiku, which is roughly 60x cheaper than Opus, so codebase exploration stays fast and inexpensive.

Creating Custom Subagents

You can define your own subagents as Markdown files with YAML frontmatter. Store them in .claude/agents/ (project-level) or ~/.claude/agents/ (user-level):

Markdown
---
name: test-fixer
description: Finds and fixes failing tests. Use proactively after code changes.
tools: Read, Edit, Bash, Grep, Glob
model: sonnet
---

You are a test specialist. When invoked:
1. Run the test suite
2. Identify failing tests
3. Read the relevant source code
4. Fix the failures
5. Re-run to verify

Use the /agents command inside Claude Code for an interactive setup experience, or create files manually.

Worktree Isolation for Subagents

When subagents modify files in parallel, they can collide. The isolation: worktree option gives each subagent its own copy of the repository via a Git worktree:

Markdown
---
name: refactor-worker
description: Refactors a module in an isolated worktree
tools: Read, Edit, Bash, Grep, Glob
isolation: worktree
---

Refactor the specified module. You are working in an isolated worktree,
so your changes will not conflict with other agents.

When the subagent finishes:

  • If it made no changes, the worktree is automatically cleaned up
  • If it made changes or commits, the worktree is preserved so you can review and merge

You can also ask Claude directly: "Use worktrees for your agents."

Foreground vs Background Subagents

  • Foreground subagents block your conversation until they finish. Permission prompts pass through to you normally.
  • Background subagents run concurrently while you keep working. Claude pre-approves the permissions they will need before launching them.

You can configure a subagent to always run in the background:

YAML
---
name: test-runner
description: Runs the test suite in the background
background: true
tools: Bash, Read
---

Or just ask Claude: "Run the tests in the background while you implement the next feature."

Press Ctrl+B to send a running foreground task to the background.

Subagent Best Practices

  • Keep subagents focused. Each one should excel at one specific task.
  • Write clear descriptions. Claude uses the description field to decide when to delegate.
  • Limit tool access. A read-only reviewer does not need the Edit tool.
  • Use Haiku for exploration. Set model: haiku for search and analysis tasks to save cost.
  • Check them into version control. Project-level subagents in .claude/agents/ let your whole team benefit.

Agent Teams: Multiple Claude Instances Working Together

Agent teams are experimental. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings or environment.

While subagents work within a single session (results flow back to the parent), agent teams are fully independent Claude Code instances that coordinate through a shared task list and direct messaging.

When to Use Teams vs Subagents

Subagents Agent Teams
Context Own context, results return to caller Fully independent context
Communication Report back to parent only Teammates message each other directly
Coordination Parent manages everything Shared task list with self-coordination
Best for Focused tasks where only the result matters Complex work requiring discussion and collaboration
Token cost Lower (results summarized back) Higher (each teammate is a separate instance)

Use subagents for quick, focused delegation. Use agent teams when workers need to share findings, challenge each other's conclusions, and coordinate on their own.

Starting a Team

Tell Claude what you need and describe the team structure:

Create an agent team to refactor the payment system:
- One teammate handles the API layer
- One handles the database migrations
- One handles the test suite
Each should work in their own worktree to avoid conflicts.

Claude creates the team, spawns teammates, assigns tasks, and synthesizes results when everyone finishes.

Interacting with Teammates

  • In-process mode (default): all teammates run in your terminal. Press Shift+Down to cycle between them.
  • Split-pane mode: each teammate gets its own tmux or iTerm2 pane. Set "teammateMode": "tmux" in settings.

You can message any teammate directly to give additional instructions or redirect their approach.


Git Worktrees for Manual Parallelism

Even without agent teams, you can run multiple Claude sessions in parallel using the --worktree (-w) flag:

Bash
# Terminal 1: work on authentication
claude --worktree feature-auth

# Terminal 2: fix a bug independently
claude --worktree bugfix-123

# Terminal 3: auto-generate a name
claude --worktree

Each worktree gets its own directory at <repo>/.claude/worktrees/<name> with its own branch (worktree-<name>), so changes never collide. When you exit:

  • No changes: worktree and branch are removed automatically
  • Changes exist: Claude asks whether to keep or remove the worktree

Add .claude/worktrees/ to your .gitignore to keep things clean.


Headless Mode: Non-Interactive Claude

The -p (or --print) flag runs Claude without an interactive session. This is the foundation for scripted usage, CI/CD integration, and automation pipelines.

Basic Usage

Bash
# Ask a question, get an answer, exit
claude -p "What does the auth module do?"

# Pipe input for analysis
cat build-error.txt | claude -p "Explain the root cause of this build error"

Structured Output

Bash
# JSON output with session metadata
claude -p "Summarize this project" --output-format json

# Streaming JSON for real-time processing
claude -p "Explain recursion" --output-format stream-json

# Schema-validated JSON for structured extraction
claude -p "Extract function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}}}'

Auto-Approving Tools

In headless mode, Claude cannot prompt you for permission. Use --allowedTools to pre-approve specific tools:

Bash
claude -p "Run tests and fix failures" \
  --allowedTools "Bash,Read,Edit"

For CI/CD where no human is available at all, --dangerously-skip-permissions bypasses every permission check. Use this only in sandboxed environments:

Bash
claude -p "Run the linter and fix all warnings" \
  --dangerously-skip-permissions

Continuing Conversations

Bash
# First request
claude -p "Review this codebase for performance issues"

# Continue the most recent conversation
claude -p "Now focus on the database queries" --continue

# Capture and resume a specific session
session_id=$(claude -p "Start a review" --output-format json | jq -r '.session_id')
claude -p "Continue that review" --resume "$session_id"

Practical Patterns

Pattern 1: Parallel Test Fixing

Ask Claude to use subagents to fix multiple failing tests simultaneously:

Run the test suite. For each failing test file, spawn a subagent
to diagnose and fix it. Use worktree isolation so fixes don't conflict.

Pattern 2: Multi-File Refactoring with Worktrees

Open multiple terminals and use --worktree to tackle different parts of a refactor in parallel:

Bash
# Terminal 1
claude -w refactor-api
> Migrate all API handlers to the new error types

# Terminal 2
claude -w refactor-services
> Migrate all service files to the new error types

# Terminal 3
claude -w refactor-tests
> Update all test files for the new error types

Each session works on its own branch. When done, merge them sequentially.

Pattern 3: CI/CD Integration with Headless Mode

Add Claude as a code reviewer in your CI pipeline:

YAML
# .github/workflows/claude-review.yml
name: Claude Code Review
on: [pull_request]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run Claude review
        run: |
          gh pr diff ${{ github.event.pull_request.number }} | \
            claude -p "Review this diff for bugs, security issues, and style problems. Output a summary." \
            --output-format json \
            --dangerously-skip-permissions \
            > review.json

Pattern 4: Code Review Pipeline

Chain headless Claude invocations for a multi-pass review:

Bash
#!/bin/bash
# review-pipeline.sh

# Pass 1: Security review
claude -p "Review this codebase for security vulnerabilities" \
  --allowedTools "Read,Grep,Glob" \
  --output-format json > security-review.json

# Pass 2: Performance review (continue same session)
claude -p "Now review for performance issues" \
  --continue \
  --allowedTools "Read,Grep,Glob" \
  --output-format json > perf-review.json

# Pass 3: Synthesize findings
cat security-review.json perf-review.json | \
  claude -p "Combine these review findings into a single prioritized report" \
  --output-format text > final-report.txt

Pattern 5: Research-Then-Implement

Split work into a cheap exploration phase and a focused implementation phase:

Phase 1 (parallel subagents, read-only):
- Subagent 1: Map out the payment service architecture
- Subagent 2: Read the Stripe webhook documentation
- Subagent 3: Check our existing webhook infrastructure

Phase 2 (focused, informed):
Based on the research, implement the Stripe webhook handler.

Phase 1 uses the Explore agent (Haiku, read-only) and costs very little. Phase 2 is fast because Claude already knows the codebase.


When NOT to Parallelize

Some work is inherently sequential. Recognize these patterns:

Must be sequential:

  • Run tests, see failures, fix them, run tests again
  • Read a file, understand it, then edit it
  • Create a database migration, run it, then update the code

Safe to parallelize:

  • Read file A AND read file B (independent reads)
  • Write test file AND write implementation file (independent writes)
  • Run linter AND run type checker (independent validations)
  • Explore module A AND explore module B (independent research)

Signs you should NOT parallelize:

  • Tasks share the same files (merge conflicts)
  • Task B depends on the output of Task A
  • The problem is poorly understood (explore first, parallelize later)
  • The task is small enough that coordination overhead exceeds time saved

Quick Reference

I want to... Use...
Speed up exploration of a large codebase Subagents (Explore agent, runs on Haiku)
Fix multiple failing tests at once Subagents with isolation: worktree
Work on two features simultaneously claude --worktree feature-a in separate terminals
Run Claude in CI/CD claude -p "prompt" --dangerously-skip-permissions
Get structured output for scripts claude -p "prompt" --output-format json
Coordinate complex multi-agent work Agent teams (experimental)
Run a long task without blocking Background subagents or Ctrl+B

Practical Exercise

Pick a project with a test suite that has at least a few failures (or intentionally break some tests). Then:

  1. Ask Claude to run the test suite and identify all failures
  2. Ask it to fix the failures in parallel using subagents with worktree isolation
  3. Observe how it spawns agents, isolates work, and merges results
  4. Compare the wall-clock time to fixing them one-by-one

For a more advanced exercise, set up a simple headless pipeline:

Bash
# Run Claude non-interactively to generate a review
claude -p "Review the src/ directory for common code smells" \
  --allowedTools "Read,Grep,Glob" \
  --output-format json | jq -r '.result'

This gives you a feel for how Claude fits into automated workflows beyond the interactive terminal.