In real-world logs across seven typical development tasks on Opus, the model read roughly 160 million tokens while generating only about 500,000—around 200 tokens read for every token written. In another week-long measurement of active work, a client accumulated 2.37 billion input tokens, yet 96% of that volume was served as cache reads and accounted for only 40% of the final bill.
Meanwhile, one engineer managed to burn through 76% of their weekly quota in less than 24 hours inside a single session. The culprit is almost never typing too much or getting long answers: quotas are drained by silent server-side cache invalidations, heavy models running routine background calls, and endless conversations that never get cleared.
For a baseline, it helps to check Anthropic's official enterprise deployment benchmarks: on average, a developer spends around $13 per active day and $150–250 per month on Claude Code, and 90% of users stay under $30 per day.
Large companies like Uber set a $1,500 monthly cap per engineer per tool not for day-to-day work, but to guard against tail risk—when a runaway agent burns weeks of budget in a couple of hours. By the end of this lesson, you will understand the exact architecture of prefix caching and eliminate the three habits that trigger cold context recomputation.
Prefix Layer Ordering: Why a Single Edit at the Top Invalidates the Entire Cache
Prompt Caching prefix layers (tools → system → project context → messages), two TTL buckets (5m and 1h), and three habits that burn up to 80% of quota (/model switching, long pauses, all-day chats).
A language model has no working memory between messages. Every time you send a prompt or the agent executes another tool call, Claude Code re-transmits the entire request structure to the server: tool definitions, the system prompt, project memory files, and the full accumulated conversation along with terminal logs.
To avoid charging full price for re-reading the same hundreds of thousands of tokens on every turn, Anthropic API and Claude Code use Prompt Caching—server-side retention of the already-processed portion of a request. Writing a block to cache carries a markup (1.25× the base input rate for 5-minute storage and 2× for 1-hour storage), while subsequent hits against the cached prefix cost orders of magnitude less.
Cache Read Cost (% of Base Input Rate)
Notice the gap between a cold recompute and a cache hit on flagship models: on Opus 5.5 ($0.20 per million read tokens) and Sonnet 5.5 ($0.10), the discount reaches 95%, and on Fable 5.2 ($0.20) it hits 97.5%. The entire economics of Claude Code subscriptions and rate limits depends on keeping your cache hit rate above 90%.
The critical mechanical detail is that the server does not cache individual files or paragraphs selectively—it validates the request strictly top-to-bottom via an exact prefix match. In Claude Code, the layers are stacked in a rigid sequence:
- Tools layer (
tools): built-in tools (Bash,Read,Edit) and definitions of connected MCP servers. - System prompt (
system): core agent behavior instructions and environment directives. - Project context (
project context): rootCLAUDE.md,Auto Memoryfiles (MEMORY.md), and global rules not scoped to path globs. - Message history (
messages): your prompts, reasoning traces, model replies, and tool call outputs.
If even a single token changes in an upper layer, the entire tower below it loses its cache immediately, and the server recomputes the remaining tail from scratch. In the Messages API, the caching boundary is set with "cache_control": {"type": "ephemeral"}: in automatic mode, the marker advances to the last cacheable block as the conversation grows, while manual mode allows up to 4 explicit breakpoints.
Additionally, Claude Code's cache is tied to a specific machine and working directory because the upper prefix automatically includes absolute paths to Auto Memory, the current working directory, the operating system, the shell, and the initial git status snapshot. Parallel sessions in the same folder can reuse a shared prefix, whereas a later session only hits the old cache if the repository's initial Git snapshot has not changed.
It is equally important to know which common actions do not break your warm cache, so you don't optimize the wrong things:
- Editing code files or
CLAUDE.mdmid-session:CLAUDE.mdis read once at startup and is only refreshed in the prefix after/clear,/compact, or a restart. - Adding MCP servers with deferred loading: in current versions of Claude Code, MCP schemas are loaded on demand via deferred tool search, so adding them on the fly only invalidates the cache if tool search is disabled or unsupported by the model.
- Running
/rewindand/recap: rolling back history via/rewindreturns the conversation to a previously cached prefix, and/recapruns without breaking the chain. - Launching subagents and
/fork: a standard subagent opens its own context without disturbing the parent chat's prefix, while/forkand fork-subagents inherit the parent's prefix and immediately read from its cache.
Two TTL Buckets and the Trap of a Timer Ticking From Request Start
Beyond prefix matching, every cache entry has an inactivity Time To Live (TTL). Inside Claude Code, requests are split into two independent TTL buckets with different defaults:
- Main conversation bucket: covers your interactive terminal turns, one-shot
claude -pruns, and Agent SDK calls. On a consumer Claude subscription within the included limit, this bucket defaults to a 1-hour TTL. - Background calls bucket ("everything else"): covers subagents, workflows, in-process teammates, forks, context compaction, and title generation. Even on a subscription, this bucket defaults to just 5 minutes.
The moment you switch to a direct API key, a cloud provider like Bedrock or Vertex, or your subscription exceeds its included limit and enters , both buckets shrink to a 5-minute default TTL.
The biggest trap lies in when the clock starts: the TTL timer ticks from the start of the request that wrote or read the cache, not from when the model finishes streaming its reply. If you kick off a heavy run on Opus 5.5 or Fable 5.2 and the model thinks and streams for 4 minutes, by the time the input prompt reappears, only 1 minute remains on a 5-minute cache. Every cache hit resets the timer for free, but a single one-minute pause after a long response turns the next turn into a cold recompute.
A telling measurement from a real 400,000-token session: a short ping keeping the cache warm cost roughly $0.08 in quota, whereas rebuilding the prefix after it cooled down during a pause consumed about $3.50 in a single turn—nearly a 44× difference.
Starting with Claude Code v2.1.242, you can control each bucket's TTL explicitly via user settings in ~/.claude/settings.json or environment variables. Here is a baseline config that extends subagent caching to one hour when you run long-lived background helpers.
{
"promptCacheTtl": "1h",
"subagentPromptCacheTtl": "1h"
}
The promptCacheTtl and subagentPromptCacheTtl keys accept strictly two values: "5m" or "1h".
When settings are specified across multiple layers, a strict top-down override hierarchy applies: FORCE_PROMPT_CACHING_5M=1 overrides everything, followed by bucket env vars (CLAUDE_CODE_PROMPT_CACHE_TTL and CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL), then keys in settings.json, then experimental.cacheTtl in skill frontmatter (v2.1.248+), the legacy ENABLE_PROMPT_CACHING_1H=1 flag, and finally the bucket default.
To verify which TTL your request actually used in your environment—especially behind a corporate gateway or API—run a quick JSON-mode test.
claude -p "hello" --output-format json
In the command output, inspect the nested usage.cache_creation object and check ephemeral_1h_input_tokens and ephemeral_5m_input_tokens. If tokens landed in ephemeral_5m_input_tokens despite expecting a 1-hour cache, either a higher-priority flag is set, the provider does not support 1-hour TTL, or your subscription has already rolled over to usage credits.
Three Habits That Burn Up to 80% of Your Limit: /model Switching, Pauses, and All-Day Chats
Now let's examine three everyday habits that cause even experienced developers to burn through a weekly limit in a single evening, even when individual prompts look harmless.
Habit 1 — switching /model mid-session. Imagine spending an hour designing a module on Opus 5.5 with 100,000 tokens in history, and then needing a quick answer: "Which file holds the logger config?" It is tempting to run /model haiku to save tokens.
Because each model has a completely isolated cache, switching models mid-chat invalidates the entire 100,000-token prefix. Haiku 5.5 must re-read and re-cache the whole history from scratch at the full input rate, and by the time you switch back to Opus 5.5, the original pass's cache may have already expired or been evicted. Since v2.1.238, /model displays a cache-reset warning, yet many developers click confirm out of habit.
Three hidden traps fall into the same bucket: toggling fast mode via /fast (which maintains a separate cache), using the hybrid opusplan mode (which switches models between planning and execution every time you enter or exit Plan Mode), and invoking custom skills with a dedicated model field but without context: fork.
By contrast, adjusting reasoning depth via /effort on current Fable 5.1+, Opus 5.5, Sonnet 5.5, and Haiku 5.5 models over a subscription or direct Anthropic API no longer resets the cache. Resets only persist on Bedrock, Google Cloud Agent Platform, Claude apps gateway, in HIPAA mode, and when CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS is set.
If you need to clarify a couple of quick details halfway through a long Opus or Fable session, do not switch the main chat's model with /model and avoid opusplan in choppy workflows with frequent returns to Plan Mode. Instead, either stay on the current model and lower /effort, or delegate the one-off lookup to a Haiku or Sonnet subagent—it gets its own isolated chat while your main prefix stays intact.
Habit 2 — long pauses and unmanaged background processes. With a main chat on a subscription, stepping away for 10–15 minutes is safe, but a 90-minute lunch break followed by resuming the same thread guarantees a cold recompute on the next turn. With subagents, the margin is 12× tighter: their 5-minute TTL expires while you are simply reading a diff. That is exactly how 76% of a weekly quota vanished in a day: seven subagents in one session sat idle waiting for instructions for over five minutes, and every follow-up turn paid to rebuild their entire context.
On top of that, subagents inherit the main chat's model by default and account for up to 47% of total spend in real-world logs: in one audit, 2,000 background requests on Fable 5.2 burned over $500 at API rates instead of ~$80 on Opus.
Silent leaks also come from background loops that repeatedly re-run full context without your input: /loop cycles, checks on stalled background bash processes, overnight /goal tasks lacking a strict stop condition, incoming cross-session messages (held back via crossSessionInbound: "hold"), and background auto-compaction of idle 1-hour sessions (disabled in v2.1.290+ via idleCompaction: false). Note that since v2.1.246, background goal check-ins are capped at three idle cycles and can be disabled completely with CLAUDE_CODE_GOAL_CHECKIN_MINUTES=0.
It is also critical to update Claude Code past v2.1.316: in older builds, the subagent background status bar re-read the entire conversation every 30 seconds (consuming 16.4% of team budget in ), whereas switching to compact summaries via Haiku 5.5 cut that overhead by 99%.
Habit 3 — one chat for the entire workday and a bloated CLAUDE.md. On models with a 1-million-token window, CLI auto-compaction only triggers around 967,000 tokens by default. As a single chat swells with a morning bug, an afternoon email, and an evening database migration, sets in, and every turn drags a massive tail.
Breakdown of a $1,300 Main-Chat Budget by Context Size
As shown in this $1,300 weekly budget breakdown, nearly three-quarters of all spend ($946) burned in the session tail past the 400,000-token mark, mostly on autonomous /goal runs. A bloated CLAUDE.md compounds the problem: in an effort to "fix every mistake once and for all," teams inflate it to 400–800 lines of contradictory rules loaded into every single session.
A telling benchmark from Anthropic engineers: moving to the Opus 5 and Fable 5 generations, they cut roughly 80% of redundant instructions from Claude Code's own system prompt with zero drop in eval scores, and Boris Cherny recommends pruning outdated skills every six months to see whether the newer model handles them on its own. Anything not needed on every step belongs in SKILL.md skills with progressive disclosure—where only a short YAML header enters the prefix at startup—keeping CLAUDE.md under 200 lines.
| Habit | Which prefix layer or limit it breaks | What to do instead |
|---|---|---|
Switching /model mid-chat or frequent opusplan transitions | Full cache reset due to per-model cache isolation (including /fast and skills without context: fork) | Pick the model before starting; adjust flexibility with /effort (preserves cache on API/subscription) or a one-off subagent |
| Long pauses (>1 hour in main chat, >5 min for subagents) and overnight loops | Cold recompute of the entire context (1.25× / 2×) and 47% background quota burn on an expensive model | Close subagents right after a single task, set a lighter CLAUDE_CODE_SUBAGENT_MODEL, run /clear after lunch |
"One chat all day" with 967K autocompact and a thick CLAUDE.md | Per-step cost spike past 400K (73% of spend) and constant ballast in project context | Follow "one task, one session" via /clear, set /autocompact 400k, and move playbooks into SKILL.md |
Simple Rules for Keeping Your Cache Warm and Budget Under Control
Rather than guessing where tokens are leaking or why your cache hit rate dropped in the current session, run a five-minute audit right in the Claude Code terminal.
- Pull real telemetry with
/usage: starting in v2.1.251, it prints thePrompt cache (main)line with hit rate, miss count, andwarm/coldstatus, and since v2.1.260 it flags the probable cause (likely cause: tool definitions changed). ToggleD(day) andW(week) and pressFto auto-fix if the UI highlights an imbalance—just remember that/usageonly tracks the local machine. - Audit tool and instruction share via
/contextand/doctor prompt-audit: verify that a forgottenCLAUDE.mdin an adjacent folder isn't eating thousands of tokens at startup and that unused MCP servers aren't bloating the header. - Lock in early compaction and cheaper subagents: run
/autocompact 400k(or setCLAUDE_CODE_AUTO_COMPACT_WINDOW=400000) so conversations never drift into the expensive degradation zone. In~/.claude/settings.json, set"CLAUDE_CODE_SUBAGENT_MODEL": "sonnet"(or"haiku"for simple search). - Cap tail risk on autonomous runs: when calling
claude -pin scripts, always pass--max-budget-usd. And if you hit the ceiling on Max or Ultra plans, check Settings > Usage onclaude.ai—around major releases like Fable 5.2, Anthropic occasionally drops one-time, time-limited free limit resets there.
The rule going forward is simple: keep the top of your prefix motionless, don't pay flagship rates where Sonnet or Haiku can handle the job, and reset sessions cleanly between distinct tasks. Once your caching foundation is protected from cold resets, the next step is cutting the stream of noisy logs and verbose code with open-source compression utilities—which we will tackle in Lesson 2.
Apply This Right Now
- Run
/usagein an active project and inspect the cache hit rate on thePrompt cache (main)line along with any listed miss causes. - Run
/doctor prompt-audit, trim your rootCLAUDE.mdunder 200 lines (keeping a routing map and hard constraints), and move long playbooks intoSKILL.md. - Set
/autocompact 400kfor your current model and add"CLAUDE_CODE_SUBAGENT_MODEL": "sonnet"to your user~/.claude/settings.json. - Check your Claude Code version (you want v2.1.316+ for the subagent status-bar savings) and disable unnecessary idle check-ins when using
/loopor/goalviaCLAUDE_CODE_GOAL_CHECKIN_MINUTES=0.


