Claude Code can spawn sub-agents — isolated Claude sessions that run tasks in parallel while you (or your orchestrator) continue working on something else. The result: instead of waiting for one long task to finish before starting the next, you can run four tasks simultaneously and collect the results.

This is one of the most powerful things Claude Code can do, and it's surprisingly underused. Most developers don't know sub-agents exist. Those who do often set them up wrong — and end up with parallel agents that step on each other's work.

This guide covers how sub-agents actually work, when to use them (and when not to), how to structure your CLAUDE.md so they behave correctly, and the patterns that make parallel AI workflows reliable in production.

What are Claude Code sub-agents?

A Claude Code sub-agent is a separate Claude session that your main (orchestrator) session spawns to run an isolated task. Sub-agents can:

  • Read files, search the codebase, run shell commands
  • Write files and make code changes
  • Call the same tools your main session has access to
  • Return results back to the orchestrator when done

The key word is isolated. Sub-agents don't share context with each other or with the parent session. Each one starts fresh with a specific task, a set of allowed tools, and whatever files you point it at.

Think of it like Git branches for AI work: you're running multiple workstreams in parallel that can later be merged by the orchestrator.

How it looks in practice

You tell Claude: "Review all 12 service files for security issues. Do them in parallel." Claude spawns 12 sub-agents simultaneously — one per file — and returns a consolidated report when all are done. Wall-clock time: same as reviewing one file. Total work: 12x.

When to use parallel agents (and when not to)

Sub-agents shine in specific situations. They're overkill (or actively harmful) in others.

Scenario Sub-agents? Why
Auditing multiple independent files Yes No shared state, perfect parallelism
Writing tests for multiple modules Yes Each module is independent; tests don't conflict
Researching multiple API docs simultaneously Yes Read-only, fully parallelizable
Refactoring that touches a shared module No Agents will overwrite each other's changes
Tasks with sequential dependencies No Task B needs Task A's output — not parallelizable
Database migrations No Order matters; parallel execution causes conflicts
Generating multiple independent content pieces Yes Blog posts, docs, summaries — no conflicts
Debugging a complex multi-file bug Sometimes Use one agent per hypothesis, not one per file

The rule: if tasks don't share mutable state, parallelize. If they do, don't.

How sub-agents actually work

When you ask Claude Code to spawn a sub-agent, here's what happens under the hood:

Orchestrator (your main session)
   │
   ├── spawn_agent("Audit auth.js for SQL injection")
   ├── spawn_agent("Audit payments.js for SQL injection")
   ├── spawn_agent("Audit users.js for SQL injection")
   │
   │       [all 3 run in parallel]
   │
   └── collect_results() → consolidated report

Each sub-agent:

  • Gets its own context window (starts empty, not inheriting parent context)
  • Receives a task prompt from the orchestrator
  • Can be given a specific set of tools (you can restrict what sub-agents can do)
  • Runs until it finishes or hits an error
  • Returns output back to the parent
Important: sub-agents don't share context

A sub-agent does NOT know what other sub-agents are doing. It doesn't know what the parent session's conversation history is. It only knows what you put in its task prompt. Design your tasks so that everything a sub-agent needs is included in the task description.

CLAUDE.md setup for multi-agent workflows

This is where most teams get it wrong. They set up CLAUDE.md for their main workflow but forget that sub-agents also read it — and that sub-agents need different guardrails than the main session.

Here's a production-tested CLAUDE.md setup for teams using sub-agents:

# CLAUDE.md — Project Rules

