Module 3: Parallel Sub-Agent Delegation

2. Parallel Delegation — Syntax, Patterns, and Limits

2. Parallel Delegation — Syntax, Patterns, and Limits

Description

Parallel delegation in Claude Code doesn't require concurrency APIs or threads — it works at the subagent level. When you ask Claude to run multiple independent tasks, it can launch several subagents simultaneously: one researches the auth module while another analyzes the products one, a third reviews the database. The three work at the same time, and Claude consolidates the results when they finish.

The mechanics have two dimensions: when something runs in parallel (background execution, prompting patterns) and how the agents are isolated so they don't step on each other (git worktrees). Understanding both is what separates "launching agents at the same time and praying" from "orchestrating parallel delegation with isolation."

By the end of this capsule you'll know exactly how to activate parallel execution — the background: true field, the Ctrl+B shortcut, the prompts that instruct Claude to delegate in parallel, and the isolation: worktree field that prevents write conflicts. You'll also know when NOT to use it, which is just as important.


Background Execution: The Base Mechanism

How it works

When Claude Code delegates to a subagent, it normally does so in foreground — it waits for it to finish before continuing. With background execution, the subagent runs in the background while Claude (or you) continues with something else.

Foreground (default):
Claude → launches subagent A → waits... → receives result → continues

Background:
Claude → launches subagent A in background ─┐
       → launches subagent B in background ──┤ (simultaneous)
       → launches subagent C in background ──┘
       → waits for all to finish → consolidates results

Three ways to activate background execution

1. The background: true field in frontmatter:

---
name: module-researcher
description: Researches a specific module for patterns and issues
tools: Read, Glob, Grep
model: haiku
background: true
---

You are a code researcher. Analyze the specified module and report...

When background: true is in the frontmatter, this subagent always runs in the background. It's useful for subagents that are asynchronous by design — research, analysis, read-only tasks that don't block the main flow.

2. Ctrl+B to background a running task:

If a subagent is already running in foreground and you notice you don't need to wait, press Ctrl+B. Claude moves the execution to the background and you can keep interacting. When the subagent finishes, the result appears in the conversation.

You: "Use the code-reviewer to analyze the whole project"
Claude: [starts running the reviewer]
You: [press Ctrl+B]
Claude: "I've sent the reviewer to the background. What else can I help with?"
[...you work on something else...]
Claude: "The reviewer finished. Here are the results:"

3. Claude decides automatically:

When your prompt implies multiple independent tasks, Claude may decide on its own to send subagents to the background. You don't need to ask for it explicitly every time — but explicit prompts are more predictable.


Prompting Patterns for Parallel Delegation

Pattern 1: Explicit parallel research

The most direct pattern. You ask Claude to research multiple areas simultaneously:

Research the auth, products, and orders modules in parallel.
For each one, report: file structure, external dependencies,
and error handling patterns.
Use separate subagents for each module.

Claude will launch 3 subagents — one per module — and run them concurrently. Each subagent has its own context and only sees the files that belong to it.

Pattern 2: Implicit delegation by independence

When you describe tasks that Claude recognizes as independent, it can parallelize automatically:

I need you to do 3 things:
1. Update the type hints in src/auth/
2. Add docstrings to all public functions in src/products/
3. Standardize the error handling in src/orders/

These tasks are independent of each other.

The key phrase is "independent of each other" — it gives Claude the signal that it can parallelize.

Pattern 3: Parallel refactor with worktrees

For tasks that modify files, you need isolation:

Refactor these 4 modules in parallel, each with a separate
subagent in an isolated worktree:
- src/auth/ — update to Pydantic v2 models
- src/products/ — add pagination to all endpoints
- src/orders/ — implement soft delete
- src/notifications/ — migrate to async handlers

When done, consolidate the changes from the 4 worktrees.

Pattern 4: Parallel analysis with merge

Analyze the API's performance in parallel:
- One subagent analyzes the read endpoints (GET)
- Another subagent analyzes the write endpoints (POST, PUT, DELETE)
- A third analyzes the database queries

When the 3 finish, give me a unified report with the top 5
optimization opportunities.

Anti-patterns: what does NOT work

❌ "Make everything faster using parallelism"
   → Too vague. Claude doesn't know what to parallelize.

❌ "Run the reviewer and the implementer in parallel"
   → The implementer NEEDS the reviewer's result. Dependency.

❌ "Launch 10 subagents, one per file"
   → Excessive overhead. Each subagent consumes context window.

Isolation with Git Worktrees

The problem it solves

Without isolation, two subagents that edit files at the same time can create conflicts:

Subagent A edits src/models/user.py (adds email field)
Subagent B edits src/models/user.py (adds phone field)

Without isolation:
→ One overwrites the other's changes
→ Or one agent sees a file "half-edited" by the other

Git worktrees solve this by giving each subagent its own isolated copy of the repository.

How isolation: worktree works

---
name: module-refactorer
description: Refactors a specific module with isolation
tools: Read, Write, Edit, Grep, Glob
isolation: worktree
---

Refactor the specified module following project conventions...

When a subagent has isolation: worktree, Claude Code:

  1. Creates a temporary git worktree — a copy of the repository that shares the git history but has its own working directory
  2. The subagent works exclusively in that worktree — its reads and writes don't affect the main repository
  3. When done, the worktree's changes are merged back into the main repository
  4. If the subagent made no changes, the worktree is cleaned up automatically
Main repository:
  /your-project/
  ├── src/auth/
  ├── src/products/
  └── ...

Subagent A's worktree:
  /tmp/worktree-auth-xxxxx/
  ├── src/auth/        ← edits here
  ├── src/products/    ← intact
  └── ...

Subagent B's worktree:
  /tmp/worktree-products-xxxxx/
  ├── src/auth/        ← intact
  ├── src/products/    ← edits here
  └── ...

Each subagent sees the complete repository but only modifies its module. There are no write conflicts because each one works in its own copy.

Worktree + background: the combination for parallel editing

For subagents that edit files in parallel, combine both fields:

---
name: auth-refactorer
description: Refactors the auth module
tools: Read, Write, Edit, Grep, Glob
background: true
isolation: worktree
---

Refactor src/auth/ following these criteria...

background: true → runs in parallel with other subagents isolation: worktree → edits files without conflicts

When you DON'T need worktrees

