In this article
Subagents are one of Claude Code's most powerful capabilities. They allow splitting complex tasks into independent subtasks that execute simultaneously, reducing total execution time. The key is they work simultaneously: while one subagent analyzes the frontend, another can be reviewing the backend, and a third running tests.
Subagent vs Main agent
Main agent (coordinator): the one you start with your prompt. Has full access to the conversation context. Decides when to parallelize and synthesizes results.
Subagent (worker): child agent that receives a specific task. Operates with reduced context and returns only the result. Doesn't see the full conversation or previous history.
Quick summary
Learn to use subagents in Claude Code to execute tasks in parallel. Practical guide with Task tool examples, when to use them and advanced patterns.
How they work internally
When Claude Code detects it can parallelize work, it launches subagents using the Task tool. Each subagent is an independent instance that:
- Receives a specific, scoped instruction from the coordinator
- Has access to system tools (file reading, search, command execution)
- Operates without seeing the full conversation history
- Returns a result that the main agent integrates into its response
- Has its own independent context window
It's a Coordinator-Worker pattern: the main agent acts as coordinator that plans, distributes and synthesizes. Subagents are specialized workers that execute and report.
Internally, the flow is: your prompt reaches the coordinator, which analyzes if it can parallelize. If it detects independent tasks, it launches N subagents with specific instructions. Each works in isolation. When all finish, the coordinator receives the N results and synthesizes them into a coherent response for you.
When to use subagents (and when not)
Subagents shine when you have tasks that are independent of each other. These are the ideal scenarios:
- Multi-file investigation: analyzing 5 different files to understand an architecture
- Parallel refactoring: updating imports in multiple modules that don't depend on each other
- Distributed testing: running frontend and backend tests simultaneously
- Code auditing: reviewing security, performance and style in parallel
- Content generation: creating documentation for several functions at the same time
- Codebase analysis: exploring structure, dependencies and patterns of a new project
When NOT to use subagents:
- Sequential tasks: if step 2 depends on step 1's result, a single agent is more efficient
- Same-file edits: two subagents editing the same file create conflicts
- Trivial tasks: don't launch subagents for something the coordinator can do in 5 seconds
- Decisions with shared context: if the decision requires seeing the full picture, the coordinator should do it itself
Types of subagents by purpose
Although Claude Code doesn't have formal subagent "types", in practice they differ by the type of task they perform:
Explorer (investigator): reads files, searches patterns, analyzes structure. Doesn't modify anything. The safest because it's read-only.
# El coordinador lanza un explorer:
"Lee src/api/ y documenta todos los endpoints,
sus métodos HTTP y parámetros"
Builder: creates or modifies files. Implements concrete changes. Requires precise instructions because it operates without seeing the full context.
# El coordinador lanza un builder:
"Añade validación Zod a todos los endpoints en
src/api/routes/users.ts siguiendo el patrón de auth.ts"
Reviewer: analyzes existing code looking for issues. Returns findings without modifying files.
# El coordinador lanza un reviewer:
"Revisa src/services/payment.ts buscando:
race conditions, error handling incompleto,
y validación de inputs"
Planner: analyzes requirements and proposes an implementation plan. Doesn't execute, only plans.
# El coordinador lanza un planner:
"Analiza el PRD en docs/prd-auth.md y propón
los archivos que hay que crear/modificar,
en qué orden, y las dependencias entre ellos"
Validator: runs tests, verifies types, checks linting. Confirms changes are correct.
# El coordinador lanza un validator:
"Ejecuta npm run test y npm run lint.
Reporta solo los errores, agrupados por archivo"
The Task tool
Claude Code launches subagents via the Task tool. You don't need to invoke it manually in most cases: Claude decides when to parallelize based on your request.
For example, if you ask "analyze the security and performance of this project", Claude may launch two subagents: one for security and another for performance.
# Lo que tú escribes:
"Analiza este proyecto: revisa la seguridad, el rendimiento
y la calidad del código"
# Lo que Claude Code hace internamente:
# Task 1 → Subagent "Analizar seguridad" (busca vulnerabilidades)
# Task 2 → Subagent "Analizar rendimiento" (busca bottlenecks)
# Task 3 → Subagent "Analizar calidad" (busca code smells)
# Coordinador → Espera los 3, sintetiza en una respuesta unificada
Each subagent works in isolation. They don't share context with each other, preventing interference and keeping each analysis focused on its domain.
How to influence parallelization:
You can guide Claude Code to use subagents by structuring your prompt so independent tasks are evident:
# Prompt que favorece paralelización:
"Haz estas 3 tareas en paralelo:
1. Busca todos los TODOs en src/
2. Lista las dependencias desactualizadas
3. Cuenta las líneas de código por directorio"
# Prompt que favorece ejecución secuencial:
"Primero lee el PRD, después diseña la API basándote
en el PRD, y finalmente implementa el primer endpoint"
Real practical examples
Example 1: Investigating a fullstack bug
# Prompt que activa subagents:
"Este bug afecta al checkout. Investiga en paralelo:
1. El componente React de checkout (src/components/Checkout/)
2. La API de pagos en el backend (src/api/payments/)
3. Las migraciones de base de datos recientes (supabase/migrations/)"
Claude will launch three subagents, each searching in its zone. In seconds you have a complete view of the problem from three perspectives without having to investigate sequentially.
Example 2: Dependency migration
# Actualizar múltiples archivos de configuración:
"Migra de lodash a es-toolkit en todo el proyecto.
Hay imports en src/utils/, src/hooks/ y src/components/"
Each directory is processed by a different subagent. The result consolidates without conflicts because each subagent works on different files.
Example 3: Automatic documentation
# Generar docs para múltiples módulos:
"Genera docstrings para todas las funciones públicas
en src/api/routes/, src/services/ y src/models/"
Example 4: Multi-layer security audit
# Revisión completa de seguridad:
"Audita la seguridad del proyecto:
1. Busca SQL injection y XSS en los endpoints
2. Revisa la configuración de CORS y headers
3. Verifica que todas las rutas protegidas tienen auth middleware
4. Comprueba que no hay secrets hardcoded en el código"
Four specialized subagents, each focused on an attack vector. The coordinator synthesizes findings prioritized by severity.
Example 5: Onboarding to a new project
# Entender un proyecto desconocido:
"Analiza este proyecto que no conozco:
1. Lee package.json y describe el stack y dependencias
2. Mapea la estructura de directorios y su propósito
3. Identifica los entry points (main, routes, pages)
4. Busca documentación existente (README, docs/, comments)"
Isolation modes
Subagents can operate with different isolation levels depending on the task:
Context isolation (default): each subagent has its own context. Doesn't see the coordinator's conversation or other subagents'. Sufficient for most reading and analysis tasks.
Directory isolation: combines subagents with git worktrees. Each subagent works in a different working directory of the repository. This allows multiple subagents to modify files without git conflicts.
# Patrón: subagent + worktree para ramas paralelas
"Crea una feature branch para auth y otra para payments.
En paralelo:
- Branch feat/auth: implementa login con JWT
- Branch feat/payments: integra Stripe checkout"
Permission isolation: you can restrict what a subagent can do. For example, an analysis subagent can have read-only access, while an implementation one has write access.
Parallel execution patterns
Fan-out / Fan-in
The most common pattern with subagents. The coordinator "fans out" the task into N independent subtasks, waits for all to finish, then consolidates (fans in) the results into a unified response.
# Fan-out: 1 tarea → N subagents
Coordinador → [Subagent 1, Subagent 2, Subagent 3]
# Fan-in: N resultados → 1 respuesta
[Resultado 1, Resultado 2, Resultado 3] → Coordinador → Tu respuesta
Pipeline with parallel stages
Combines sequentiality with parallelism. First, a sequential phase (planning). Then, a parallel phase (execution). Then, another sequential phase (validation).
# Fase 1 (secuencial): Coordinador analiza requisitos
# Fase 2 (paralela): 3 subagents implementan en paralelo
# Fase 3 (secuencial): Coordinador válida coherencia
Subagent as post-change validator
After the main agent modifies code, it launches subagents to validate: one runs tests, another verifies types, another checks linting. If any fails, the main agent fixes and re-validates.
Map-Reduce over files
For operations affecting many files (e.g.: adding license headers, migrating imports, updating deprecated APIs):
# Map: un subagent por grupo de archivos
Subagent 1 → procesa src/api/*.ts
Subagent 2 → procesa src/services/*.ts
Subagent 3 → procesa src/components/*.tsx
# Reduce: coordinador verifica coherencia global
Relationship with worktrees
Subagents by default work in the same directory. If you need git-level isolation (separate branches, non-interfering changes), combine subagents with worktrees. Each worktree is an independent working directory of the repository, perfect for parallel implementations going to different branches.
Cost optimization with subagents
Subagents consume tokens. Each one has its own model invocation. These strategies minimize cost:
1. Concise instructions: every token in the subagent instruction is paid. "Search for SQL injection vulnerabilities in src/api/" is better than a three-paragraph explanation of what SQL injection is.
2. Limit the scope: "Review src/api/routes/users.ts" consumes less than "Review all of src/". A scoped subagent is cheaper and more precise.
3. Use read subagents before write ones: a subagent that reads and reports is cheaper than one that reads, decides and modifies. Do the investigation phase with cheap subagents, and implementation with the coordinator that already has the full context.
4. Don't parallelize trivial tasks: if a task takes the coordinator 5 seconds, launching a subagent for it is unnecessary overhead. The subagent setup cost (instruction + minimal context) doesn't pay off.
5. Group related tasks: instead of 10 subagents for 10 files in the same directory, use 3 subagents for 3 file groups. Less coordination overhead.
Limitations and best practices
- Reduced context: subagents don't see the full conversation. Give clear, self-contained instructions. If they need to know something from context, explicitly include it in the instruction.
- No inter-subagent communication: they can't talk to each other. They only report to the coordinator. If one subagent's result affects another, you need a sequential pattern, not parallel.
- File conflicts: if two subagents modify the same file, there will be conflict. Design tasks that operate on different files, or use worktrees for git isolation.
- Token cost: each subagent consumes independent context. Don't launch 10 subagents for a trivial task. The sweet spot is 2-5 subagents for substantial tasks.
- Mandatory verification: always review the consolidated result. The coordinator may lose nuances when synthesizing N results into one response. Ask for details if something seems superficial.
- Timeout: subagents with very complex tasks may take long. If a subagent gets stuck, the coordinator waits. Design scoped tasks with predictable results.
FAQ
Can I force Claude Code to use subagents?
Yes. Structure your prompt with numbered tasks and add "in parallel" or "simultaneously". Claude Code interprets this as a signal to use the Task tool. You can also explicitly say "use subagents for this".
What happens if a subagent fails?
The coordinator receives the error as a result. It can decide to retry with different instructions, do the task itself, or report the failure to you. It doesn't get blocked waiting indefinitely.
Can subagents use MCP tools?
Yes. Subagents have access to the same tools as the main agent: file reading/writing, command execution, search, and configured MCP servers.
How many subagents can I launch at once?
There's no official hard limit, but the practical limit is 2-5 for most tasks. More than 5 simultaneous subagents create coordination overhead and result synthesis loses quality.
Do subagents see my CLAUDE.md?
Yes. Subagents load the same CLAUDE.md as the coordinator. They inherit the project rules. This ensures they follow the same conventions even though they operate independently.
Next step
Subagents multiply Claude Code's capacity for parallel tasks. Combine them with worktrees for git isolation, with skills for repeatable workflows that use subagents internally, and with MCP servers to expand the tools available to each subagent.
Start with a simple case: next time you need to analyze multiple files, ask Claude Code to do it in parallel. You'll see the difference in response speed.
Master Claude Code from zero to advanced
The first 3 IAcademy modules are free. They include subagents, worktrees, MCP and advanced patterns.
Start free