Claude Code Task Tool Parallel Execution and Error Handling Implementation Patterns¶
Target Audience
- Intermediate developers who understand Claude Code basic operations
- Teams looking to optimize subagent usage with the Task tool
Key Points¶
- Improve Task tool performance using 4 optimization levers
- Establish subagent governance through permission controls and Hooks
- Quantitatively measure results with OpenTelemetry-based instrumentation
Why This Problem is Critical Now¶
With Claude Code Task tool automation, performance varies significantly depending on how subagents are used. Rather than relying on subjective "fast vs. slow" assessments, it's important to optimize through structured approaches and verify results with measurement.
This article systematically covers 4 optimization levers based on the official documentation.
4 Optimization Levers Overview¶
| Lever | Description | Primary Effect |
|---|---|---|
| (1) Task Decomposition & Parallelization | Select appropriate subagent types and run in parallel | Reduced processing time |
| (2) Permission Controls | Subagent control via permissions.deny | Improved security & stability |
| (3) Hooks-Based Gating | Leverage SubagentStart / SubagentStop events | Improved observability & control |
| (4) Event-Based Measurement | OpenTelemetry metrics utilization | Quantitative impact verification |
Lever 1: Task Decomposition & Parallelization¶
Choosing Subagent Types¶
Claude Code provides 4 subagent types optimized for different purposes. Selecting the right type for each task is the first step in optimization.
| Type | Model | Tool Access | Use Case |
|---|---|---|---|
| Explore | Haiku (fast, lightweight) | Read-only | File discovery, code search |
| Plan | Inherits parent model | Read-only | Design, planning |
| general-purpose | Inherits parent model | Full tool access | Complex task execution |
| Bash | Separate context | Command execution | Shell command execution |
Leverage Explore Aggressively
Explore uses the Haiku model, making it fast and cost-effective. An efficient pattern is to first run Explore for codebase investigation and file searches, then process results with general-purpose.
Auto-Compaction¶
Subagents automatically execute compaction (summary compression) when they reach approximately 95% of their context capacity. This threshold is configurable via an environment variable.
# To change the compaction threshold (default: 95)
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=80
Architectural Constraint
Subagents cannot spawn other subagents. This is an architectural constraint designed to prevent resource consumption from recursive agent spawning.
Task Decomposition Instructions via CLAUDE.md¶
Parallel execution of the Task tool is achieved by providing instructions in CLAUDE.md or prompts. Instead of Python pseudo-code, here are instruction examples that align with actual Claude Code usage patterns.
Example parallel execution instructions for CLAUDE.md:
## Task Tool Usage Policy
### Parallel Execution Patterns
When there are multiple independent tasks, launch subagents in parallel using the Task tool.
#### Parallelizing Codebase Investigation
- Use Explore subagents to investigate multiple directories simultaneously
- Example: Explore frontend and backend related code concurrently
#### Investigation -> Planning -> Execution Pipeline
1. First investigate the codebase with Explore
2. Create an implementation plan with Plan based on investigation results
3. Execute implementation with general-purpose following the plan
Example parallel execution prompt:
Please execute the following 3 tasks in parallel using the Task tool:
1. Explore: Collect a list of endpoints under src/api/
2. Explore: Investigate test coverage status under tests/
3. Plan: Create a refactoring plan based on the results from tasks above
Run 1 and 2 in parallel, then execute 3 after both complete.
Lever 2: Permission Controls¶
Restricting Subagents¶
Use permissions.deny in .claude/settings.json to restrict the use of specific subagents.
Disabling a specific subagent:
{
"permissions": {
"deny": [
"Task(general-purpose)"
]
}
}
This configuration blocks general-purpose subagent launches. This is effective when you want to restrict usage to lightweight subagents like Explore and Plan only.
Preventing all subagent spawning:
Use the --disallowedTools CLI option to disable the Task tool entirely.
claude --disallowedTools Task
Background Subagent Permissions
Background subagents automatically deny any permissions that haven't been pre-approved. For team operations, it's recommended to explicitly specify allowed tools in the allow list.
Safe Team Defaults¶
When operating Claude Code as a team, place configurations like the following in the project's .claude/settings.json.
{
"permissions": {
"deny": [
"Task(general-purpose)",
"Bash(rm *)",
"Bash(git push --force)"
],
"allow": [
"Task(Explore)",
"Task(Plan)",
"Bash(npm test)",
"Bash(npm run build)"
]
}
}
Key points of this configuration:
- deny: Blocks the general-purpose subagent (which has full tool access) and destructive commands
- allow: Explicitly permits read-only Explore / Plan and safe build/test commands
Lever 3: Hooks-Based Gating¶
SubagentStart / SubagentStop Events¶
Using Claude Code's Hooks feature, you can execute custom commands when subagents start and stop. This enables logging subagent activity and implementing conditional gating.
Configure in .claude/settings.json as follows:
{
"hooks": {
"SubagentStart": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "echo \"Subagent started at $(date)\" >> /tmp/subagent-log.txt"
}
]
}
],
"SubagentStop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "echo \"Subagent completed: $(cat /dev/stdin | jq -r '.agent_name')\" >> /tmp/subagent-log.txt"
}
]
}
]
}
}
Usage Patterns¶
| Pattern | Description |
|---|---|
| Log Collection | Record subagent start/stop events to files or log management tools |
| Execution Time Measurement | Calculate execution time from timestamp differences between SubagentStart and SubagentStop |
| Notification Integration | Notify Slack etc. when long-running subagents complete |
| Conditional Blocking | Block subagent launches under specific conditions via SubagentStart |
Lever 4: Event-Based Measurement¶
Metrics Collection with OpenTelemetry¶
Instead of subjective "fast vs. slow" judgments, perform quantitative measurement with telemetry data.
Enabling telemetry:
export CLAUDE_CODE_ENABLE_TELEMETRY=1
Key Metrics¶
| Metric Name | Description |
|---|---|
claude_code.active_time.total | Total active processing time |
claude_code.token.usage | Token consumption |
claude_code.tool_result | Tool execution results (with duration_ms) |
The tool_result event includes success rates and execution duration (duration_ms) for each tool invocation. This allows you to identify which subagent types are becoming bottlenecks.
Exporting Metrics¶
To export metrics to Prometheus or an OTLP collector:
# Export in Prometheus format
export OTEL_METRICS_EXPORTER=prometheus
# Export to OTLP endpoint
export OTEL_METRICS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
Measurement-Driven Improvement Cycle
- Enable telemetry and measure the baseline
- Apply optimizations from Levers 1-3
- Verify improvement impact with the same metrics
- Apply additional optimizations to remaining bottlenecks
Common Pitfalls and Solutions¶
| Symptom | Cause | Solution |
|---|---|---|
| Slow subagent responses | Overuse of general-purpose | Separate tasks that can be handled by Explore / Plan |
| Context overflow errors | Passing oversized tasks to subagents | Break tasks into smaller pieces and adjust CLAUDE_AUTOCOMPACT_PCT_OVERRIDE |
| Permission errors causing stops | Auto-denial during background execution | Explicitly allow required tools in permissions.allow |
| Can't perceive improvements | Relying on subjective assessment | Measure quantitatively with OpenTelemetry metrics |
Advanced Configuration (High-Level Optimization)
## Environment Variable Reference | Variable | Description | Default | |----------|-------------|---------| | `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | Auto-compaction threshold (%) | 95 | | `CLAUDE_CODE_ENABLE_TELEMETRY` | Enable telemetry | 0 (disabled) | | `OTEL_METRICS_EXPORTER` | Metrics exporter | None | | `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint URL | None | ## Task Decomposition Template for CLAUDE.md## Task Execution Rules
### Investigation Phase
- Use Explore subagents
- Investigate multiple directories in parallel
### Implementation Phase
- Create an implementation plan with Plan before executing with general-purpose
- Run tests with Bash subagents
### Prohibited Actions
- File exploration with general-purpose (use Explore instead)
- Overloading a single subagent with oversized tasks