Skip to content

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

  1. Improve Task tool performance using 4 optimization levers
  2. Establish subagent governance through permission controls and Hooks
  3. 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

LeverDescriptionPrimary Effect
(1) Task Decomposition & ParallelizationSelect appropriate subagent types and run in parallelReduced processing time
(2) Permission ControlsSubagent control via permissions.denyImproved security & stability
(3) Hooks-Based GatingLeverage SubagentStart / SubagentStop eventsImproved observability & control
(4) Event-Based MeasurementOpenTelemetry metrics utilizationQuantitative 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.

TypeModelTool AccessUse Case
ExploreHaiku (fast, lightweight)Read-onlyFile discovery, code search
PlanInherits parent modelRead-onlyDesign, planning
general-purposeInherits parent modelFull tool accessComplex task execution
BashSeparate contextCommand executionShell 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

PatternDescription
Log CollectionRecord subagent start/stop events to files or log management tools
Execution Time MeasurementCalculate execution time from timestamp differences between SubagentStart and SubagentStop
Notification IntegrationNotify Slack etc. when long-running subagents complete
Conditional BlockingBlock 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 NameDescription
claude_code.active_time.totalTotal active processing time
claude_code.token.usageToken consumption
claude_code.tool_resultTool 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

  1. Enable telemetry and measure the baseline
  2. Apply optimizations from Levers 1-3
  3. Verify improvement impact with the same metrics
  4. Apply additional optimizations to remaining bottlenecks

Common Pitfalls and Solutions

SymptomCauseSolution
Slow subagent responsesOveruse of general-purposeSeparate tasks that can be handled by Explore / Plan
Context overflow errorsPassing oversized tasks to subagentsBreak tasks into smaller pieces and adjust CLAUDE_AUTOCOMPACT_PCT_OVERRIDE
Permission errors causing stopsAuto-denial during background executionExplicitly allow required tools in permissions.allow
Can't perceive improvementsRelying on subjective assessmentMeasure 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