← All posts

Claude Code Hooks Performance: Keep Agents Fast

If your Claude Code setup feels slower after adding dashboards, safety checks, formatters, and plugins, start with the hooks. Claude Code hooks performance depends less on one clever script and more on a simple rule: keep only policy gates in the foreground, and push observability, notifications, indexing, and slow checks into the background.

The reason is blunt. Anthropic documents that hooks block Claude by default. Async command hooks can run in the background with "async": true, but they cannot approve, deny, block, or force continuation because the controlled action has already moved on. That gives platform teams a clean split: synchronous hooks are for tiny decisions that must happen before the action. Background hooks are for everything that can be recorded, retried, or handled after the agent keeps working.

The hidden tax in Claude Code hooks

A hook that costs 50 ms does not sound like a problem in one terminal. It becomes a problem when it fires on every PreToolUse, UserPromptSubmit, Stop, or SubagentStop event across a busy agent team.

Field reports in the brief show the shape of the issue. One HN discussion around an agent dashboard reported blocking hook overhead around 50 to 60 ms per hook, then 3 to 5 ms after moving to a fire-and-forget background shim. A Reddit post about a persistent hook runtime claimed a command-hook invocation dropped from about 34.6 ms to 0.31 ms through a persistent daemon. A DEV writeup measured a UserPromptSubmit cost hook at mean 819 ms and p95 5,320 ms before adding a 60-second TTL cache.

Those numbers are not universal benchmarks. They are self-reported, environment-specific measurements. But they all point at the same failure mode: process startup, external CLIs, config reads, HTTP calls, and broad matchers add up fast.

What the hook model means for latency

Claude Code runs all matching hooks for an event in parallel. That helps, but it does not erase foreground cost. The session still waits for the slowest synchronous hook in that event batch.

Command hooks receive JSON on stdin and return results through exit codes, stdout, and stderr. Exit code 2 can block only on events that can still be blocked, including PreToolUse, UserPromptSubmit, Stop, and SubagentStop. A PostToolUse hook runs after the tool has already executed, so it is the wrong place for hard prevention.

Async hooks solve a different problem. They are useful when the hook should not hold the coding loop. They are not a safety boundary. Once an async hook starts, Claude Code does not enforce its normal timeout on that hook, and non-interactive claude -p sessions can kill still-running async hooks at teardown unless the hook starts a fully detached process.

Build a two-lane hook architecture

The cleanest production pattern is two lanes.

Lane 1: synchronous policy gates

Use synchronous hooks only when the agent must wait for the answer. These checks should be local, bounded, and rare.

  • Block rm -rf or other destructive shell patterns.
  • Deny writes to .env, private keys, generated secrets, or protected paths.
  • Ask before production deploy commands.
  • Reject a SubagentStop when required evidence is missing.

For this lane, failure behavior matters. A secrets guard probably fails closed. A missing dashboard process does not.

Lane 2: async background observers

Move slow or non-critical work out of the agent path.

  • Append audit events.
  • Update dashboards from hook payloads or transcript paths.
  • Publish Slack, email, or room notifications.
  • Run non-critical lint, test, or cost analysis jobs.
  • Index transcript deltas for later review.
  • Fan out metrics to OpenTelemetry or a local collector.

In practice, this usually means an async command hook, a local HTTP daemon, or a queue. A persistent runtime can amortize Node or Python startup, but it adds real ownership: auth, lifecycle, crash handling, retries, and log hygiene.

Set a latency budget before hooks sprawl

Claude Code does not publish an official hook latency budget, so teams need their own. A reasonable starting point:

Hook use case Suggested budget Default lane
PreToolUse security policy Under 50 ms target Sync, fail closed where justified
Prompt or stop validation Under 100 to 200 ms Sync only for real gates
Dashboard event write Do not hold the foreground path Async, fail open, retry
Formatter after file edits Only sync if consistently fast PostToolUse sync, async, or pre-commit
Full test suite Outside the hot path Async, or a Stop gate for release-critical work

