12 How and When to Use Subagents in Claude Code
12.1 Isolated Context, Parallel Work
Subagents are one of the most powerful tools in Claude Code, and also one of the most misunderstood. A subagent is an isolated Claude instance with its own context window, running independently of the main session. It does work, produces a result, and returns only that result — the main session never sees the subagent’s working context.
This simple architecture — isolated context, result-only return — enables a set of patterns that are impossible (or grossly inefficient) in a single session. Subagents are the building block of parallelism, context isolation, and fresh-perspective review in Claude Code.
This chapter covers what subagents are, when to use them, how to invoke them, the patterns they enable, and crucially, when not to use them.
12.2 What Is a Subagent?
A subagent is a full Claude instance with:
- Its own context window — separate from the main session.
- Its own tool access — configurable; can be a subset of the main session’s tools.
- Its own system prompt — can be customized for the subagent’s role.
- A result-only return — the main session receives only the synthesized output, not the working process.
When the main session delegates work to a subagent, the subagent spins up, receives its task and inputs, does its work (reading files, running tools, reasoning), and returns a result. The main session’s context is unaffected by the subagent’s work — it only grows by the size of the result.
The key property of subagents is context isolation. Everything the subagent reads, writes, and reasons about stays in its own context. The main session sees only the final result. This makes subagents dramatically more context-efficient than doing the same work in the main session, especially for tasks that involve reading a lot of files or generating large artifacts.
12.3 When to Use Subagents
12.3.1 Context Isolation Needed
The most fundamental reason to use a subagent is context isolation. If a task requires reading many files, exploring a large part of the codebase, or generating a large artifact, doing it in the main session bloats the context and accelerates context rot (Chapter 7). Delegating to a subagent keeps the main session lean.
Example: “Research how the authentication system works across the codebase.” This task requires reading many files — auth middleware, session management, token handling, tests. Doing it in the main session would fill the context with file contents that are useful for the research but not for subsequent work. A subagent does the research in isolation and returns a summary; the main session sees only the summary.
12.3.2 Parallel Independent Tasks
Subagents enable parallelism. If a task can be decomposed into independent subtasks, you can spawn multiple subagents to work on them simultaneously, then synthesize the results.
Example: “Review the security, performance, and correctness of this PR.” Three independent reviews can run in parallel — a security subagent, a performance subagent, and a correctness subagent. Each explores the PR from its own angle; the main session synthesizes their findings.
12.3.3 Fresh Perspective
A subagent starts with a clean context — no preconceptions, no biases from the main session’s history. This makes subagents valuable for tasks where you want an unbiased look, like adversarial code review or alternative approach generation.
Example: “Review this code as if you’re seeing it for the first time. What concerns you?” A subagent with no prior context provides a genuinely fresh perspective, catching issues that the main session (which has been working on the code) might be blind to.
12.3.4 Heavy Research
Research tasks — gathering information from many sources, cross-referencing, synthesizing — are ideal for subagents. The subagent does the heavy gathering and processing in its own context and returns a synthesized result.
Example: “Find all the places we handle webhooks and document the processing pipeline.” A subagent explores the codebase, traces the webhook flow, and returns documentation. The main session gets the documentation without the exploration overhead.
12.4 How to Invoke Subagents
12.4.1 Conversational Invocation
The simplest way to use a subagent is to ask for one conversationally:
> Use a subagent to explore the payment processing module
and summarize how refunds are handled.
Claude Code recognizes the intent and spawns a subagent for the exploration task. This is the most accessible way to use subagents and works well for ad-hoc needs.
12.4.2 Custom Subagents (.claude/agents/)
For reusable subagent roles, you can define custom subagents in the .claude/agents/ directory. A custom subagent has a defined role, system prompt, tool set, and optionally a specific model. When you invoke it (by name or by describing a task that matches its role), Claude Code spawns an instance.
# .claude/agents/security-reviewer.yaml
name: security-reviewer
model: opus
system_prompt: |
You are a security-focused code reviewer. Examine code for
vulnerabilities following the OWASP Top 10. Be thorough and
report findings with severity levels.
tools:
- read_file
- grep
- bashCustom subagents are valuable for roles you invoke repeatedly: security reviewer, test writer, documentation generator, migration specialist.
12.4.3 CLAUDE.md Instructions
You can instruct Claude Code in CLAUDE.md to use subagents for certain types of work: “For any task involving the legacy/ directory, use a subagent to avoid context pollution from its different conventions.”
12.4.4 Skills and Hooks
Skills can include subagent invocations as part of their procedures, and hooks can trigger subagents in response to events (e.g., “when a PR is opened, spawn a code review subagent”).
12.5 Patterns Enabled by Subagents
12.5.1 Pattern 1: Parallel Codebase Exploration
Multiple subagents explore different parts of the codebase simultaneously, then synthesize findings. This is the foundation of dynamic workflows (Chapter 2, Chapter 3).
[Main Session]
├─→ [Subagent A: explore module X] ─┐
├─→ [Subagent B: explore module Y] ─┤→ [Synthesize]
└─→ [Subagent C: explore module Z] ─┘
12.5.2 Pattern 2: Adversarial Code Review
One subagent (or the main session) produces code; another subagent reviews it adversarially. The reviewer’s job is to find problems, not to validate.
[Main Session] → [Producer Subagent] → [Code]
↓
[Adversarial Reviewer Subagent] → [Issues found]
12.5.3 Pattern 3: Parallel Bug Fixes
When multiple independent bugs need fixing, spawn one subagent per bug. Each fixes its bug in isolation; the main session merges the results.
[Bug 1] → [Subagent] ─┐
[Bug 2] → [Subagent] ─┤→ [Merged fixes]
[Bug 3] → [Subagent] ─┘
12.6 When NOT to Use Subagents
Equally important is knowing when subagents are the wrong tool. Using them inappropriately adds overhead without benefit.
12.6.1 Sequential Dependent Work
If tasks are sequential and dependent — task B depends on task A’s output — subagents add overhead. Each subagent must wait for the previous one’s result, and the context-passing overhead exceeds the benefit. Do sequential work in the main session.
Wrong: “Use a subagent to design the API, then another to implement it, then another to test it.” Right: Do this sequentially in the main session, where each step builds on the previous one’s context.
12.6.2 Small Tasks
For small tasks — a quick edit, a simple question, a minor refactor — the overhead of spawning a subagent exceeds the benefit. Subagents shine for substantial work; for trivial tasks, just do it in the main session.
12.6.3 Too Many Specialists
If you find yourself spawning many narrowly-scoped specialist subagents for a single task, you may be over-decomposing. Each subagent adds coordination overhead. If the specialists need to coordinate tightly, consider agent teams (multi-agent orchestration with shared state, as in Managed Agents — Chapter 13) instead of isolated subagents.
12.6.4 Agents That Need to Coordinate
Subagents are isolated — they can’t communicate with each other during execution, only through the main session. If your agents need to coordinate (share intermediate findings, adjust based on each other’s progress), isolated subagents are the wrong model. Use a coordination mechanism that supports communication, like dynamic workflows (which can pass messages) or Managed Agents’ multiagent orchestration (Chapter 13).
12.7 Subagents vs. Other Steering Methods
| Characteristic | Subagents | Skills | Hooks |
|---|---|---|---|
| Context cost to main session | Zero (result only) | Low (loaded on demand) | Low (runs as code) |
| Parallelism | ✅ Yes | ❌ No | ❌ No |
| Context isolation | ✅ Yes | ❌ No | N/A |
| Deterministic | ❌ No (model-based) | ❌ No (model-based) | ✅ Yes |
| Best for | Deep/parallel/isolated work | Procedures/workflows | Must-fail policies |
12.8 Best Practices
12.8.1 Give Subagents Clear, Self-Contained Tasks
A subagent starts with a clean context, so its task description must be self-contained — it can’t rely on the main session’s history. Include all necessary context, constraints, and acceptance criteria in the task.
12.8.2 Choose the Right Model per Subagent
Subagents can use different models. A research subagent might use Sonnet (cost-effective for gathering); an adversarial reviewer might use Opus (deeper reasoning for finding issues). Match the model to the subagent’s role.
12.8.3 Synthesize Results Deliberately
When multiple subagents return results, the main session must synthesize them. Don’t just concatenate — reason about how the results fit together, resolve conflicts, and produce a coherent synthesis.
12.8.4 Don’t Over-Subagent
Resist the urge to decompose every task into subagents. The overhead of spawning, isolating, and synthesizing is worth it only for substantial, parallel, or isolation-needing work. For most day-to-day tasks, the main session is the right place.
12.9 Subagent Architecture in Detail
Understanding the subagent architecture helps you use subagents more effectively and design better custom subagents.
12.9.1 The Context Boundary
The defining feature of a subagent is its isolated context window. When the main session delegates work to a subagent:
- A new context window is created for the subagent.
- The task and inputs are written into this new context.
- The subagent works — reading files, calling tools, reasoning — all within its own context.
- The result is returned to the main session.
- The subagent’s context is discarded (or archived) — it does not merge with the main session.
The main session’s context grows by only the size of the result, regardless of how much the subagent read or generated during its work. This is what makes subagents so context-efficient.
Main Session Context: [task] [result] ← grows by result size only
↑
Subagent Context: [task] [reads 50 files] [reasons extensively] [produces result]
↑ everything here stays isolated, doesn't affect main session
12.9.2 Tool Configuration
Subagents can have customized tool sets — they don’t need access to all the main session’s tools. This is valuable for:
- Security: A review subagent might have read-only tools (can’t modify files).
- Focus: A research subagent might have search tools but not edit tools.
- Specialization: A testing subagent has test-running tools; a deployment subagent has deploy tools.
Customizing tools per subagent ensures each subagent has exactly what it needs and nothing more, reducing the risk of unintended actions.
12.9.3 Model Selection per Subagent
Subagents can use different models. This enables cost optimization and capability matching:
- A research subagent gathering information might use Sonnet (cost-effective for gathering).
- An adversarial reviewer looking for subtle bugs might use Opus (deeper reasoning).
- A formatting subagent doing routine work might use a faster model.
Matching the model to the subagent’s role optimizes both cost and quality.
12.10 Designing Custom Subagents
Custom subagents (defined in .claude/agents/) are reusable roles you can invoke repeatedly. Designing them well requires thought about the role, the system prompt, and the tool set.
12.10.1 Role Definition
A custom subagent should have a clearly defined role — a specific type of work it does well. Good roles are:
- Focused: “Security reviewer” is focused; “general assistant” is not.
- Repeatable: You invoke this role often enough to justify a custom definition.
- Distinct: The role differs from other subagents in tools, model, or approach.
12.10.2 System Prompt for Subagents
A custom subagent’s system prompt defines its perspective and approach. Unlike CLAUDE.md (which is lightweight), a subagent’s system prompt can be more prescriptive because it applies only when the subagent is active, not on every turn.
# .claude/agents/test-writer.yaml
name: test-writer
model: sonnet
system_prompt: |
You are a test-writing specialist. Your job is to write
comprehensive, maintainable tests for the code you're given.
Approach:
1. Read the code you're testing thoroughly
2. Identify all code paths and edge cases
3. Write tests that cover each path
4. Include tests for error conditions and edge cases
5. Ensure test names clearly describe what they test
Principles:
- Tests should be independent (no test depends on another)
- Tests should be deterministic (same input, same result)
- Prefer testing behavior over implementation
- Mock external dependencies
tools:
- read_file
- write_file
- bash12.10.3 Tool Set Design
Choose the subagent’s tools based on what it needs to do its job:
- Reader/analyst subagents:
read_file,grep,search— no write/edit tools. - Writer subagents:
read_file,write_file,edit— but maybe nobash(can’t execute). - Executor subagents: Full tool access including
bashfor running commands.
Restricting tools reduces risk and focuses the subagent on its role.
12.11 Advanced Subagent Patterns
12.11.1 Pattern 4: Pipeline Subagents
For sequential work with context isolation at each stage, use a pipeline of subagents:
[Task] → [Subagent A: analyze] → [findings]
↓
[Subagent B: design] → [design]
↓
[Subagent C: implement] → [code]
Each stage runs in its own context, preventing the accumulation that would occur in a single long session. The main session coordinates the pipeline, passing each stage’s output to the next.
12.11.2 Pattern 5: Voting / Consensus
For high-stakes decisions, spawn multiple subagents with the same task but different configurations (different models, different prompts), and compare their outputs. Agreement increases confidence; disagreement flags areas needing human review.
[Decision] → [Subagent A (Opus, conservative prompt)] → [Decision A]
→ [Subagent B (Opus, aggressive prompt)] → [Decision B]
→ [Subagent C (Sonnet, neutral prompt)] → [Decision C]
↓
[Compare/Vote]
12.11.3 Pattern 6: Iterative Refinement
A subagent produces work; a reviewer subagent critiques; the original (or a new) subagent revises. This loop continues until the reviewer approves.
[Task] → [Producer] → [Work] → [Reviewer] → [Approved?]
↓ No
[Feedback] → [Producer revises] → ...
↓ Yes
[Final work]
12.12 Measuring Subagent Effectiveness
To assess whether subagents are helping or hurting:
- Context efficiency: Is the main session staying leaner than it would without subagents?
- Quality: Are subagent-produced results as good as or better than main-session work?
- Speed: Is parallel subagent work faster than sequential main-session work?
- Cost: Are the tokens consumed by subagents justified by the benefits?
If subagents aren’t improving on at least one of these dimensions, you may be over-using them. The goal of subagents is to make work better, faster, or more efficient — not to add complexity for its own sake.
12.13 Key Takeaways
- Subagents are isolated Claude instances with their own context windows; they return only results, keeping the main session lean.
- When to use: context isolation needed, parallel independent tasks, fresh perspective, heavy research.
- When NOT to use: sequential dependent work, small tasks, too many narrowly-scoped specialists, agents that need to coordinate during execution.
- How to invoke: conversationally (“use a subagent to…”), via custom subagents (
.claude/agents/), via CLAUDE.md instructions, or within skills and hooks. - Patterns enabled: parallel codebase exploration, adversarial code review, parallel bug fixes.
- Give subagents self-contained tasks — they start with clean context and can’t rely on session history.
- Choose the right model per subagent — match capability (and cost) to the subagent’s role.
- Synthesize results deliberately — don’t just concatenate; reason about how results fit together.
- Don’t over-subagent — the overhead is worth it only for substantial, parallel, or isolation-needing work.