Skip to content

Enterprise Cost Control

Enterprise cost control covers how Claude Code spend is tracked and capped: per-session and per-team visibility through /cost, /stats, /context, and OpenTelemetry metrics; hard guardrails for automation such as --max-budget-usd and --max-turns; and model routing that reserves Opus 5 for demanding work while routing everyday tasks to Sonnet 5 and Haiku 4.5. Costs scale with context size and conversation length.

Your team’s Claude Code API bill tripled this month, finance wants a hard cap by Friday, and nobody can tell you which projects or people are driving the spend. Security wants audit logs on top of it. The instinct is to build a homegrown gateway that meters every request — but Claude Code already ships the visibility and guardrails you need.

Without telemetry you are guessing. With it, one dashboard answers every question finance, engineering, and security are asking.

  • A per-session and per-team way to see token spend using /cost, /stats, /context, and the status line — no custom telemetry code required
  • An OpenTelemetry export that feeds claude_code.cost.usage and claude_code.token.usage into a dashboard, broken down by team and model, plus the full metric and event catalog to build panels against
  • Hard budget guardrails for automation: --max-budget-usd, --max-turns, and per-subagent model: haiku
  • A model-routing policy that reserves Opus 5 for the work that needs it and pushes everyday tasks to Sonnet 5 and Haiku 4.5
  • Rate-limit guidelines that scale with team size
  • Copy-paste prompts to audit a bloated session, stand up an OTel exporter, and write a downgrade policy

Claude Code costs scale with context size and conversation length. Every message re-sends the system prompt, your CLAUDE.md, MCP tool definitions, and the accumulated conversation.

The three biggest, most-controllable drivers:

  • Stale context — leftover files and conversation from a previous task you never cleared
  • MCP tool definitions — every connected server adds tool schemas to context even when idle
  • Model choice — running Opus 5 for formatting and lint fixes that Haiku 4.5 handles for a fraction of the cost

Anthropic’s published baseline, useful as the number to compare your own dashboard against:

MetricValue
Average cost per developer per day$6
90th percentile daily cost$12
Monthly average (Sonnet)$100-200/developer
Monthly average (Opus-heavy usage)$300-500/developer

Automation, long-running sessions, and oversized context blow past that fast, which is why the guardrails below matter more than the averages.

You cannot manage what you cannot see, and Claude Code exposes usage at four levels.

  1. Check the current session. Run /cost in the REPL to see token usage and API cost for this session (API users), or /stats for usage patterns on Max/Pro:

    Total cost: $0.55
    Total duration (API): 6m 19.7s
    Total duration (wall): 6h 33m 10.2s
    Total code changes: 42 lines added, 18 lines removed
  2. See what’s eating context. Run /context to break down exactly what is consuming your window — system prompt, CLAUDE.md, MCP tool definitions, and conversation history. This is how you find the MCP server you forgot to disable.

  3. Keep usage visible continuously. Configure the status line to display context window usage so you see token pressure on every message instead of discovering it at invoice time.

  4. Roll up across the team. For API workspaces, set workspace spend limits and read cost and usage reporting in the Anthropic Console. The “Claude Code” workspace is created automatically on first authentication and centralizes org-wide tracking.

/cost is per-session. For a finance-grade view across every developer, export Claude Code’s OpenTelemetry metrics to your existing observability stack.

Environment variables are the whole setup — no code:

Terminal window
# Turn on telemetry and pick your exporters
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export OTEL_METRICS_EXPORTER=otlp # otlp, prometheus, or console
export OTEL_LOGS_EXPORTER=otlp
# Point at your OTLP collector
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector.company.com:4317
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer ${OTEL_TOKEN}"

To attribute spend to teams, tag every session with a resource attribute:

Terminal window
export OTEL_RESOURCE_ATTRIBUTES="department=payments,team=checkout"

Now claude_code.cost.usage and claude_code.token.usage arrive in your backend sliced by department, team, model, and user.account_uuid, so a single Grafana panel answers “which team spent what, on which model.”

For org-wide rollout, push these settings through the managed settings file instead of asking every developer to set env vars:

{
"env": {
"CLAUDE_CODE_ENABLE_TELEMETRY": "1",
"OTEL_METRICS_EXPORTER": "otlp",
"OTEL_LOGS_EXPORTER": "otlp",
"OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
"OTEL_EXPORTER_OTLP_ENDPOINT": "http://collector.company.com:4317",
"OTEL_EXPORTER_OTLP_HEADERS": "Authorization=Bearer company-token"
}
}