Track p50, p95, and max duration per hook and per event. The max matters because one wedged subprocess can freeze a headless run long after averages looked fine.

Optimize the hot path

Start with inventory. List every global plugin and hook that can run on common events. Teams in the brief reported that disabling accumulated plugins produced a bigger speedup than expected, which is exactly what happens when several broad matchers quietly run on every tool call.

Then tighten the work:

  • Narrow matchers so hooks fire only on relevant tools and paths.
  • Use cheap local checks for simple policy. A shell or compiled helper may beat a cold Node or Python process for trivial rules.
  • Cache expensive data. The DEV cost-hook example improved after adding a 60-second TTL cache because the expensive state could not change meaningfully on every prompt.
  • Bound file reads. Do not parse a whole transcript when the hook only needs the latest tool name or path.
  • Keep feedback short. Hook output injected into the conversation has token and context cost.
  • Move formatting and full tests to pre-commit, CI, async hooks, or explicit stop gates when they are not immediate safety checks.

Instrument hooks separately from agent work

Do not diagnose hook latency by feel. Claude Code monitoring exposes hook execution events, including start and complete events, and a beta hook span with fields such as duration, hook count, success counts, block counts, error counts, stdout size, and additional context size.

Hook payloads also carry useful correlation fields, including prompt_id, tool_use_id, transcript_path, and cwd. Anthropic documents that prompt_id matches the OpenTelemetry prompt.id attribute. Use that to separate model latency, tool execution latency, and hook overhead in your dashboard.

For most teams, the practical answer is hybrid. Use OpenTelemetry for aggregate metrics. Ingest hook payloads and JSONL transcripts only where you need richer event detail, such as subagent dashboards, approval timelines, or audit records.

Use subagent hooks carefully

SubagentStop is tempting because it sees agent_id, agent_type, agent_transcript_path, last_assistant_message, and parent-session background task data. That makes it excellent for dashboards and acceptance gates.

It also sits at a sensitive point in the workflow. If five subagents complete around the same time and each stop event triggers several synchronous scripts, the team loses the benefit of parallel work. Keep acceptance checks small. Send logging, summary extraction, notification fanout, and metrics to the async lane.

A practical decision table

Need Recommended hook pattern Why
Block secrets or protected paths Sync PreToolUse, fail closed The action must not happen if the guard cannot decide.
Write dashboard events Async hook or local queue, fail open Visibility should not slow every tool call.
Capture transcript metadata Async hook with bounded payload The transcript path gives enough correlation for later ingestion.
Enforce final acceptance criteria Sync Stop or SubagentStop The agent should not claim completion without evidence.
Run full tests Async job, explicit command, or Stop gate Full suites are too slow for routine tool-call hooks.
Rate-limit browser calls Intentional sync delay with visible budget Some latency is policy, but it should be measured and named.

Internal Link Anchors To Add

  • Claude Code hooks org policy: link from the section on managed policy and mandatory security hooks.
  • coding agent harness observability: link from the instrumentation section.
  • background AI agent approval inbox: link from the Stop and SubagentStop gate discussion.
  • scan Claude Code skills plugins MCP security risks: link from the plugin sprawl section.

Related reading: Claude Code hooks org policy, coding agent harness observability, background AI agent approval inbox, and scan Claude Code skills plugins MCP security risks.

The takeaway

Claude Code hooks are most useful when they are treated as production infrastructure, not a drawer full of shell scripts. Put hard policy in tiny synchronous gates. Put telemetry and slow work in background hooks, queues, daemons, or OpenTelemetry. Then measure the result per hook, per event, and per agent session.

The test is simple: if a hook cannot safely block the agent, it should not be in the foreground path.

Get started

Deploy your fleet.

Put a fleet of sandboxed agents to work on your own infrastructure, provisioned in seconds and watched live from one console.

Get started →

Admin-provisioned · Self-host in one command · Your data never leaves your VM