"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:
- Wide search scope: The task requires traversing multiple directories with
greporfind - Many edit targets: Ten or more files are expected to change simultaneously
- 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 generationWhen 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 completeWithout 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:
- Parent agent: Updates
packages/shared/type definitions first - Sub-agent A: Updates
packages/api/middleware and tests (referencing shared changes) - 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 changesYour 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.