All metric and event names carry the claude_code. namespace — use the full name when building dashboard queries or your filters will not match.

MetricTypeWhat It Tracks
claude_code.session.countCounterSessions started
claude_code.lines_of_code.countCounterLines added/removed by Claude
claude_code.pull_request.countCounterPRs created
claude_code.commit.countCounterCommits made
claude_code.cost.usageCounterDollar cost of API calls
claude_code.token.usageCounterInput and output tokens
claude_code.code_edit_tool.decisionCounterEdit tool allow/deny decisions
claude_code.active_time.totalCounterActive session time in seconds

Cost lives in claude_code.cost.usage; the rest is what turns a spend chart into an ROI chart, because lines_of_code.count, pull_request.count, and commit.count are the output side of the same ratio.

EventWhat It Captures
claude_code.user_promptWhen prompts are submitted (content optional via OTEL_LOG_USER_PROMPTS=1)
claude_code.tool_resultTool call results and outcomes
claude_code.api_requestAPI call details (model, tokens, latency)
claude_code.api_errorAPI errors and rate limits
claude_code.tool_decisionPermission decisions for tool calls

api_error is the one security and platform teams ask for first: it is where rate-limit rejections show up before anyone files a ticket about Claude “being slow.”

Interactive sessions self-correct — a developer notices a runaway loop and hits Escape. Headless and CI runs do not. For any non-interactive claude -p invocation, cap the blast radius directly with print-mode flags:

Terminal window
# Stop spending past $5 on this run, and never exceed 8 agentic turns
claude -p "Triage failing tests in src/ and propose fixes" \
--max-budget-usd 5.00 \
--max-turns 8 \
--model sonnet

--max-budget-usd stops the run once API spend crosses the limit; --max-turns exits with an error after N agentic turns so a misbehaving loop can’t burn your budget unattended. Both are print-mode (-p) only.

The single highest-leverage cost lever is not metering — it is model choice. During Sonnet 5’s launch pricing through August 31, it costs two-fifths of Opus 5 per token; after that it moves to three-fifths. Haiku 4.5 is cheaper still — about a fifth of Opus — for mechanical work.

ModelRough price (input / output per Mtok)Reach for it when
Claude Fable 5~$10 / ~$50Plan-mode planning, complex multi-file refactors, greenfield builds, and final verification on the hardest tasks (2x Opus)
Claude Opus 5~$5 / ~$25Architecture decisions, multi-step reasoning, gnarly debugging, security audits
Claude Sonnet 5$2 / $10 through Aug 31; then $3 / $15Everyday coding, code review, most bug fixes, refactors, test writing
Claude Haiku 4.5~$1 / ~$5Formatting, lint fixes, comments, high-volume mechanical edits, trivial subagents

See the model comparison for full pricing details. Claude Fable 5 sits a tier above Opus 5 at exactly twice its price. On a budget, treat it as a bracket rather than a default — escalate to Fable 5 (/model fable) for planning and final verification, and run implementation on Sonnet 5 or Opus 5. If you set Fable as your default, explicitly pin cheaper subagent models; subagents otherwise inherit according to their configuration rather than universally auto-routing to cheaper tiers.

Switch mid-session with /model, or set a default in /config.

Trimming context before it trims your budget

Section titled “Trimming context before it trims your budget”

Token cost is a direct function of context size. Claude Code auto-compacts near the limit and caches the system prompt, but the cheap wins are habits.

Clearing, compacting, and where the compaction rules live

Section titled “Clearing, compacting, and where the compaction rules live”
  • /clear between unrelated tasks. Stale context is re-billed on every subsequent message. Use /rename before clearing so you can /resume later.

  • Guide compaction. /compact Keep test output and code changes. Summarize discussion. tells Claude what to keep when it summarizes.

  • Write the compaction rule down once. Put it in CLAUDE.md so you are not retyping it every session:

    # Compact instructions
    When compacting, preserve test output, error traces, and file paths. Summarize discussion and reasoning.
  • Offload to hooks. A PreToolUse hook can grep a 10,000-line log down to the matching errors before Claude ever reads it, turning tens of thousands of tokens into hundreds.

  • Move workflow instructions out of CLAUDE.md into skills. CLAUDE.md loads at session start and is billed even on unrelated work; skills load on demand. Keep CLAUDE.md under ~500 lines.

  • Install code-intelligence plugins for typed languages. They give Claude precise symbol navigation instead of grep-then-read-many-files, cutting exploratory token spend on TypeScript, Go, Rust, and similar codebases.

  • Tune adaptive reasoning. For simple tasks, lower the effort level with /effort or the /model slider. A positive MAX_THINKING_TOKENS cap works only after enabling fixed-budget mode on Opus/Sonnet 4.6; Fable 5 thinking cannot be disabled. Thinking tokens bill as output.

