CLAUDE LABJP
TEACHERS — Anthropic launches Claude for Teachers, giving verified US K-12 educators free premium access, teaching skills, and curriculum links aligned to standards in all 50 statesADMIN — The Admin API is now in beta for every Claude Enterprise organization: member and invite calls need no beta header, while group and custom-role calls doM365 — The Microsoft 365 connector gains write tools — draft, send, and organize email, manage calendar events and mailbox settings, and create or update files in OneDrive and SharePointMCP — Fixed servers from --mcp-config or .mcp.json ignoring a per-server request_timeout_ms, which left long-running tool calls timing out at the 60s default in fresh sessionsSUBAGENT — A new --forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT variable include subagent text and thinking in stream-json outputDEADLINE — Opus 4.7 fast mode is removed on July 24, seven days out. speed: "fast" will error, so confirm your move to Opus 4.8TEACHERS — Anthropic launches Claude for Teachers, giving verified US K-12 educators free premium access, teaching skills, and curriculum links aligned to standards in all 50 statesADMIN — The Admin API is now in beta for every Claude Enterprise organization: member and invite calls need no beta header, while group and custom-role calls doM365 — The Microsoft 365 connector gains write tools — draft, send, and organize email, manage calendar events and mailbox settings, and create or update files in OneDrive and SharePointMCP — Fixed servers from --mcp-config or .mcp.json ignoring a per-server request_timeout_ms, which left long-running tool calls timing out at the 60s default in fresh sessionsSUBAGENT — A new --forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT variable include subagent text and thinking in stream-json outputDEADLINE — Opus 4.7 fast mode is removed on July 24, seven days out. speed: "fast" will error, so confirm your move to Opus 4.8
Articles/Claude Code
Claude Code/2026-04-12Advanced

Claude Code Sub-agent Patterns — Designing Autonomous Task Decomposition and Parallel Execution

Dissect Claude Code's internal Sub-agent architecture and learn concrete design patterns for task decomposition, parallel execution, and result merging in your own projects.

claude-code129sub-agentparallel-processing2task-decompositionarchitecture10

"Apply this change across every file." The moment you send that instruction to Claude Code, something unexpected scrolls through your terminal. Three ⏳ Launching agent... messages appear simultaneously, each working in a different directory. That is the Sub-agent pattern in action.

Claude Code is not a simple prompt-in, response-out tool. It can spawn multiple "child agents" internally, decompose tasks, and process them in parallel. Whether you understand this mechanism or not creates a two-to-threefold productivity gap between developers using the exact same tool.

When and Why Sub-agents Emerge

Claude Code spawns a Sub-agent when it determines that a single context cannot handle the full scope of work. Specifically, one of three conditions must be met:

  1. Wide search scope: The task requires traversing multiple directories with grep or find
  2. Many edit targets: Ten or more files are expected to change simultaneously
  3. Independent verification needed: Testing and refactoring can proceed in parallel without blocking each other

The critical insight is that Sub-agent creation is not something you explicitly request. Claude Code decides autonomously. However, the way you phrase your prompt significantly influences whether Sub-agents get spawned:

# Less likely to trigger Sub-agents
claude "Fix the formatDate function in src/utils/format.ts"
 
# More likely to trigger Sub-agents
claude "Date formatting is inconsistent across all components. Fix it.
Investigate the full scope of impact and update tests accordingly."

The second prompt contains keywords like "investigate," "all," and "update tests" that signal the task is decomposable. In my experience, instructions containing three or more verbs dramatically increase the Sub-agent spawn rate.

Controlling Task Granularity with CLAUDE.md

The most effective lever for controlling Sub-agent behavior is CLAUDE.md. This file, placed at the project root, lets you pre-define how tasks should be decomposed.

# CLAUDE.md — Sub-agent Control Section
 
## Task Decomposition Policy
- Test fixes may run in parallel with implementation changes
- Database migrations must be processed sequentially (no parallelism)
- Frontend and backend changes should be split into separate Sub-agents
 
## Directory Ownership
- src/api/ — Backend. Always run integration tests after changes
- src/components/ — Frontend. Include Storybook snapshot updates
- prisma/ — Database. Verify seed data consistency after migration generation

When these directives exist, Claude Code references them when deciding how to create Sub-agents. Writing "database migrations must be sequential" ensures they execute in order, even when parallel processing would be technically possible.

Here is a pattern I use in production projects:

## Parallel Processing Guardrails
- Never allow multiple Sub-agents to write to the same file
- Execute package.json changes exactly once, at the end
- Perform git commit only after all Sub-agents complete

Without this "guardrails" section, two Sub-agents can simultaneously edit package.json and create merge conflicts. This is not documented anywhere official, but it is a wall you will inevitably hit in large-scale projects.

Merging Parallel Sub-agent Results

The hardest part of the Sub-agent pattern is integrating results after parallel execution. Internally, Claude Code runs a three-phase process:

Phase 1: Diff Collection

Changes from each Sub-agent are collected at the file level. No conflict detection happens yet.

Phase 2: Conflict Detection and Resolution

When multiple Sub-agents modify the same file, the parent agent merges their diffs. This uses logic similar to git's 3-way merge, but with semantic understanding — making it capable of smarter decisions than pure text-based merging.

Phase 3: Consistency Verification

The merged code is automatically checked with type checking and linting. If errors are found, additional Sub-agents are spawned to fix them.

To leverage this flow, I keep the following scripts in every project:

{
  "scripts": {
    "validate": "tsc --noEmit && eslint . && vitest run --reporter=verbose",
    "validate:quick": "tsc --noEmit && eslint --cache ."
  }
}

Defining a validate command in package.json lets Claude Code use it automatically during Phase 3. Having validate:quick available speeds up intermediate checks and tightens the feedback loop.

Practical Example: Sub-agents in a Monorepo

The Sub-agent pattern shines brightest in monorepo setups. Here is a real example of refactoring both frontend and backend simultaneously using Turborepo and Claude Code:

Project structure:
packages/
  api/        ← Sub-agent A handles this
  web/        ← Sub-agent B handles this
  shared/     ← Parent agent manages directly (shared code)

The prompt:

Migrate the auth flow from JWT to session-based.
Update the API server middleware, frontend auth context,
and shared type definitions. Fix all tests.

Claude Code decomposed this as follows:

  1. Parent agent: Updates packages/shared/ type definitions first
  2. Sub-agent A: Updates packages/api/ middleware and tests (referencing shared changes)
  3. Sub-agent B: Updates packages/web/ auth context and tests (referencing shared changes)

The key observation is that shared code changes happen first, and each Sub-agent references them. This is not naive parallelism — it is DAG-based (directed acyclic graph) execution that respects dependency order.

Debugging and Monitoring Sub-agents

When Sub-agents do not behave as expected, you need debugging strategies.

# View Claude Code logs in verbose mode
CLAUDE_LOG_LEVEL=debug claude "task description"

Logs record each Sub-agent's launch timing, assigned task, and execution duration. Pay special attention to the agent_context_tokens field. If it is close to the parent agent's context length, the Sub-agent may not have received enough information to work effectively.

Another practical technique is the --max-turns flag:

# Limit maximum turns for Sub-agents (default is unlimited)
claude --max-turns 20 "execute large-scale refactoring"

This acts as a safety valve against the rare case where a Sub-agent enters an infinite loop. You typically do not need it, but I recommend setting it when integrating Claude Code into CI/CD pipelines.

Cost Optimization: Sub-agents and Token Consumption

Using the Sub-agent pattern increases token consumption because each Sub-agent maintains its own context. Project-level information like CLAUDE.md contents and directory structure gets duplicated across every agent.

Rules of thumb from experience:

  • No Sub-agents: base cost × 1.0
  • 2 parallel Sub-agents: base cost × 1.6–1.8 (duplicate context overhead)
  • 3 parallel Sub-agents: base cost × 2.2–2.5

The most effective way to reduce costs is keeping your CLAUDE.md concise. Every Sub-agent reads the full CLAUDE.md, so cutting 1,000 tokens saves 3,000 tokens across three Sub-agents.

# ❌ Verbose CLAUDE.md (inflates Sub-agent costs)
This project was started in January 2024 with a team of five...
(500 lines of background explanation)
 
# ✅ Concise CLAUDE.md (optimized for Sub-agent costs)
## Tech Stack
Next.js 15 / TypeScript / Prisma / PostgreSQL
 
## Rules
- Tests use vitest. Maintain 80%+ coverage
- Update OpenAPI spec with any API changes

Your Next Move

If you want to try the Sub-agent pattern in your own project, start by adding a "Task Decomposition Policy" section to your CLAUDE.md. That single addition will make Claude Code's autonomous task decomposition significantly more effective.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Claude Code2026-05-25
Three State-Passing Patterns for Claude Code Subagents — Lessons from 4 Months of Automated Blog Pipelines
JSON files, environment variables, and context bundles — three ways to hand state between Claude Code subagents, compared with four months of production data and clear guidance on when to pick each.
Claude Code2026-07-17
The Morning My Table Ended in "… 2,847 more rows" — Separating Render Caps from Token Cost in Tool Output
Claude Code 2.1.209 caps markdown tables at 200 rows plus a remainder count. Only the rendering is capped — the model still receives every row. Here is how to measure the gap and redesign tool output around aggregates.
Claude Code2026-07-15
Answering auto mode's confirmation prompts in headless runs — a deny-by-default permission-prompt-tool
auto mode's confirmation step is a friend when you're at the keyboard, but in an unattended midnight run it becomes the reason a job sits waiting until morning. Here is how I catch those prompts with permission-prompt-tool, decide deny-by-default, and log every ruling — with working code.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →