Claude Code Parallel Agents in 7 Steps — Subagent Setup to Worktree Isolation

Table of Contents

The common assumption is that Claude Code processes tasks one at a time, sequentially. That’s not actually the case. With Claude Code parallel agents, it’s possible to investigate or refactor authentication modules, databases, and API layers simultaneously. The key concept is the subagent — each subagent runs in its own independent context window, executing in parallel and funneling results back to the main conversation. This dramatically cuts task completion time compared to sequential execution. Add worktree isolation, and each agent’s code changes won’t collide with one another.

This article covers subagent definitions, parallel execution setup, worktree isolation, fork mode, and CLI flag usage step by step. A practical checklist and caveats are included at the end.

Understanding Subagent Structure

Each Claude Code subagent runs in its own independent context window. This means custom system prompts, tool access permissions, and independent permissions per agent. If the main Claude Code session is the “team lead,” subagents are the “team members” each diving deep into their assigned area.

Subagents are defined as markdown files in the .claude/agents/ or ~/.claude/agents/ directory. Configuration goes in the YAML frontmatter, with the system prompt written below it.

---
name: code-reviewer
description: Reviews code for quality and best practices
tools: Read, Glob, Grep
model: sonnet
---

You are a code reviewer. When invoked, analyze the code and provide
specific, actionable feedback on quality, security, and best practices.

Only two fields are required: name and description. Everything else is optional.

Optional Fields

FieldRoleDefault
toolsTool list available to the subagentSame as parent
modelModel to use (sonnet, opus, haiku)Inherited from parent
permissionModePermission modeSame as parent
isolationExecution isolation method (e.g., worktree)None
backgroundWhether to run in backgroundfalse
maxTurnsMaximum number of turnsNo limit
Choosing Where to Place Subagent Files
Project-specific subagents go in .claude/agents/; subagents shared across multiple projects go in ~/.claude/agents/. If the team needs to share them, the project directory is more convenient since it can be managed with Git.

The tools field accepts entries like Read, Glob, Grep, Bash, Edit, and Write. For a code-review-only subagent, omitting Edit and Write is the safer choice. Restricting to read-only access eliminates the possibility of unintended code modifications.

Subagent Nesting Restrictions

Subagents cannot spawn other subagents. If nested delegation is needed, chain through Skills or the main conversation instead. This constraint is a design decision to prevent execution depth from growing unbounded.

Setting Up Claude Code Parallel Agent Execution

Once subagents are defined, the next step is running them in parallel. According to the Claude Code subagent official guide, multiple subagents can execute simultaneously, each exploring an independent investigation path before Claude synthesizes the results.

For example, this instruction from the main session works:

Research the authentication, database, and API modules in parallel using separate subagents

That single line triggers Claude Code to explore authentication, database, and API modules through separate subagents in parallel.

The background Field and Ctrl+B

Setting the background field to true makes the subagent always run as a background task. Add background: true to the YAML frontmatter. If a subagent is already running in the foreground, pressing Ctrl+B switches it to background mid-execution.

Tool Permission Warning for Background Execution
Background subagents have their required tool permissions pre-approved before execution. Tools that aren’t approved get auto-denied. For subagents using the Bash tool, verifying permissions before switching to background is critical — otherwise key commands get rejected and the task stalls midway.

The biggest advantage of parallel execution is running independent tasks simultaneously to reduce total elapsed time. If authentication module analysis takes 3 minutes, DB schema analysis takes 2 minutes, and API endpoint review takes 4 minutes, sequential execution requires 9 minutes. Parallel execution finishes in roughly 4 minutes — the duration of the longest task.

Task Types Suited for Parallel Execution

Not every task is a good fit for parallelism. Use these criteria:

  • Suitable: Independently analyzing different directories or modules
  • Suitable: Performing read-only investigation of the same codebase from multiple perspectives
  • Not suitable: Sequential dependency tasks where one subagent’s output feeds into another’s input
  • Not suitable: Tasks modifying the same file simultaneously (causes conflicts)

When multiple subagents need to modify the same file, worktree isolation is required. The next section covers this.

Preventing Parallel Agent Conflicts with Worktree Isolation

One of the most practical features in the Claude Code parallel agents workflow is worktree isolation. Setting the isolation field to worktree runs the subagent in a temporary git worktree, providing an isolated copy of the repository.

---
name: feature-builder
description: Builds a new feature in isolated worktree
tools: Read, Edit, Write, Bash
isolation: worktree
---

Implement the requested feature in the isolated worktree.
Focus on clean, testable code.

Worktree isolation works as follows:

  1. A temporary git worktree is created from the current repository when the subagent starts
  2. The subagent freely modifies files in this isolated copy
  3. If the subagent makes no changes, the worktree is automatically cleaned up
  4. If changes exist, the worktree and branch can be kept or removed
Where Worktree Isolation Shines
It’s particularly useful for A/B implementation patterns — having two subagents implement the same feature with different approaches, then comparing results to pick the better one. Experimentation is possible without polluting the main branch.

Without worktree isolation, multiple subagents modifying the same file simultaneously produce git conflicts. With isolation, each subagent works on an independent branch, enabling conflict-free parallel modifications. Conflicts only need to be resolved at the point of merging back into the main branch.

Context Sharing and Cost Reduction with Fork Mode

Fork mode, activated via the CLAUDE_CODE_FORK_SUBAGENT=1 environment variable, uses a different execution model than standard subagents.

Standard subagents start with a fresh context window. In fork mode, subagents inherit the full conversation history from the parent. The key difference is that they use the same system prompt, tools, and model as the parent.

AspectStandard SubagentFork Mode
ContextFresh startInherits parent history
System promptCustomizableSame as parent
ToolsCustomizableSame as parent
ModelCustomizableSame as parent
Prompt cacheIndependentReuses parent cache
ExecutionForeground/background selectableAlways background

The primary benefit of fork mode is cost reduction through reusing the parent’s prompt cache. As conversations grow longer, context transmission costs increase. Fork mode reuses already-cached prompts, cutting down on redundant costs.

export CLAUDE_CODE_FORK_SUBAGENT=1
claude

Running Claude Code with this environment variable set causes all subagent spawns to automatically run in the background.

Specific token cost benchmarks for parallel subagent execution aren’t documented in the official docs. While fork mode’s cache reuse does reduce costs, the exact savings ratio varies depending on conversation length and model.

Choosing Between Normal Mode and Fork Mode

Fork mode works best when the parent conversation’s context is also relevant to the subagents. For instance, with an instruction like “implement each module based on the architecture decisions discussed so far,” fork mode means subagents already know the prior conversation — no separate explanation needed.

On the other hand, when each subagent requires entirely different roles and tools, normal mode is the right choice. Limiting a code reviewer to Read only while giving a debugger access to Bash requires custom subagent definitions.

Quick Testing with the –agents CLI Flag

Subagents can also be defined directly from the CLI without creating files. Passing JSON to the --agents flag creates session-scoped subagents. Since nothing is saved to disk, this approach is ideal for quick testing and automation scripts.

claude --agents '{
  "code-reviewer": {
    "description": "Expert code reviewer. Use proactively after code changes.",
    "prompt": "You are a senior code reviewer. Focus on code quality, security, and best practices.",
    "tools": ["Read", "Grep", "Glob", "Bash"],
    "model": "sonnet"
  },
  "debugger": {
    "description": "Debugging specialist for errors and test failures.",
    "prompt": "You are an expert debugger. Analyze errors, identify root causes, and provide fixes."
  }
}'

This single command registers two subagents — code-reviewer and debugger — for the session. It supports the same fields as YAML frontmatter (description, prompt, tools, model) in JSON format.

CLI Agent Usage Patterns

The --agents flag is particularly useful when invoking Claude Code from CI/CD pipelines. For example, a script can automatically run a code review subagent and a security audit subagent in parallel whenever a PR is opened.