Each connected MCP server adds tool definitions to your context, consuming tokens even when idle:

  • Run /context to see what consumes space, then /mcp to disable servers you are not using
  • Prefer CLI tools (gh, aws, gcloud, sentry-cli) over MCP servers where possible — they add no persistent tool definitions to context
  • Set ENABLE_TOOL_SEARCH=auto:5 to trigger MCP tool search when tool definitions exceed 5% of the context window (the default trigger is 10%). Deferred tools only enter context when actually used, so a lower threshold trims idle definitions

Subagents have their own context windows, which is what makes them a cost lever rather than just an organizational one. Use them for verbose operations (reading many files, running test suites), for parallel work that would otherwise bloat the main context, and for repetitive edits across many files.

The saving only lands if you pin the model. Use model: haiku for trivial subagents and model: sonnet for ones that need real reasoning:

---
name: test-runner
description: Runs the test suite and returns only failures
tools: [Bash, Read]
model: haiku
---
You run the project's test command, then summarize only failing tests and their
error messages. Never paste full passing output.

For API workspaces, per-user limits should fall as the team grows, because not everyone is active concurrently:

Team SizeTPM per UserRPM per User
1-5200k-300k5-7
5-20100k-150k2.5-3.5
20-5050k-75k1.25-1.75
50-10025k-35k0.62-0.87
100-50015k-20k0.37-0.47

Treat these as starting points and watch claude_code.api_error for rate-limit rejections rather than waiting for complaints.

  • /cost shows pennies but the bill is huge. You are on a subscription where /cost is not your invoice, or spend is coming from CI keys that never run /cost interactively. Reconcile against Console workspace reporting and per-key usage, not session output.
  • Telemetry data never appears. Check that CLAUDE_CODE_ENABLE_TELEMETRY=1 is actually set, and that the OTLP endpoint is reachable from developer machines. Metrics export every 60 seconds by default, so wait at least that long before debugging further.
  • OTel dashboard is empty on Bedrock/Vertex/Foundry. Claude Code does not emit cost metrics through cloud providers. Track via the provider’s billing or a LiteLLM gateway with per-key spend; see LLM Gateway.
  • --max-budget-usd didn’t stop a runaway job. It only applies to print mode and only enforces against API-key billing. For subscriptions or interactive sessions there is no dollar meter — rely on workspace spend limits and --max-turns.
  • Telemetry lags or floods your backend. Metrics export every 60s and logs every 5s by default. Tune OTEL_METRIC_EXPORT_INTERVAL, and use the OTEL_METRICS_INCLUDE_* cardinality controls to keep storage costs down — a per-session-ID metric explosion can cost more than the Claude usage you are tracking.
  • Rate limits bite during onboarding or training. The per-user guidelines assume average concurrency. For a week where everyone is in the tool at once, raise the limits temporarily or stagger the sessions.
  • Costs are higher than expected with no obvious culprit. Run /context: large MCP configurations and bloated auto-memory files inflate every single request, and a session that was never cleared keeps re-billing work you finished yesterday.
  • A model downgrade tanks quality. Cost cuts that produce broken code are not savings. Keep Opus 5 available for the hard 10% and measure rework, not just token spend.
  • Leaving Fable 5 as your default without a usage-credit budget. Since July 20, 2026 it is permanently included on Max and Team Premium at up to 50% of weekly usage limits, but on Pro and Team Standard it bills usage credits at 2x Opus rates. Scope it back to planning and final verification unless the extra spend is deliberate.

Effective cost control is about balance: maximize value, eliminate waste. Get visibility first with /cost, /stats, and OTel; then apply model routing and guardrails. Most teams cut 30-50% without touching velocity — just by clearing context, right-sizing models, and turning off MCP servers they forgot were running.