# Subagents and Parallel Execution in Claude Code: Running Multiple Tasks Simultaneously

> A comprehensive guide to task parallelization in Claude Code: subagent architecture, shared vs. isolated context, Fan-Out and Swarm patterns, headless CLI orchestration with -p, and token economics.

## 1. What Are Subagents in Claude Code: Moving from Sequential to Parallel Thinking

A standard **Claude Code** session operates in a strictly sequential event loop. The user issues a prompt, the agent gathers context, executes searches, modifies files, runs linters or tests, and only after finishing this entire pipeline does it move on to the next instruction. As codebases grow and engineering workflows demand multiple independent tasks, this linear approach introduces unnecessary latency and rapidly inflates the context window.

To overcome this bottleneck, Claude Code implements the concept of **subagents**—isolated, autonomous execution instances of the model delegated to handle distinct, independent components of a larger objective.

```mermaid
flowchart TD
    subgraph Sequential ["Sequential Mode (Single Session)"]
        S1["Task 1"] --> S2["Task 2"] --> S3["Task 3"] --> S4["Final Result"]
    end

    subgraph Parallel ["Parallel Mode (Subagent Orchestration)"]
        P_Parent["Parent Claude Code Session"] --> P1["Subagent 1: Auth"]
        P_Parent --> P2["Subagent 2: Validation"]
        P_Parent --> P3["Subagent 3: Formatting"]
        P1 --> P_Join{"Result Aggregation"}
        P2 --> P_Join
        P3 --> P_Join
        P_Join --> P_Done["Completed Pull Request / Report"]
    end
```

### Core Characteristics of Autonomous Subagents

- **Dedicated Isolated Context Window:** A subagent is not burdened by the parent session's extensive conversational backlog, remaining entirely focused on its targeted instruction.
- **Shared Filesystem Access:** Subagents read repository structure, configuration files, and source code with identical system permissions as the parent process.
- **Asynchronous Execution:** Multiple subagents execute concurrently, reducing wall-clock development time proportionally to the number of parallel workers.
- **Automated Result Aggregation:** Upon task completion, each subagent produces a structured summary, reports findings back to the parent session, and terminates.

> [!NOTE]
> The clearest mental model for subagents is modern engineering management. Rather than having a single staff engineer write documentation for five microservices sequentially, the lead creates five distinct tasks, assigns them to parallel developers, and verifies the final output of each.

---

## 2. Parallelization Criteria: When to Fork Tasks vs. Work Sequentially

Parallelization is not an unconditional panacea. Its effectiveness relies strictly on task independence. Attempting to execute coupled workflows concurrently causes race conditions, merge conflicts, and logical deadlocks.

| Development Scenario | Recommended Mode | Architectural Justification |
| :--- | :---: | :--- |
| **Unit test generation for distinct utility modules** | Parallel | Zero module interdependence; self-contained files |
| **Multi-vector code audit (Security, SEO, A11y)** | Parallel | Each agent evaluates code from an orthogonal angle in read-only mode |
| **Database schema design and migration creation** | Sequential | Database migrations cannot be authored until schema models are settled |
| **Mutating a shared global configuration file** | Sequential | Concurrent writes by multiple agents cause dirty overwrites |
| **Batch component refactoring across directories** | Parallel | Each UI component resides in an isolated file without cross-imports |

### When Parallelization Must Be Avoided

1. **Sequential Data Dependencies:** When step B strictly consumes outputs from step A (e.g., auditing a legacy schema, designing a normalized model, and only then generating the Prisma migration script).
2. **Shared File Mutation Points:** When Agent 1 and Agent 2 simultaneously edit `app.ts` or `package.json`, leading to file corruption or lost changes.
3. **Exploratory Tasks Requiring Human Guidance:** When specifications are ambiguous and require progressive discovery with human feedback, keep work within an interactive single-threaded session.

> [!WARNING]
> The golden rule of parallelization: Before spawning subagent pools, ask: **"Can each agent complete its entire objective from start to finish without waiting for intermediary feedback from peers?"**. If the answer is no, stay strictly sequential.

---

## 3. Architecture and Mechanics: How Claude Code Dispatches Subagents

Under the hood, Claude Code orchestrates subagents via its internal **Task tool**. When the parent model detects that a prompt can be partitioned into independent work units, it automatically spawns background worker processes.

Engineers rarely need to invoke raw Task tool JSON payloads manually—formulating clean task boundaries in natural language enables Claude Code to handle dispatching and joins autonomously.

![Claude Code subagent dispatching architecture and result aggregation into the parent session](/api/guides-media/ai_agents/claude-code-subagents-and-parallel-work/images/claude-code-subagents-and-parallel-work-step-01.webp)

### Parallel Execution Lifecycle

1. **Task Dispatching:** The parent session receives a composite prompt (e.g., writing comprehensive tests for five utilities: `auth.ts`, `validation.ts`, `formatting.ts`, `api-client.ts`, `cache.ts`).
2. **Child Context Spawning:** Independent subagents are initialized, each receiving its specific scope and target file path.
3. **Autonomous Execution:** Each subagent independently inspects source code, analyzes exported types, crafts test suites, and verifies execution.
4. **Result Join & Aggregation:** The parent session waits for all worker processes to conclude, collects output summaries, and presents a consolidated debrief to the user.

---

## 4. Shared vs. Isolated Context: What Subagents Can and Cannot See

A frequent misconception among developers is that subagents possess hive-mind telepathy or retain knowledge from turn 50 of the parent conversation. In practice, Claude Code enforces strict memory separation.

![Shared vs isolated subagent context: what is available across all agents vs kept private](/api/guides-media/ai_agents/claude-code-subagents-and-parallel-work/images/claude-code-subagents-and-parallel-work-extra-02.webp)

| System Resource / State | Shared Across All Agents? | Technical Access Characteristics |
| :--- | :---: | :--- |
| **Filesystem Repository on Disk** | **Yes** | All agents possess equal read/write access to project files |
| **CLAUDE.md System Instructions** | **Yes** | Every worker inherits global project rules, style conventions, and commands |
| **Parent Conversational History** | **No** | Isolated context; subagents only see their immediate task prompt |
| **Live File Mutations** | **Caution Required** | No automated file-locking primitives; concurrent writes risk collision |

### Enforcing Single-Agent Write Ownership

To avoid codebase corruption during parallel execution, adhere strictly to the **Single Writer Principle**:

```text
Valid Work Partitioning (Zero Collision):
Subagent 1 ──► src/utils/auth.test.ts        (creates new test file)
Subagent 2 ──► src/utils/validation.test.ts  (creates new test file)
Subagent 3 ──► src/utils/formatting.test.ts  (creates new test file)

Invalid Work Partitioning (Race Condition):
Subagent 1 ──► src/index.ts  (mutates barrel export lines)
Subagent 2 ──► src/index.ts  (mutates barrel export lines)
Subagent 3 ──► src/index.ts  (mutates barrel export lines)
```

> [!IMPORTANT]
> If multiple parallel agents produce modules that must be registered in a single central barrel file (`src/index.ts` or `src/routes.ts`), **do not** instruct subagents to update that central file. Have each subagent write its isolated file, and allow the parent session to append exports after joining results.

---

## 5. Prompting Patterns for Launching Parallel Subagents

While Claude Code includes heuristics to detect opportunities for concurrency, explicit parallel phrasing eliminates ambiguity and minimizes planning latency.

### Production Prompt Templates

:::tabs
@tab Basic Parallel Partitioning
```markdown
Execute the following three tasks concurrently using dedicated subagents:

1. Implement schema validation in the registration form (src/components/RegisterForm.tsx).
2. Build a loading skeleton component for the dashboard (src/components/DashboardSkeleton.tsx).
3. Add cursor pagination support to the user list hook (src/hooks/useUsers.ts).

Ensure each subagent operates strictly within its designated file without altering shared configs.
```
@tab Fan-Out Research
```markdown
Investigate the following topics concurrently using subagents:

- Agent 1: Research official Stripe API webhooks for subscription lifecycles.
- Agent 2: Audit our existing implementation in src/services/billing.ts for vulnerabilities.
- Agent 3: Author typed TypeScript DTO interfaces for incoming Stripe payloads in src/types/stripe.ts.

Synthesize all findings into a unified refactoring plan in the main session upon completion.
```
@tab Multi-Vector Audit
```markdown
Run a parallel 4-pillar codebase audit across the repository:

- Vector A (Security): Scan for leaked secrets in git history and check database parameterization.
- Vector B (Performance): Identify N+1 query patterns in controllers and evaluate client bundle footprints.
- Vector C (Type Safety): Inspect strict TypeScript mode and flag unvetted "any" casts.
- Vector D (Accessibility): Verify ARIA attributes, semantic landmarks, and contrast ratios in UI components.
```
:::

---

## 6. Four Core Parallel Work Patterns: Architectural Blueprints

Field experience with Claude Code automation yields four proven orchestration patterns that cover the majority of engineering workflows.

```mermaid
flowchart LR
    subgraph P1 ["1. Research Fan-Out"]
        RF_Q["Architectural Decision"] --> RF1["PostgreSQL"]
        RF_Q --> RF2["MongoDB"]
        RF_Q --> RF3["SQLite"]
        RF1 & RF2 & RF3 --> RF_M["Comparative Matrix"]
    end

    subgraph P2 ["2. Audit Swarm"]
        AS_Code["Repository"] --> AS1["Security"]
        AS_Code --> AS2["Performance"]
        AS_Code --> AS3["A11y"]
        AS_Code --> AS4["Code Quality"]
        AS1 & AS2 & AS3 & AS4 --> AS_R["Consolidated Audit Report"]
    end
```

### Research Fan-Out

Employed when architectural decisions require evaluating multiple competing technologies or libraries against identical criteria (performance, license compliance, community maintenance, bundle impact). Dedicated subagents research each option in parallel, enabling the parent session to construct an objective decision matrix.

### Audit Swarm

One of the most time-efficient patterns in agentic coding. Rather than having a single agent read the codebase four times sequentially, four specialized audit workers review the repository concurrently. Because audits are purely read-only, file write conflicts are fundamentally impossible.

### Batch Processor

Ideal for large-scale mechanical migrations where an identical transformation applies across dozens of decoupled files:
- Migrating legacy React class components to modern functional hooks in `src/components/`.
- Porting test suites from Jest to Vitest.
- Modernizing deprecated API imports across an evolving monorepo.

### Feature Sprint

Simultaneous implementation of independent UI widgets, client endpoints, or utility modules:
- Agent 1 builds a dark mode toggle (`ThemeToggle.tsx` and related state context).
- Agent 2 builds a global search drawer (`SearchBar.tsx` and indexing hook).
- Agent 3 crafts a notification center flyout (`NotificationsDropdown.tsx`).

---

## 7. Parallel Execution via CLI: Headless Mode and the -p Flag

Beyond interactive sessions, Claude Code offers enterprise-grade automation via **headless mode** using the `-p` (`--print`) CLI flag. In headless mode, the agent accepts a prompt as a command-line string, executes the task autonomously, and streams structured output directly to standard out.

This allows developers to leverage Unix process management (`&`) and synchronization primitives (`wait`):

```bash
# Concurrently spawn three background Claude Code worker processes in bash/zsh
claude -p "Write unit tests for src/utils/auth.ts using Vitest" &
PID_AUTH=$!

claude -p "Write unit tests for src/utils/validation.ts using Vitest" &
PID_VAL=$!

claude -p "Write unit tests for src/utils/formatting.ts using Vitest" &
PID_FMT=$!

# Await completion of all background agent tasks
echo "Spawned background agents with PIDs: $PID_AUTH, $PID_VAL, $PID_FMT. Awaiting..."
wait $PID_AUTH $PID_VAL $PID_FMT

echo "All tests generated! Executing verification suite..."
npm test
```

### Advantages of CLI-Driven Parallelism

- **Zero Human Overhead:** Perfect for scheduled CI/CD jobs, overnight test generation, or pre-commit checks.
- **Process-Level Isolation:** Every `claude` worker runs within an isolated operating system memory space.
- **Dedicated Log Streams:** Output from each process can be redirected directly into specific logfiles: `claude -p "..." > logs/auth.log 2>&1 &`.

> [!TIP]
> In Unix shells, trailing `&` detaches the command into the background immediately. The native `wait` builtin halts script execution until all specified process IDs terminate, ensuring downstream build verification only runs after all agents complete.

---

## 8. Token Economics, API Rate Limits, and Cost Optimization

While concurrency drastically compresses human waiting time, it introduces distinct financial considerations. Every subagent initializes its own context window; running $N$ parallel subagents consumes approximately $N$ times more context tokens than a single session.

