Claude Code Patterns: Subagents, Worktrees, Orchestration
Once you’ve mastered basic plugins and skills, you can unlock Claude Code’s full potential with advanced patterns. Subagents, worktrees, and multi-agent orchestration let you break complex tasks into manageable pieces, experiment safely, and build collaborative AI systems. This guide explores these powerful patterns with concrete examples and best practices.
To build a solid foundation in Claude Code extensibility, start with our main guide Claude Code Skills and Plugins.
Subagents: Spawn a Helper
Subagents are independent Claude instances that run in the background while you continue working in the main session. Think of them as assistants you can delegate tasks to. They have their own conversation history, but they share access to the same workspace files and tools.
You can spawn a subagent with the /spawn command. For example:
/spawn Analyze these test results and create a summary report.
The subagent runs concurrently. You can interact with it later by switching to its chat view, or you can let it work unsupervised. Subagents are ideal for long-running tasks that would otherwise block your main session: running a test suite, generating a large data file, or performing a lengthy API sync.
Use cases:
- Parallel tasks: Spawn multiple subagents to work on different parts of a project simultaneously.
- Background processing: Start a subagent to monitor logs or perform periodic maintenance.
- Specialized roles: Give each subagent a custom system prompt (via
/system) to specialize it, e.g., a code reviewer or a documentation writer.
Subagents inherit the tools of the parent, so they can edit files, run commands, and use plugins. However, they do not share context; they see only the messages in their own conversation.
Best practices:
- Give subagents a clear, narrow goal. Avoid vague “help me” prompts.
- Set a timeout to avoid runaway tasks (
/timeout 30m). - Monitor token usage; subagents add to your overall consumption.
- Terminate subagents when done with
/killor/cancel.
Pro Tip
You can hand off work to a subagent using the /spawn command and then immediately switch back to your main conversation. The subagent continues working, and you can check its progress later with /agents.
Worktree Strategies: Isolate Your Experiments
Git worktrees are an underutilized feature that lets you have multiple working directories attached to the same repository. Claude Code integrates with worktrees, enabling you to spin up isolated environments for testing skills, trying refactors, or exploring new ideas; all without switching branches in your main workspace.
Create a new worktree from within Claude Code:
/worktree create feature/new-carousel /tmp/feature-carousel
This creates a new directory with the current branch checked out. You can now open that worktree in a separate window (or keep it in the background). The worktree shares the same .git directory but has its own working tree, so you can modify files, run commands, and even commit without affecting the main workspace.
Why is this useful?
- Safe experimentation: Try out a new plugin or skill without risking uncommitted changes in your main project.
- Parallel workstreams: Work on two features at once, each in its own worktree.
- Continuous integration: You could spawn a subagent in a worktree to run tests for a specific branch automatically.
When you’re done, you can delete the worktree with /worktree delete. Claude Code helps manage the lifecycle, cleaning up automatically if a worktree becomes stale.
Multi-Agent Orchestration
For complex projects, you may want to coordinate several agents (including subagents) toward a common objective. This is orchestration, and Claude Code provides the /goal command to set a shared goal that multiple agents can contribute to.
When you run /goal Implement user authentication, Claude Code creates a goal object that agents can join. Agents can post updates, claim tasks, and mark sub-tasks as done. The goal view shows a unified timeline of all activity.
Orchestration patterns:
- Supervisor-Worker: One agent (the supervisor) breaks the goal into tasks and assigns them to worker agents. It monitors progress and reassigns if needed.
- Pipeline: Agents pass artifacts (files, data) along a chain. For example, Agent A generates code, Agent B reviews it, Agent C writes tests.
- Fan-out/Fan-in: Distribute independent subtasks to many agents (fan-out), then gather results (fan-in). Great for parallelizing independent work like updating many files.
To assign a subagent to a goal, use /spawn and then /goal join <goal-id>. The subagent will see the goal in its context and can contribute.
| Pattern | Use Case | Pros | Cons |
|---|---|---|---|
| Supervisor-Worker | Task distribution | Clear delegation, workload balancing | Requires supervisor overhead |
| Pipeline | Sequential processing | Simple to understand, good for data transformation | Bottleneck if one stage slow |
| Fan-out/Fan-in | Parallel independent tasks | High throughput, fast | Need to combine results, possible race conditions |
Communication Between Agents
Agents in an orchestration need to communicate. Claude Code facilitates this through several mechanisms:
- Shared workspace files: Agents can read and write files to pass data. Use a designated folder for handoffs.
- Goal messages: Agents can post messages to the goal’s chat, which other agents see. This is like a shared conversation thread.
- Tool calls: An agent can invoke a tool provided by another agent (if the tool is registered globally). For instance, a code generation agent might expose a
write_filetool that other agents can call.
Design your agents with clear contracts: define what inputs they expect and what outputs they produce. Use structured data (JSON, YAML) for handoffs to avoid parsing errors.
Error Handling and Recovery
In a multi-agent system, failures are inevitable. Build resilience with:
- Timeouts: Set maximum execution time for subagents and tools. Prevent hung tasks.
- Retries with backoff: If a tool fails due to transient error (network glitch), automatically retry a few times with increasing delays.
- Fallback strategies: Have an alternative plan if an agent can’t complete its task. For example, if a code review agent fails, fall back to a simpler linting pass.
- Escalation: When an agent can’t handle an error, it should surface it to the supervisor or the main user.
Use /kill to stop misbehaving agents quickly. Keep error messages informative but not overwhelming; they should guide debugging.
Cost Considerations
Each agent consumes tokens just like a normal chat session. Running many subagents concurrently can significantly increase your Anthropic API bill. To manage costs:
- Model selection: Assign simpler tasks to smaller, cheaper models (Haiku, Sonnet). Reserve Opus for complex reasoning.
- Token budgeting: Set limits on subagent conversation length. Use
/max_turnsor summarization to keep context small. - Reuse agents: Instead of spawning a new agent for every task, consider reusing an existing one with a reset command to preserve some context.
- Monitor usage: Track token consumption per agent and per goal. Identify expensive patterns and optimize.
Orchestration adds overhead but often pays off in reduced human intervention and faster turnaround.
Debugging and Observability
When multiple agents are running, it’s easy to lose track. Claude Code provides tools to inspect the system:
/agents: List all active agents and their status./goal list: Show all active goals and their progress./trace <agent-id>: Stream detailed logs of an agent’s actions./console: Open developer console to see raw tool invocations.
Instrument your subagents with clear system prompts that include their role and constraints. When an agent misbehaves, check its conversation history to see what led to the error.
Warning
Be careful with recursive spawning: an agent could spawn another agent, leading to a cascade. Always set a global maximum depth to avoid infinite loops and runaway costs.
Real-World Use Cases
These patterns are not just theoretical; they power production workflows.
- CI/CD Orchestration: When a pull request is opened, spawn agents to run static analysis, unit tests, integration tests, and security scans in parallel. Aggregate results and post a summary comment.
- Data Pipeline Construction: One agent extracts data from sources, another transforms it, a third loads it into a warehouse. They coordinate via shared files.
- Code Review Squad: A goal with multiple specialized agents: one checks style, another reviews security, a third evaluates performance. Each leaves comments, and a final agent synthesizes them into a unified review.
The key is to decompose clearly and let agents work independently where possible, then combine results.
Conclusion
Subagents, worktrees, and orchestration transform Claude Code from a single assistant into a multi-agent powerhouse. By mastering these patterns, you can automate complex workflows, reduce manual toil, and scale your AI capabilities. Start small: spawn a subagent for a simple task, then gradually adopt orchestration as you grow comfortable. And remember to keep an eye on costs and errors; observability is your friend. For more on extending Claude Code, revisit our main guide. Claude Code Skills and Plugins.
Frequently Asked Questions
FAQs
There’s no hard limit, but practical constraints apply: your system’s resources, API rate limits, and budget. As a rule of thumb, 5-10 concurrent subagents is manageable. More than that may cause contention or high costs. Start with one or two and scale up slowly while monitoring performance.
No. Subagents have isolated conversation histories. They don’t see the parent’s messages unless you explicitly provide context via the /spawn prompt. They do share the same workspace files, so they can read and write the same files as the parent.
Yes. Subagents inherit the same tool permissions as the parent (including plugins and MCP servers). They can execute any command that the main agent can, subject to the same user consent prompts. If a tool is disabled in the parent, it’s also unavailable to subagents.
There are several ways: (1) Have each subagent write its output to a designated file in the workspace; (2) Use a shared goal with /goal and have subagents post results to the goal chat; (3) The parent can use /agents to check status and then /attach to an agent to retrieve its last response. Choose based on the workflow: file-based is good for large data; goal-based is good for textual summaries.
No. A worktree is a separate working directory that can be on any branch (or tag). You can have multiple worktrees each on a different branch simultaneously. Branches are just pointers; worktrees let you check out multiple branches at once because each has its own working tree. This is useful for Claude Code because you can keep a feature branch open in a worktree while still working on main in the main directory.
Yes. Through MCP servers, you can route subagents to different backends. For example, you could spawn a subagent that uses a different model by configuring its environment to point to a different API endpoint. The orchestration logic (supervisor, pipeline) remains the same regardless of which model powers each agent. This provider-agnostic approach is a key strength of the MCP standard.