Claude Code Parallel Tasks
Claude Code provides multiple mechanisms for executing tasks in parallel, allowing you to handle several work items at once and significantly boosting development efficiency. This chapter introduces three main parallelization approaches: Subagents, Agent Teams, and Git Worktree, helping you choose the most suitable method for different use cases.
Overview of Parallel Tasks
When facing complex tasks, a single Claude instance may struggle—the context grows too long, responses slow down, and tasks become intertwined. Claude Code offers three layers of parallelization to meet different levels of complexity and collaboration needs:
| Mechanism | Applicable scenarios | Collaboration approach | Complexity |
|---|---|---|---|
| Subagents | Focused tasks where you only care about the result | One-way reporting (results returned to the main agent) | Low |
| Agent Teams | Complex work requiring discussion and collaboration | Multi-way communication (teammates message each other directly) | Medium |
| Git Worktree | Multiple tasks requiring isolated code environments | Fully independent (each with its own working directory) | Medium |
Selection advice:
Subagents (Sub-agents)
What are Subagents
A Subagent is an independently running Claude instance with its own context and task focus. The main Claude can create multiple Subagents, each responsible for a specific subtask:
┌─────────────────────────────────────────────────────────┐
│ 主 Claude │
│ (协调者) │
└─────────────────────────────────────────────────────────┘
│
▼
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Agent A │ │ Agent B │ │ Agent C │
│ 代码审查 │ │ 测试生成 │ │ 文档编写 │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└───────────────┴───────────────┘
│
▼
返回结果给主代理
Up to 49 Subagents can run in parallel, fully meeting most parallel processing needs.
Built-in Subagents
Claude Code comes with the following built-in Subagents:
| Agent | Model | Tool | Purpose |
|---|---|---|---|
Explore |
Haiku (fast, low latency) | Read-only tools | File discovery, code search, codebase exploration |
Plan |
Inherit the main conversation | Read-only tools | Codebase research in plan mode |
General-purpose |
Inherit the main conversation | all tools | Complex research, multi-step operations, code modifications |
statusline-setup |
Sonnet | — | Run /statusline Configure the status line |
Claude Code Guide |
Haiku | — | Answer questions about Claude Code features |
Creating a Subagent
Method 1: Use the /agents command
Run /agents command, follow the prompts to create a new Subagent:
/agents
Choice Create new agent, then choose a save location, describe the functionality, and let Claude generate the configuration.
Method 2: Manually create a Subagent file
A Subagent file is configured with YAML frontmatter, followed by the system prompt in Markdown:
Example
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.
Subagent configuration fields
| Field | Required | Description |
|---|---|---|
name |
Is | Unique identifier, using lowercase letters and hyphens |
description |
Is | Describes when Claude should delegate to this Subagent |
tools |
No | List of tools the Subagent can use |
disallowedTools |
No | Tools to deny |
model |
No | Model to use: sonnet, opus, haiku, or inherit |
permissionMode |
No | Permission mode: default, acceptEdits, auto, dontAsk, bypassPermissions, plan |
maxTurns |
No | Maximum number of agent turns before the Subagent stops |
skills |
No | Skills loaded at startup |
mcpServers |
No | MCP servers available to this Subagent |
memory |
No | Persistent memory scope: user, project, or local |
background |
No | Whether to always run as a background task |
isolation |
No | Set to worktree to run in a temporary git worktree |
Controlling Subagent capabilities
Tool restrictions
Example
Allow only specific tools
name
:
safe-researcher
description
:
Research agent with restricted capabilities
tools
:
Read, Grep, Glob, Bash
Exclude specific tools
name
:
no-writes
description
:
Inherits every tool except file writes
disallowedTools
:
Write, Edit
Model selection
Example
Use Haiku (fast, cheap)
name
:
quick-searcher
description
:
Quick file search
model
:
haiku
Use Opus (powerful, expensive)
name
:
deep-analyst
description
:
Deep code analysis
model
:
opus
Inherit the main conversation's model
name
:
general-purpose
model
:
inherit
Invoking a Subagent
Method 1: Natural language
Use the test-runner subagent to fix failing tests
Method 2: @-mention
@"code-reviewer (agent)" look at the auth changes
Method 3: Launch from the command line
claude --agent code-reviewer
Foreground and background execution
- Foreground Subagent: blocks the main conversation until completion
- Background Subagent: runs concurrently, can be
Ctrl+Bswitch
Agent Teams
What are Agent Teams
Agent Teams let you coordinate multiple Claude Code instances working together. Imagine opening four Claude sessions (A, B, C, D) at once, with one acting as the team leader (Leader), responsible for coordinating work, assigning tasks, and integrating results. The other three members work independently with their own context windows, while still being able to communicate directly with one another.
Subagents vs Agent Teams
| Feature | Subagents | Agent Teams |
|---|---|---|
| Context | Own context window; results returned to the caller | Own context window; fully independent |
| Communication | Only report results to the main agent | Teammates message each other directly |
| Coordination | The main agent manages all the work | Shared task list with self-coordination |
| Best suited for | Focused tasks that only care about the result | Complex work requiring discussion and collaboration |
| Token cost | Lower: results are aggregated back into the main context | Higher: each teammate is an independent Claude instance |
In short:A Subagent is like an employee reporting to a boss, while Agent Teams are a project group of peers collaborating as equals。
Enabling Agent Teams
Agent Teams are disabled by default. You need to settings.json add the following:
Example
{
"env"
:
{
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS"
:
"1"
}
}
or set an environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
Requirement: Claude Code v2.1.32 or later
Starting an Agent Team
Once enabled, describe the task and team structure in natural language:
Example
I'm designing a CLI tool that helps developers track TODO comments across
their codebase. Create an agent team to explore this from different angles: one
teammate on UX, one on technical architecture, one playing devil's advocate.
Controlling an Agent Team
Display mode
- In-process: all teammates run in the main terminal, using
Shift+DownCycle through teammates - Split panes: each teammate gets its own tmux/iTerm2 pane
Example
{
"teammateMode"
:
"in-process"
}
Specify the number of teammates and models
Create a team with 4 teammates to refactor these modules in parallel.
Use Sonnet for each teammate.
Task assignment
- The leader can explicitly assign tasks
- Teammates can self-claim unassigned, unblocked tasks
- Tasks have three states: pending, in progress, and completed
Interacting with teammates
- In-process:
Shift+DownCycle through → type a message →EnterView →EscapeInterrupt - Split-pane: click a teammate's pane to interact directly
Shut down teammates
Ask the researcher teammate to shut down
Agent Teams architecture
| Component | Role |
|---|---|
| Team Lead | The main Claude Code session that creates the team, spawns teammates, and coordinates work |
| Teammates | Independent Claude Code instances each handling assigned tasks |
| Task List | Shared list of work items that teammates claim and complete |
| Mailbox | Messaging system for communication between agents |
Storage location:
- Team config:
~/.claude/teams/{team-name}/config.json - Task list:
~/.claude/tasks/{team-name}/
Git Worktree Support
Problem background
When multiple Agents work at the same time, they can "clash." Imagine this scenario: you ask Agent A to refactor the database module and Agent B to fix a bug on the login page. The two tasks seem unrelated, but both are being worked on in the same code repository and on the same branch. Agent A is modifying utils.py, Agent B is also modifying utils.py. One saves a version, the other overwrites it with a different one, ultimately causing conflicts, errors, and even data loss.
This is not an AI problem; it's a limitation of the underlying Git repository structure.
What is Git Worktree
Git Worktree is a Git feature that lets you attach multiple independent working directories to the same repository. Each working directory has its own branch, its own HEAD, and its own staging area, but shares the same .git database (history, object storage).
Analogy
An everyday analogy: "One company (the main repository) has multiple offices (worktrees),
each office has a different team (Agent) working on a different project (branch),
but all share the company's database (.git) and history."
Using Git Worktree
Command-line launch
# 创建 feature-auth 分支的工作树
claude -w feature-auth
# Create tmux session
claude -w feature-auth --tmux
# Using traditional tmux
claude -w feature-auth --tmux=classic
CLI parameters
| Parameters | Description | Example |
|---|---|---|
--worktree, -w |
Launch Claude in an isolated git worktree | claude -w feature-auth |
--tmux |
Create a tmux session for the worktree | claude -w feature-auth --tmux |
Worktree creation location:
Desktop support
In the Claude desktop app, go to the Code tab and simply check worktree mode to enable workspace mode.
Subagent + Worktree isolation
You can have custom Subagents always run in their own worktree:
Example
name
:
background-refactorer
description
:
Background refactoring agent
isolation
:
worktree
Usage examples
Example 1: Parallel code review
Using Subagents
Have multiple Subagents review different aspects of the code simultaneously
Use the security-reviewer subagent to check for security issues
Use the performance-reviewer subagent to analyze performance impact
Use the test-coverage subagent to validate test coverage
Using Agent Teams
Create an agent team to review PR #142. Spawn three reviewers:
-
One focused on security implications
-
One checking performance impact
-
One validating test coverage
Have them each review and report findings.
Example 2: Parallel research
Research the authentication, database, and API modules in parallel using separate subagents
Example 3: Investigation using competing hypotheses
Example
Users report the app exits after one message instead of staying connected.
Spawn 5 agent teammates to investigate different hypotheses. Have them talk to
each other to try to disprove each other's theories, like a scientific
debate. Update the findings doc with whatever consensus emerges.
Example 4: Multi-branch development
# 终端 1:重构用户模块
claude -w feature/user-refactor
# Terminal 2: Fix login bug
claude -w bugfix/login-issue
# Terminal 3: Develop new features
claude -w feature/new-dashboard
Example 5: Chaining Subagents
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
Best Practices
Subagent best practices
- Stay focused: each Subagent should have a clear, single task
- Limit tools: restrict a Subagent's tool access based on task needs
- Choose the right model: use Haiku for simple tasks, Sonnet or Opus for complex ones
- Use background execution: use background Subagents for long tasks to avoid blocking the main conversation
- Resume Subagents: when work needs to continue, ask Claude to resume the Subagent
Agent Teams best practices
- Give teammates enough context: include task-specific details in the spawn prompt
- Choose an appropriate team size: most workflows start with 3-5 teammates
- Size tasks appropriately: 5-6 tasks per teammate to maintain productivity
- Wait for teammates to finish: tell the leader to wait for teammates to complete their tasks before proceeding
- Start with research and review: start with tasks that don't require writing code
- Avoid file conflicts: divide work so each teammate owns a different set of files
- Monitor and guide: check progress and redirect approaches that aren't working
Git Worktree best practices
- One worktree per task: avoid handling multiple unrelated tasks in the same worktree
- Manage with tmux: when running multiple Claude sessions, use tmux for easy switching
- Clean up unneeded worktrees: delete worktrees promptly after tasks are done
Troubleshooting
Agent Teams FAQ
| Problem | Solution |
|---|---|
| Teammates don't appear | Check whether the task is complex enough and whether tmux is installed |
| Too many permission prompts | Pre-approve common operations in permission settings |
| Teammates stop after an error | Check the output and give additional instructions or spawn a replacement teammate |
| Leader shuts down early | Tell the leader to continue or wait for teammates to finish |
| Orphaned tmux sessions | Use tmux ls and tmux kill-session -t Clean up |
Practical Subagent examples
Code reviewer
Example
name
:
code-reviewer
description
:
Expert code review specialist. Proactively reviews code for quality, security, and maintainability.
tools
:
Read, Grep, Glob, Bash
model
:
inherit
You are a senior code reviewer ensuring high standards of code quality and security.
When invoked
:
1
. Run git diff to see recent changes
2
. Focus on modified files
3
. Begin review immediately
Review checklist
:
-
Code is clear and readable
-
Functions and variables are well-named
No
duplicated code
-
Proper error handling
No
exposed secrets or API keys
-
Input validation implemented
-
Good test coverage
-
Performance considerations addressed
Provide feedback organized by priority
:
- Critical issues
(
must fix
)
- Warnings
(
should fix
)
- Suggestions
(
consider improving
)
Debugger
Example
name
:
debugger
description
:
Debugging specialist for errors, test failures, and unexpected behavior.
tools
:
Read, Edit, Bash, Grep, Glob
You are an expert debugger specializing in root cause analysis.
When invoked
:
1
. Capture error message and stack trace
2
. Identify reproduction steps
3
. Isolate the failure location
4
. Implement minimal fix
5
. Verify solution works
Debugging process
:
-
Analyze error messages and logs
-
Check recent code changes
-
Form and test hypotheses
-
Add strategic debug logging
-
Inspect variable states
Read-only database querier
Example
name
:
db-reader
description
:
Execute read-only database queries. Use when analyzing data or generating reports.
tools
:
Bash
hooks
:
PreToolUse
:
- matcher
:
"Bash"
hooks
:
- type
:
command
command
:
"./scripts/validate-readonly-query.sh"
You are a database analyst with read-only access. Execute SELECT queries to answer questions about the data.