Claude Code Parallel Tasks
Claude Code provides multiple mechanisms for executing tasks in parallel, allowing you to handle multiple work items simultaneously and significantly improve development efficiency. This chapter will introduce three main parallelization approaches: Subagents, Agent Teams, and Git Worktree, helping you choose the most suitable method based on different usage scenarios.
* * *
## Overview of Parallel Tasks
When facing complex tasks, a single Claude instance may be insufficientβlong context, slow responses, and task interweaving. Claude Code offers three levels of parallelization mechanisms to meet varying complexity and collaboration needs:
| Mechanism | Use Case | Collaboration Style | Complexity |
| --- | --- | --- | --- |
| **Subagents** | Focused tasks requiring only results | Unidirectional reporting (results returned to main agent) | Low |
| **Agent Teams** | Complex work requiring discussion and collaboration | Multidirectional communication (team members send messages directly to each other) | Medium |
| **Git Worktree** | Multiple tasks requiring isolated code environments | Fully independent (separate working directories) | Medium |
> **Recommendations:**
>
>
> * Need to process independent subtasks in parallel β Use **Subagents**
> * Require multiple agents to discuss and coordinate work β Use **Agent Teams**
> * Multiple tasks need to operate on different branches of the same repository β Use **Git Worktree**
* * *
## Subagents
### 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:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ Main Claude ββ (Coordinator) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β βΌ βββββββββββββββββΌββββββββββββββββ βΌ βΌ βΌββββββββββββ ββββββββββββ βββββββββββββ Agent A β β Agent B β β Agent C ββ Code Review β β Test Generation β β Documentation Writing βββββββββββββ ββββββββββββ ββββββββββββ β β β βββββββββββββββββ΄ββββββββββββββββ β βΌ Return Results to Main Agent
Up to 49 Subagents can run in parallel, fully meeting most parallel processing needs.
### Built-in Subagents
Claude Code comes pre-configured with the following built-in Subagents:
| Agent | Model | Tools | Purpose |
| --- | --- | --- | --- |
| `Explore` | Haiku (fast, low latency) | Read-only tools | File discovery, code search, codebase exploration |
| `Plan` | Inherits main conversation | Read-only tools | Codebase research under planning mode |
| `General-purpose` | Inherits main conversation | All tools | Complex research, multi-step operations, code modification |
| `statusline-setup` | Sonnet | β | Run `/statusline` to configure status line |
| `Claude Code Guide` | Haiku | β | Answer questions about Claude Code features |
### Creating Subagents
#### Method 1: Using the /agents command
Run the `/agents` command and follow the prompts to create a new Subagent:
/agents
Select **Create new agent**, then choose the save location, describe the function, and let Claude generate the configuration.
#### Method 2: Manually creating a Subagent file
Subagent files are configured using YAML frontmatter followed by system prompts 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` | Yes | Unique identifier, lowercase letters and hyphens only |
| `description` | Yes | Describes when Claude should delegate to this Subagent |
| `tools` | No | List of tools available to the Subagent |
| `disallowedTools` | No | Tools to be rejected |
| `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 stopping |
| `skills` | No | Skills to load 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 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 main conversation model
---
name: general-purpose
model: inherit
---
### Invoking Subagents
#### 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: Command Line Launch
claude --agent code-reviewer
### Foreground vs Background Execution
* **Foreground Subagent**: Blocks the main conversation until completion
* **Background Subagent**: Runs concurrently; switch with `Ctrl+B`
* * *
## Agent Teams
### What Are Agent Teams
Agent Teams allow you to coordinate multiple Claude Code instances working together. Imagine opening 4 Claude sessions (ABCD), where one acts as the team leader, coordinating work, assigning tasks, and integrating results. The other three members work independently, each with their own context window, but also able to communicate directly with each other.
### Subagents vs Agent Teams
| Feature | Subagents | Agent Teams |
| --- | --- | --- |
| **Context** | Own context window; results returned to caller | Own context window; completely independent |
| **Communication** | Only reports results back to main agent | Teammates send messages directly to each other |
| **Coordination** | Main agent manages all work | Shared task list, supports self-coordination |
| **Best For** | Focused tasks requiring only results | Complex work needing discussion and collaboration |
| **Token Cost** | Lower: results aggregated into main context | Higher: each teammate is an independent Claude instance |
In short: **Subagent is worker reporting to boss, Agent Teams is a collaborative project group**.
### Enabling Agent Teams
Agent Teams are disabled by default. Add the following to `settings.json`:
## Example
{
"env":{
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"
}
}
Or set the environment variable:
export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1
> **Requirement**: Claude Code v2.1.32 or higher
### Starting an Agent Team
After enabling, 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 Agent Teams
#### Display Mode
* **In-process**: All teammates run within the main terminal, cycle through with `Shift+Down`
* **Split panes**: Each teammate gets its own tmux/iTerm2 pane
## Example
{
"teammateMode":"in-process"
}
#### Specify Number of Teammates and Model
Create a team with 4 teammates to refactor these modules in parallel. Use Sonnet for each teammate.
#### Task Assignment
* Leader can explicitly assign tasks
* Teammates can self-assign unassigned, unblocked tasks
* Tasks have three states: pending, in progress, completed
#### Interacting with Teammates
* **In-process**: `Shift+Down` to cycle β type message β `Enter` to view β `Escape` to interrupt
* **Split-pane**: Click teammate pane to interact directly
#### Shutting Down Teammates
Ask the researcher teammate to shut down
### Agent Teams Architecture
| Component | Role |
| --- | --- |
| **Team Lead** | Creates the team, generates teammates, coordinates work |
| **Teammates** | Independent Claude Code instances handling assigned tasks |
| **Task List** | Shared list of work items claimed and completed by teammates |
| **Mailbox** | Messaging system between agents |
**Storage Locations:**
* Team config: `~/.claude/teams/{team-name}/config.json`
* Task list: `~/.claude/tasks/{team-name}/`
* * *
## Git Worktree Support
### Problem Background
When multiple Agents work simultaneously, they might "fight." Consider this scenario: you ask Agent A to refactor a database module and Agent B to fix a login page bug. These tasks seem unrelated, but both work on the same code repository and branch. Agent A modifies `utils.py`, and Agent B modifies `utils.py` too. One saves one version, the other overwrites with another, leading to conflicts, errors, or even data loss.
This isn't an AI issueβit's a limitation of the underlying Git repository structure.
### What Is Git Worktree
Git Worktree is a Git feature that allows mounting multiple independent working directories on the same repository. Each working directory has its own branch, HEAD, and staging area, but shares the same `.git` database (history, object storage).
## Analogy
Everyday analogy: "Same company (main repo) has multiple offices (worktrees),
each office has different teams (Agents) working on different projects (branches),
but all share the company's database (.git) and history."
### Using Git Worktree
#### Command-line Launch
# Create a worktree for feature-auth branch
claude -w feature-auth # Also create a tmux session
claude -w feature-auth --tmux # Use classic tmux
claude -w feature-auth --tmux=classic
#### CLI Arguments
| Argument | Description | Example |
| --- | --- | --- |
| `--worktree`, `-w` | Launch Claude in isolated git worktree | `claude -w feature-auth` |
| `--tmux` | Create tmux session for worktree | `claude -w feature-auth --tmux` |
Worktree creation location: `/.claude/worktrees/`
#### Desktop App Support
In the Claude desktop app, go to the Code tab and simply check the worktree mode to enable workspace mode.
### Subagent + Worktree Isolation
Custom Subagents can be forced to always run in their own worktree:
## Example
---
name: background-refactorer
description: Background refactoring agent
isolation: worktree
---
* * *
## Usage Examples
### Example 1: Parallel Code Review
## Using Subagent
# Have multiple Subagents review different aspects of 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 Contrarian 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
# Terminal 1: Refactor user module
claude -w feature/user-refactor # Terminal 2: Fix login bug
claude -w bugfix/login-issue # Terminal 3: Develop new feature
claude -w feature/new-dashboard
### Example 5: Linking Subagents
Use the code-reviewer subagent to find performance issues, then use the optimizer subagent to fix them
* * *
## Best Practices
### Subagent Best Practices
1. **Keep focused**
YouTip