## Architecture
- Monorepo: /apps (services), /packages (shared libs), /infra (terraform)
- Node 20, TypeScript strict mode, Postgres 16
- Never import from /apps/* → /apps/* (services are isolated)

## Code Standards
- All new functions must have JSDoc
- Tests go in __tests__/ next to source file
- Errors use Result<T, E> pattern — never throw in business logic
- No console.log in production code — use logger.info()

## Sub-Agent Rules
- If you are a sub-agent, announce your task at the start of your output
- Sub-agents MUST NOT modify files outside the scope given in your task
- Sub-agents MUST NOT run npm install or change package.json
- Sub-agents MUST NOT create new branches or commit to git
- Sub-agents: end output with a summary block in this format:
  RESULT: [one-line summary]
  FILES_CHANGED: [comma-separated list or NONE]
  ISSUES_FOUND: [count]

## Dangerous Operations (require explicit confirmation)
- Deleting files
- Dropping database tables
- Modifying environment files (.env, .env.production)
- Any operation touching /infra/

The Sub-Agent Rules section is the critical addition. Without it, sub-agents have no idea they're operating in a parallel context and may:

  • Modify shared files that other agents are also working on
  • Install dependencies that conflict across agents
  • Return output in inconsistent formats that are hard to aggregate

The structured output format (RESULT:, FILES_CHANGED:, ISSUES_FOUND:) lets the orchestrator parse results programmatically and build consolidated reports.

5 practical sub-agent patterns

1. The Parallel Auditor

Best for: security reviews, code quality checks, dependency analysis.

# Tell your orchestrator:
You are an orchestrator. Use sub-agents to audit each file in /src/services/
for SQL injection vulnerabilities. One sub-agent per file. Run them in parallel.
Return a consolidated report with every file reviewed, sorted by severity.

2. The Parallel Writer

Best for: generating docs, tests, or content for multiple independent modules.

# Each agent writes tests for one module — no conflicts
Spawn 5 sub-agents to write unit tests for the following 5 modules:
- /src/auth/login.ts  → write to /src/auth/__tests__/login.test.ts
- /src/auth/logout.ts → write to /src/auth/__tests__/logout.test.ts
- /src/payments/charge.ts → write to /src/payments/__tests__/charge.test.ts
[...and so on]
Each sub-agent only modifies its assigned test file. Nothing else.

3. The Research Aggregator

Best for: pulling information from multiple sources before making a decision.

Spawn 3 sub-agents to research our API usage:
Agent 1: Read all files in /src/integrations/ and list every external API called
Agent 2: Search /logs/ for any API error patterns in the last 7 days
Agent 3: Read package.json and all node_modules with "api" in the name

Aggregate results into /docs/api-inventory.md

4. The Fan-Out Transformer

Best for: applying the same transformation to many files independently.

There are 20 legacy service files in /src/legacy/*.js
Spawn sub-agents to convert them to TypeScript one by one in parallel.
Rules for each agent:
- Convert .js → .ts for your assigned file only
- Add proper types — no 'any' allowed
- Output the new .ts file, leave the .js file in place
- Do NOT touch any other files

5. The Hypothesis Tester

Best for: debugging where you have multiple competing theories about what's wrong.

I have a bug: users are being logged out randomly. Three theories:
Agent 1: Check /src/auth/session.ts — look for session TTL bugs or race conditions
Agent 2: Check /src/middleware/auth.ts — look for token validation logic that could fail
Agent 3: Search all .env files for SESSION_* variables and cross-check with documentation

Report findings independently. Don't try to fix anything — just diagnose.

The 3 most common sub-agent mistakes

Mistake 1: Letting agents touch shared files

If two agents both have permission to write to /src/utils/helpers.ts, they will race. The last write wins, and you lose the other agent's work — silently.

Fix: In your task prompt, be explicit: "Only modify files in /src/auth/. Do not touch anything else." Put this rule in your CLAUDE.md sub-agent section too.

Mistake 2: Not giving sub-agents enough context

Sub-agents don't inherit the parent conversation. If you've been discussing a specific approach for 20 messages and then spawn a sub-agent, the sub-agent knows nothing about that discussion.

Fix: Include all necessary context in the sub-agent task prompt itself. Treat it like writing a ticket for a new contractor who just joined the project today.

Mistake 3: Using sub-agents for sequential work

Some developers spawn sub-agents for every task automatically, even when tasks depend on each other. If Agent B needs Agent A's output, they can't run in parallel.

Fix: Before spawning parallel agents, ask yourself: "Can I start all these tasks simultaneously, or does one need to finish before another starts?" If sequential, run them sequentially in the main session.

Quick test for parallelizability

Ask: "Could a new hire work on Task A and Task B simultaneously without looking at each other's work?" If yes, parallelize. If they'd need to coordinate, don't.

Cost and token implications

Sub-agents are powerful but they're not free. Each sub-agent uses its own token budget.

  • Parallelism costs the same as sequential work — 10 sub-agents doing 1,000 tokens each = 10,000 tokens total, same as one agent doing 10 tasks sequentially. You're trading time for the same cost.
  • Over-spawning is a real problem — spawning 50 agents to analyze 50 tiny files probably isn't worth the overhead. Use parallel agents for meaningful tasks (>10 minutes of sequential work).
  • Sub-agents don't compress context — each agent gets its own context window. If you give each agent a large codebase to analyze, you're paying for that context 10 times over. Be precise about what context each agent actually needs.
Avoid token sprawl

A common mistake: pointing sub-agents at an entire large codebase when they only need one directory. Be surgical. "Analyze /src/auth/" costs a fraction of "analyze the whole project".


Putting it together: a real example

Here's a real workflow — a team wants to add JSDoc to all 15 service files that are currently undocumented. Without sub-agents, this is 15 sequential tasks. With sub-agents:

# The orchestrator prompt:
There are 15 service files in /src/services/ that have no JSDoc documentation.
Here's the list: [paste list of files]

Spawn one sub-agent per file. Each agent should:
1. Read the file
2. Add JSDoc to every exported function (parameters, return type, description)
3. Save the file
4. Output a RESULT summary showing how many functions were documented

Do not modify any files outside the assigned service file.
Follow the JSDoc standard in CLAUDE.md.

Result: 15 files documented in the time it takes to do one. The orchestrator collects all RESULT summaries and gives you a completion report.

This is the pattern. Identify the parallelizable unit (the file, the module, the hypothesis), describe the task precisely, restrict scope, and let the agents run.

CLAUDE.md Team Starter Kit

Pre-built CLAUDE.md templates for 8 roles — including an orchestrator template and sub-agent rules block ready to customize for your team.

Get the Kit — $19 Instant download · One-time payment · Works with Claude Code

Related guides