```text
Sequential Session (1 Context Window):
[System Prompt] + [Task 1] ──► [Task 2] ──► [Task 3]
Total Token Footprint: Base Context + ΔT1 + ΔT2 + ΔT3

Parallel Subagents (3 Independent Windows):
Subagent 1: [Base Context + Task 1]
Subagent 2: [Base Context + Task 2]
Subagent 3: [Base Context + Task 3]
Total Token Footprint: (3 × Base Context) + ΔT1 + ΔT2 + ΔT3
```

### Four Best Practices for Token Budget Control

1. **Strictly Scoped Task Prompts:** Never issue vague mandates like "Fix all repository bugs." State precise file boundaries: "Write 3 unit tests for the parseJwt utility in src/utils/auth.ts."
2. **Aggressive Context Exclusion:** Ensure large build artifacts, database fixtures, and auto-generated types are ignored via `.claudeignore` to avoid redundant multi-megabyte parsing.
3. **Headless `-p` for Deterministic Tasks:** Non-interactive execution prevents ballooning chat histories and delivers concise, actionable output.
4. **Merge Trivial Adjustments:** Avoid spawning subagents for single-line CSS edits—the overhead of initializing context far outweighs the benefits of parallelism.

---

## 9. Hands-on Workshop: Step-by-Step Execution from Tests to Audit Swarms

Solidify your mastery with this structured, end-to-end practical walkthrough.

### Step 1. Selecting Isolated Modules and Environment Preparation

Identify three decoupled utility files in your codebase that share no mutual dependencies:
- `src/utils/auth.ts`
- `src/utils/validation.ts`
- `src/utils/formatting.ts`

Verify that corresponding unit test files do not yet exist or require comprehensive rewrites.

### Step 2. Formulating and Dispatching the Concurrency Prompt

Launch an interactive Claude Code session in your terminal and issue the following prompt:

```markdown
Generate unit tests for the following three files concurrently using subagents:

1. src/utils/auth.ts -> Save tests to src/utils/auth.test.ts
2. src/utils/validation.ts -> Save tests to src/utils/validation.test.ts
3. src/utils/formatting.ts -> Save tests to src/utils/formatting.test.ts

Testing Requirements:
- Use Vitest and assert edge cases (null, undefined, empty strings).
- Do not modify the original utility implementation files.
```

### Step 3. Monitoring Execution and Test Suite Verification

Observe terminal output as Claude Code dispatches child workers, analyzes each module concurrently, and reports task completions.

Verify generated test suites via your standard runner:

```bash
npm run test:run
```

All three test suites should execute cleanly with full test coverage and zero git merge collisions.

### Step 4. Executing an Audit Swarm for Codebase Quality

Next, test the analytical Audit Swarm pattern. Issue this multi-vector review request:

```markdown
Run a comprehensive codebase audit using four concurrent subagents:

- Security Agent: Check for XSS, CSRF vulnerabilities, insecure packages, and hardcoded secrets.
- Performance Agent: Analyze client bundle weight, excessive re-renders, and heavy imports.
- Accessibility Agent: Audit semantic HTML tags, keyboard navigation traps, and ARIA attributes.
- Code Quality Agent: Identify dead code, duplicated utilities, and unsafe "any" type usage.

Compile findings into an aggregated debrief prioritized by severity (High / Medium / Low).
```

---

## 10. Summary Cheat Sheet and Parallelization Readiness Checklist

Keep this checklist handy prior to initiating large-scale parallel agent workflows in Claude Code.

### Pre-Flight Concurrency Checklist

- [ ] **Task Independence:** No task depends on intermediary results generated by sibling subagents.
- [ ] **File Write Isolation:** Every subagent writes exclusively to its own dedicated file; zero contention for shared configuration barrels.
- [ ] **Precise Prompt Scoping:** Explicit inputs, outputs, file paths, and testing criteria are provided.
- [ ] **Economic Viability:** The time saved justifies the multiplier on base context token consumption.
- [ ] **Clean Environment:** Heavy directories and generated files are filtered via `.claudeignore`.

### Quick Tool Selection Matrix

| Objective | Recommended Approach | Execution Interface |
| :--- | :--- | :--- |
| **Generating tests across 5+ independent modules** | Interactive Claude Code or CLI `-p` | `claude -p "..." &` |
| **Multi-vector security and code audit** | Audit Swarm in interactive session | Prompt with 4 specialized subagents |
| **Technology / library evaluation** | Research Fan-Out | Consolidated decision table |
| **Deep core architectural refactoring** | Sequential Single Session | Interactive dialog with iterative engineer review |