If the parallel subagents only read files (don't edit), you don't need isolation:

---
name: module-analyzer
description: Analyzes a module (read-only)
tools: Read, Glob, Grep
background: true
---

Multiple parallel readers don't generate conflicts. You only need worktrees when there's parallel writing.

Automatic worktree cleanup

If a subagent with isolation: worktree finishes without making changes (it only read files, or decided there was nothing to change), the worktree is cleaned up automatically. No orphaned temporary directories are left behind.

If the subagent did make changes, Claude Code handles the merge back into the main repository. If there are merge conflicts (rare if the subagents edit independent modules), Claude presents them to you for resolution.


Permissions in Background Mode

The restriction: no interaction in background

A background subagent can't ask you for confirmation. There's no human waiting to approve each action. This has implications for permissions:

Foreground: "Can I edit src/auth/models.py?" → You: "Yes" → Edits

Background: "Can I edit src/auth/models.py?" → ... no one responds → FAILS

Pre-approved permissions

For a subagent to work correctly in the background, Claude Code pre-approves the permissions based on the tools defined in the frontmatter. If the subagent has tools: Read, Write, Edit in its frontmatter, those tools are pre-approved for use without confirmation.

---
name: background-implementer
tools: Read, Write, Edit, Grep, Glob
background: true
---

This subagent can read, write, and edit files without asking for confirmation — because it operates in the background.

What happens if it fails on permissions

If a background subagent needs a tool it doesn't have pre-approved, it fails silently on that action. You can resume the task in foreground to resolve the problem:

Claude: "The background-implementer subagent couldn't complete the task
         because it needed to run a Bash command that wasn't in its
         tools list."

You: "Resume it in foreground"

Claude: [re-runs in foreground, asks you for confirmation for Bash]

To avoid this, make sure the frontmatter includes all the tools the subagent might need.

permissionMode and background

The permissionMode field interacts with background execution:

permissionModeIn foregroundIn background
defaultAsks confirmation for each actionPre-approves everything in the allowlist
acceptEditsAccepts edits, asks confirmation for othersPre-approves everything in the allowlist
bypassPermissionsEverything without confirmationEverything without confirmation
planRead-only, doesn't executeRead-only, doesn't execute

In background, the distinction between default and acceptEdits disappears — both pre-approve the allowlist tools.


Limits of Parallel Delegation

Subagents can't launch subagents

A subagent can't delegate to another subagent. The hierarchy is one level:

✅ Valid:
Claude (main) → subagent A (in parallel)
              → subagent B (in parallel)
              → subagent C (in parallel)

❌ Not valid:
Claude (main) → subagent A → sub-subagent A1
                             → sub-subagent A2

If you need task subdivision within a subagent, the logic must be in its system prompt, not in nested delegation.

Context window consumption

Each parallel subagent consumes its own context window. If you launch 4 subagents with model: sonnet, you're using 4 context windows simultaneously. This isn't a technical problem (they run), but it is a cost one — each subagent consumes tokens independently.

1 sonnet subagent with 50K tokens of context = X tokens
4 sonnet subagents in parallel = 4X tokens

For read-only or simple analysis tasks, use model: haiku, which is more economical.

Practical parallelism limit

There's no strict technical limit on how many subagents you can launch in parallel, but there are practical limits:

  • 2-4 parallel subagents: Optimal. Good balance between speed and result handling
  • 5-8 parallel subagents: Works, but result coordination gets complicated
  • 10+ parallel subagents: Diminishing returns. The coordination overhead exceeds the parallelism benefit

The recommendation: start with 2-3 parallel subagents and scale up if you need more.

Not every task benefits

The overhead of creating a subagent (context initialization, tool setup) is constant. If a task takes 10 seconds sequentially, parallelizing it with a subagent may take longer because of the setup overhead.

10s sequential task  →  Don't parallelize (overhead > benefit)
60s sequential task  →  Good candidate
5min sequential task →  Excellent candidate

Rule: if the individual task takes less than 30 seconds, it's probably not worth creating a separate subagent for it.


Sequential vs Parallel: When to Use Each One

The decision isn't "always parallel"

ScenarioSequentialParallel
Tasks with a direct dependency (A produces input for B)✅
Independent tasks in different modules✅
reviewer → implementer → tester pipeline✅
Refactor of 4 modules without dependency✅
Research of 3 codebase areas✅
Implementation + tests of the same feature✅
Documentation + linting (different files)✅
Schema change + migration + seed data✅
Code review of frontend + backend✅

The independence test

Before parallelizing, ask yourself these questions:

  1. Does task B need task A's output? → If yes, sequential.
  2. Do both tasks edit the same file? → If yes, sequential (or worktree with careful merge).
  3. Does one task's result invalidate the other's assumptions? → If yes, sequential.
  4. Can each task start now with the information that already exists? → If yes, parallel.

If the 4 answers are "no, no, no, yes" — parallelize without hesitation.

Hybrid: Parallel with sequence

The most powerful pattern combines both:

Phase 1 (parallel):
├── Research auth module      ──┐
├── Research products module  ──┤ (simultaneous)
└── Research orders module    ──┘
              ↓
Phase 2 (sequential):
└── Coordinate findings and create unified plan
              ↓
Phase 3 (parallel):
├── Implement changes in auth      ──┐
├── Implement changes in products  ──┤ (simultaneous, worktrees)
└── Implement changes in orders    ──┘
              ↓
Phase 4 (sequential):
└── Merge + testing

Research in parallel → sequential planning → implementation in parallel → sequential verification. Each phase uses the mode that maximizes efficiency for the task type.


Complete Example: Parallel Analysis of 3 Modules

The subagent files

Create 3 subagent files for parallel analysis:

.claude/agents/module-analyzer.md:

---
name: module-analyzer
description: Analyzes a specific module for patterns, issues, and improvement opportunities. Read-only.
tools: Read, Glob, Grep
model: haiku
background: true
maxTurns: 10
---

## Role
You are a module analyzer. When given a module path, analyze it completely.

## Process
1. List all files in the module with Glob
2. Read each file
3. Identify: public API, internal helpers, dependencies, error patterns
4. Report findings in the exact format below

## Output Format

### Module Analysis: [module name]

**Files:** [count]
**Lines of code:** [approximate]
**Dependencies:** [external imports]

#### Public API
- [function/class name] — [what it does]

#### Patterns Found
- [pattern name] — [where and how it's used]

#### Issues
- [issue] — [file:line] — [severity]

#### Improvement Opportunities
- [opportunity] — [estimated effort: low/medium/high]

The execution prompt

Analyze these 3 modules in parallel using the module-analyzer:
1. src/auth/
2. src/products/
3. src/orders/

When the 3 finish, give me a comparative report:
- Which module has the most issues
- Which patterns are common to all 3
- Top 5 priority improvements considering the 3 modules

What happens internally

Claude (main):
  1. Reads the prompt
  2. Launches module-analyzer(src/auth/)     → background
  3. Launches module-analyzer(src/products/) → background
  4. Launches module-analyzer(src/orders/)   → background
  5. Waits for the 3 results
  6. Consolidates into a comparative report
  7. Presents you the result

The 3 subagents work simultaneously. If src/auth/ takes 30s, src/products/ takes 45s, and src/orders/ takes 35s:

  • Sequential: 30 + 45 + 35 = 110 seconds
  • Parallel: ~45 seconds (the slowest defines the total) + consolidation time

Expected output

## Module Comparison Report

### Individual Analysis

#### src/auth/ (30s)
- 8 files, ~450 LOC
- Issues: 2 (1 warning, 1 suggestion)
- Pattern: JWT middleware pattern

#### src/products/ (45s)
- 12 files, ~680 LOC
- Issues: 4 (1 critical, 2 warnings, 1 suggestion)
- Pattern: Repository pattern with SQLAlchemy

#### src/orders/ (35s)
- 10 files, ~520 LOC
- Issues: 3 (2 warnings, 1 suggestion)
- Pattern: State machine for order status

### Common Patterns
1. All 3 modules use Pydantic v2 for validation
2. Inconsistent error handling — auth uses custom exceptions, the others use HTTPException
3. None has pagination implemented

### Top 5 Priority Improvements
1. [CRITICAL] src/products/routes.py:45 — SQL injection
2. [WARNING] Standardize error handling — same pattern across the 3 modules
3. [WARNING] Add pagination — products and orders need it
4. [SUGGESTION] Extract shared middleware from auth
5. [SUGGESTION] Add missing type hints in orders

The Environment Variable for Debugging

CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1

If you're debugging a problem with parallel delegation and need everything to run in foreground (sequentially), you can temporarily disable background tasks:

CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 claude

This forces all subagents to run in foreground, even if they have background: true. It's useful when:

  • A subagent fails silently in the background and you want to see the errors in foreground
  • You need to interact with a subagent's permissions step by step
  • You're developing a new subagent and want to see its output in real time

Don't leave it enabled in production — you lose the whole benefit of parallelization.


Troubleshooting

"The subagents don't run in parallel"

Cause: The prompt isn't explicit enough about the independence of the tasks, or the subagents don't have background: true.

Solution: Add background: true to the frontmatter and use an explicit prompt:

Run these 3 subagents IN PARALLEL, each as an independent task:
1. module-analyzer for src/auth/
2. module-analyzer for src/products/
3. module-analyzer for src/orders/

"The background subagent fails with no error message"

Cause: The subagent needed a permission it didn't have pre-approved.

Solution: Verify that all the necessary tools are in the frontmatter's tools field. If you need debugging, run with CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 to see the errors in foreground.

"The worktrees aren't cleaned up"

Cause: A subagent with isolation: worktree crashed before finishing normally.

Solution: List and clean up worktrees manually:

git worktree list
git worktree prune

"Two parallel subagents modified the same file"

Cause: The subagents didn't have isolation: worktree or edited the same file from different worktrees.

Solution: If the subagents edit potentially shared files, make sure each system prompt limits the scope to a specific directory. For maximum safety, use worktrees AND restrict the scope:

## Constraints
ONLY modify files inside src/auth/. Do NOT touch any file outside this directory.

"The consolidated result loses information"

Cause: Claude has to summarize the results of multiple subagents, and the consolidation discards details.

Solution: In the orchestration prompt, specify what information must be preserved:

When consolidating, include ALL issues found by each subagent.
Don't omit any finding. The consolidated report must have the
COMPLETE information from the 3 analyses.

Exercises

Exercise 1: Your first background subagent (Easy)

Create a subagent file named quick-scanner.md with background: true that looks for security patterns (hardcoded secrets, SQL injection) in a specified directory. Read-only. Run it against your project.

See solution

.claude/agents/quick-scanner.md:

---
name: quick-scanner
description: Scans a directory for security anti-patterns. Read-only, runs in background.
tools: Read, Glob, Grep
model: haiku
background: true
maxTurns: 8
---

## Role
Security scanner. Find hardcoded secrets and injection risks. NEVER modify files.

## Process
1. Grep for patterns: API_KEY, SECRET, PASSWORD, token in string literals
2. Grep for SQL string concatenation: f"SELECT, f"INSERT, .format(
3. Grep for eval(), exec(), os.system() with user input
4. Report findings

## Output Format
### Security Scan: [directory]
#### HIGH RISK
- **[file:line]** — [pattern found] — `[code snippet]`
#### MEDIUM RISK
- **[file:line]** — [pattern found]
#### Summary: [n] high, [n] medium

Invocation: Use the quick-scanner to scan src/

Exercise 2: Parallelize two analyses (Easy)

Write the prompt you would give Claude to run two subagents in parallel: one analyzing src/api/ and another analyzing src/models/. Both should use the module-analyzer from this capsule.

See solution
Analyze these 2 modules in parallel using separate subagents:
1. src/api/ — structure, endpoints, patterns
2. src/models/ — structure, relationships, validation

Each analysis should be independent. When both finish,
compare the findings and give me a unified summary.

The key is to specify that they're independent and that you expect results from both before the summary.

Exercise 3: Design frontmatter with worktree (Medium)

Design the complete YAML frontmatter for a subagent named style-fixer that fixes style inconsistencies (quotes, trailing whitespace, import ordering) in a specific module. It should run in the background with worktree isolation. Justify each field.

See solution
---
name: style-fixer
description: Fixes style inconsistencies in a module — quotes, whitespace, imports. Runs in isolated worktree.
tools: Read, Write, Edit, Grep, Glob
model: haiku
background: true
isolation: worktree
maxTurns: 15
---

Justifications:

  • tools: Needs Write/Edit to fix files, Read/Grep/Glob to find inconsistencies
  • model: haiku — Style fixes are mechanical, they don't require deep reasoning
  • background: true — To be able to launch multiple style-fixers in parallel (one per module)
  • isolation: worktree — It edits files, so it needs isolation to not conflict with other parallel agents
  • maxTurns: 15 — Enough to read, detect, and fix in a medium-sized module. Prevents infinite execution

Exercise 4: Identify what to parallelize (Medium)

Given this workflow, identify which tasks can go in parallel and which must be sequential. Draw the optimized flow:

  1. Update the Pydantic models in src/models/
  2. Update the routes that use those models in src/routes/
  3. Update the tests in tests/
  4. Update the documentation in docs/
  5. Run the linter on the whole project
  6. Run the tests
See solution
Dependency analysis:
1. Models (doesn't depend on anything)
2. Routes (depends on 1 — uses the models)
3. Tests (depends on 2 — tests the routes)
4. Docs (depends on 1 and 2 — documents models and routes)
5. Linter (depends on 1, 2, 3 — needs final code)
6. Tests run (depends on 1, 2, 3 — needs final code)

Optimized flow:

Phase 1 (sequential): Update models
         ↓
Phase 2 (parallel):
├── Update routes  ──┐
└── Update docs     ──┘ (docs can be based on models alone)
         ↓
Phase 3 (sequential): Update tests (needs final routes)
         ↓
Phase 4 (parallel):
├── Run linter  ──┐
└── Run tests   ──┘ (independent of each other)

Only Phase 2 and Phase 4 are parallelizable. The gain is modest but real.

Exercise 5: Debugging a background failure (Hard)

A subagent with this frontmatter fails silently in the background:

---
name: db-migrator
tools: Read, Grep
background: true
---

Run alembic upgrade head and verify the migration applied correctly.

Identify the problem and propose the fix.

See solution

Problem: The system prompt asks to run alembic upgrade head (a Bash command), but tools only includes Read and Grep. It doesn't have Bash/Bash. In foreground, Claude would ask for permission and fail visibly. In background, it fails silently because it can't request additional permissions.

Fix:

---
name: db-migrator
tools: Read, Grep, Glob, Bash
background: true
maxTurns: 10
---

Add Bash to the tools list. In background, the allowlist tools are pre-approved, so Bash will work without confirmation.

Additional note: a subagent that runs database migrations in the background is risky — a destructive migration would run without confirmation. Consider whether this subagent should be foreground (background: false) with permissionMode: default so it asks you for confirmation before running the migration.

Exercise 6: Design a hybrid parallel-sequential flow (Hard)

Design the complete flow for this task: "I need to add JWT authentication to a project that has 4 routers (users, products, orders, admin). Each router needs protected endpoints."

Define: which tasks go in parallel, which in sequence, which subagents you need, and which isolation field they use.

See solution
Dependency analysis:
- The auth logic (JWT utils, middleware) must exist BEFORE protecting endpoints
- The 4 routers are independent of each other AFTER auth exists
- The tests must run AFTER all the routers are updated

Flow:

Phase 1 — SEQUENTIAL:
  auth-implementer (no isolation)
  → Create JWT utils, auth middleware, login/register endpoints
  → Must finish before Phase 2

Phase 2 — PARALLEL (4 subagents with worktree):
  ├── router-protector (isolation: worktree) → protect users router
  ├── router-protector (isolation: worktree) → protect products router
  ├── router-protector (isolation: worktree) → protect orders router
  └── router-protector (isolation: worktree) → protect admin router

Phase 3 — SEQUENTIAL:
  merge-coordinator (no isolation)
  → Verify consistency of the 4 protected routers
  → Run the linter

Phase 4 — SEQUENTIAL:
  code-tester (no isolation)
  → Run the complete test suite

Subagents needed:
1. auth-implementer: tools=[Read,Write,Edit,Grep,Glob], model=sonnet
2. router-protector: tools=[Read,Write,Edit,Grep,Glob], background=true,
   isolation=worktree, model=sonnet
3. merge-coordinator: tools=[Read,Grep,Glob,Bash], model=haiku
4. code-tester: tools=[Bash,Read,Grep,Glob], model=haiku

The key: auth is the dependency of all the routers, so it goes first. The 4 routers are independent of each other, so they go in parallel with worktrees. Testing goes last because it needs all the code finished.


Summary

  • Parallel delegation is activated with background: true in frontmatter, Ctrl+B during execution, or explicit prompts that indicate independence
  • isolation: worktree creates isolated copies of the repo so parallel agents edit files without conflicts
  • Background subagents have pre-approved permissions — they can only use allowlist tools without confirmation
  • If a background subagent fails on permissions, you can resume it in foreground for debugging
  • Subagents can't launch subagents — the hierarchy is a single level
  • The optimal range is 2-4 parallel subagents — beyond that, coordination overhead exceeds the benefit
  • Use CLAUDE_CODE_DISABLE_BACKGROUND_TASKS=1 to force sequential execution during debugging
  • Not everything is parallelized — tasks with dependencies, very short tasks, and tasks that edit the same files aren't good candidates
  • The hybrid pattern (parallel → sequential → parallel) is the most powerful in practice

Additional Resources

  1. Create Custom Subagents (Anthropic Docs) — Official documentation including background, isolation, maxTurns
  2. Claude Code Sub-agents — Background Execution — Reference for background execution, permissions, and Ctrl+B
  3. Git Worktrees Documentation — Official git worktrees reference
  4. Claude Code CLI Reference — Environment variables like CLAUDE_CODE_DISABLE_BACKGROUND_TASKS
  5. Claude Code Best Practices — Delegation and prompting patterns
  6. Claude Code Tips and Tricks — Tips for working with subagents
  7. Prompt Engineering: Be Clear and Direct — Clarity in delegation prompts
  8. Claude Models Documentation — Model reference for choosing haiku vs sonnet by cost in parallelism

Next capsule: In capsule 03 you'll learn to coordinate the results of parallel subagents — how to design dependency graphs, what happens when agents finish at different times, merge strategies, and how git worktrees resolve write conflicts. You already master the mechanics of launching agents in parallel; now you'll learn to bring the results together coherently.