# CI script structure example
claude --agents "$AGENT_CONFIG" \
  "Review the changes in this PR for code quality and security issues using both subagents in parallel"

File-based and CLI subagents differ in storage and use cases:

AspectFile-based (.claude/agents/)CLI (–agents)
StoragePersisted on diskDestroyed on session end
SharingShareable via GitShared through env vars/scripts
EditingEdit the fileModify the JSON string
Use caseRepeatedly used agentsExperiments, automation, one-off tests
Managing JSON Agent Configs
When the --agents JSON gets long, save it to a separate JSON file and load it with claude --agents "$(cat agents.json)". Commit it to Git, but plan a point to transition to .claude/agents/ markdown files.

Claude Code Parallel Agents Practical Checklist

Here’s a checklist covering the process from subagent setup to parallel execution. It includes items that are easy to overlook in production use.

Subagent Definition Checklist

  • Are the required fields name and description both filled in?
  • Does the tools list follow the principle of least privilege? (No Write tool for read-only agents?)
  • Does the model selection match task complexity? (haiku for simple searches, sonnet for code analysis)
  • Is the file location appropriate? (Project-specific → .claude/agents/, global → ~/.claude/agents/)
  • Does the system prompt clearly define the role and expected output format?

Parallel Execution Checklist

  • Are the tasks targeted for parallel execution truly independent? (No sequential dependencies?)
  • If subagents modify the same file, is isolation: worktree configured?
  • Have tool permissions been pre-approved for background subagents?
  • If fork mode is needed, is the CLAUDE_CODE_FORK_SUBAGENT=1 environment variable set?
  • Have the latest fields been verified against the subagent configuration and execution options documentation?

Troubleshooting Checklist

  • Subagent can’t use tools → Check whether auto-deny triggered during background execution
  • Worktree subagent changes aren’t visible → Verify whether changes were saved to a separate branch
  • Fork mode subagent behaves unexpectedly → Check the parent conversation history for conflicting prior instructions
  • Nested subagent call fails → Subagents can’t spawn other subagents; switch to chaining from the main conversation

Caveats and Limitations

Key constraints to keep in mind when working with Claude Code parallel agents.

No Nested Spawning

A subagent cannot invoke another subagent internally. Execution depth is limited to one level. For complex task branching, call subagents sequentially from the main session, or chain logic using Skills.

Agent Teams Documentation Gap

Detailed configuration and messaging protocol documentation for Agent Teams requires further investigation. Some aspects aren’t covered in the official docs yet. For team-level agent orchestration needs, using parallel subagent execution as a substitute is the more pragmatic approach.

maxTurns Tuning

Production-level guidance on maxTurns and auto-compaction tuning isn’t documented officially. Setting maxTurns too low causes the subagent to halt before completing its task. Setting it too high increases token consumption. Starting with defaults and adjusting based on observed task patterns is the safest approach.

Notes on Non-English Documentation

The completeness of non-English official guide translations is unverified. For accurate field names and behavior specifications, refer to the English subagent documentation as the authoritative source.

Principle of Least Privilege for Tools
Exercise caution when granting subagents the Bash tool. In particular, allowing both Bash and Write without isolation: worktree means unexpected file changes apply directly to the main branch. Read-only investigation subagents should be limited to Read, Glob, and Grep.

Next Steps: Beyond Parallel Agents

Once parallel subagent execution becomes second nature, several areas are worth exploring next. Claude Code’s hooks feature enables inserting conditional validation logic before and after subagent execution — for example, automatically running a linter after a code review subagent finishes.

MCP server integration is another extensible direction. Adding the mcpServers field to a subagent definition provides the subagent with tools that call external APIs directly. And once comfortable with parallel subagent setups, expanding scope to Claude Code agent teams orchestration is a natural next step.

When adopting a Claude Code multi-agent development environment in a team, the first design decision is how to partition subagents and which tasks warrant worktree isolation — this is the foundational design point for Claude Code parallel agents.

Scroll to Top