Prompt caching is the single biggest lever for cutting Claude Code costs on long sessions. It lets the API skip reprocessing your entire conversation history on every turn, billing you roughly one tenth the normal input rate for repeated prefixes. This guide covers how the cache is organized, the eight actions that invalidate it, the eight actions that preserve it, and how to read the token counts that tell you whether prompt caching is actually working.

Prompt Caching: What You’ll Learn
Prompt caching happens inside the API, not in your terminal, so you never see a “cache hit” message flash by, and the only visible evidence is the token breakdown that /cost reports. By the end you will know the three layers the cache is organized into, the eight actions that wipe it, the eight that leave it untouched, and how to structure a session for maximum hits. The system rewards predictable behavior and punishes unnecessary changes.
What Is Prompt Caching?
The Claude API avoids reprocessing the beginning of your conversation on every turn through prompt caching. Instead of reading your full system prompt, tool definitions, CLAUDE.md, and message history from scratch on every turn, the API matches the start of each new request against content it already processed, and the match is exact and byte for byte. If the first several thousand tokens match a previous request, they are served from the cache at roughly ten percent of the standard input price, but if even one character changes in that prefix, everything after the change point is recomputed from scratch.
The API does not cache your CLAUDE.md separately from your tool definitions or messages; it caches one continuous prefix, which is the key conceptual point. The cache is a single prefix match, not a collection of independent parts, much like a streaming buffer where any change flushes everything downstream of it.
How the Cache Is Organized: Three Layers
Every request Claude Code sends is ordered so rarely changing content comes first and frequently changing content comes last. From most stable to most volatile, the three layers are the system prompt, the project context, and the conversation.
Layer 1: System Prompt
The system prompt contains core instructions, tool definitions, and output style settings, and it changes only when tool definitions change or when Claude Code itself is upgraded. Because it sits at the front of every request it is the most cache friendly layer, and it is also the largest, since tool definitions alone can consume thousands of tokens. The biggest, most expensive layer is also the most stable, so it almost always hits the cache.
Layer 2: Project Context
The project context layer holds your CLAUDE.md file, auto memory, and any unscoped rules, and it is read once at session start and again after /clear or /compact, so it changes less often than the conversation but more often than the system prompt. Because it sits between the system prompt and the conversation, it acts as a bridge. If it changes, the conversation layer after it must recompute, but if it stays stable, only the conversation layer grows.
Layer 3: Conversation
The conversation layer is your messages, Claude’s responses, and tool results, and it changes every single turn as each new turn appends to the end, so the prefix up to the previous turn still matches the cache. This is why caching works on a growing conversation: the old turns are a stable prefix for the new ones. Every turn adds tokens, but only the new tokens are uncached, so over a long session the savings compound.
Beyond the Prefix: Model and Effort
Two things are not part of the prompt text but are part of the cache key: the model has its own cache, so switching from Sonnet to Opus forces a full recompute, and the effort level has its own cache for the same model. Prompt caching rewards picking a model and effort level at the top of your session and sticking with them. Save /compact for natural break points, because the fewer mid task changes you make, the higher your cache hit rate.
Where the Cache Lives
Cache storage depends on how you authenticate. The table below shows where cached content resides for each common setup, which helps you reason about data residency and why behavior may differ across auth methods.
| Auth Method | Cache Location |
|---|---|
| API key | Anthropic infrastructure |
| Claude subscription | Anthropic infrastructure |
| Claude Platform on AWS | Anthropic infrastructure |
| Amazon Bedrock | Your cloud provider (AWS) |
| Google Cloud Agent Platform | Your cloud provider (GCP) |
| Microsoft Foundry | Anthropic infrastructure |
| Custom ANTHROPIC_BASE_URL / LLM gateway | Wherever requests are forwarded |
If you use a custom gateway, caching behavior depends on what that gateway does with requests. Some gateways strip headers or rewrite payloads in ways that break the prefix match, so if your hit rate is unexpectedly low, check caching passthrough with your infrastructure team.
A Worked Example: High Cache Hits vs Cache Misses
To see prompt caching in action, consider two developers working on the same feature whose habits produce wildly different costs. The difference is entirely in how well each preserves the cache prefix.
The Disciplined Session
Developer A picks Sonnet at effort medium and reads three files, implements a function, reviews it, adds a test, reviews that, and asks for a refactor, never switching models, changing effort, or compacting mid task. On each turn the system prompt, project context, and previous turns are served from cache, so only the newest turn’s tokens are billed at full rate, and her /cost shows cache_read_input_tokens near 38,000 versus about 2,000 cache_creation_input_tokens per turn.
Halfway through she wants to check something in a different model, so she finishes her current unit of work first and opens a new session for the switch, leaving the original cache intact. Her total cost is a fraction of what it would be without the cache, because prompt caching rewards this kind of disciplined, block focused work.
The Chaotic Session
Developer B starts the same task with different habits: he switches to Opus after three turns, switches back two turns later, changes effort from medium to high, compacts because the context feels long, then connects and disconnects an MCP server and upgrades Claude Code mid session. Each action invalidated the cache, forcing the next request to reprocess the entire history at full rate, so over twenty turns he paid full price on at least six occasions with cache_creation_input_tokens spiking to 30,000 or more.
The cost difference between these two sessions can be five to ten times, with the same model, task, and number of turns, because prompt caching is not a marginal optimization but the difference between cents and dollars. The lesson is simple: the cache rewards consistency, so pick your setup at the start and batch disruptive actions into natural break points between sessions.
Eight Actions That Invalidate the Cache
These eight actions force the API to recompute your prefix from scratch. Each one changes something in the cache key, breaking the exact prefix match, and understanding all eight is the core of effective prompt caching.
1. Switching Models
Running /model switches you to a different model, and each model maintains its own separate cache, so the next request after a switch reads your entire history from scratch with no cache hits. This includes switching between Opus plan mode and Sonnet execution when opusplan is active, as well as automatic model fallback on Fable 5. You cannot control fallback, but you can plan cache sensitive work for when model availability is stable.
2. Changing Effort Level
The cache is keyed by effort level combined with model, so running /effort to change from medium to high invalidates it just as thoroughly as switching models. Claude Code shows a confirmation dialog first, which gives you a moment to reconsider whether the change is worth the reset. Prompt caching works best when effort is chosen once and held steady, so pick one level per session block.
3. Turning On Fast Mode
Fast mode adds a request header that becomes part of the cache key, so the first request after enabling it has no cache hits, though after the first turn the header persists and toggling it off and back on within the same session keeps the cache intact as of Claude Code v2.1.86 and later. Enabling fast mode from a non Opus model also switches the model to Opus, triggering the model switch invalidation above. To get fast mode without a model switch, start on Opus first, then enable it.
4. Connecting or Disconnecting an MCP Server
MCP server tool definitions live in the system prompt layer, so connecting or disconnecting a server changes those definitions and the prefix; the advisor tool is the exception, since it does not invalidate the cache. Whether connecting invalidates depends on tool search behavior. Deferred tools, the default on supported models, are not loaded into the prefix and do not invalidate, while tools loaded into the prefix (when tool search is unavailable or disabled, on Haiku models, on Google Cloud, on custom gateways, or with alwaysLoad enabled) do invalidate it.
5. Enabling or Disabling a Plugin
Plugins can include skills, commands, agents, hooks, and MCP servers. Skills, commands, agents, and hooks never invalidate the cache because they are appended after the conversation rather than inserted into the prefix, and changes apply on /reload-plugins or in a new session. The exception is a plugin that includes MCP servers, which follow the MCP server rules above: if its server tools load into the prefix, toggling the plugin invalidates the cache.
6. Denying an Entire Tool
Denying a tool with a bare name like Bash or WebFetch removes it from context, and built in tools live in the system prompt layer, so removing them changes the prefix and invalidates the cache. This applies to bare names, Bash(*) style denies, and tool name globs using *. Scoped deny rules like Bash(rm *) do not invalidate the cache, because they only restrict specific uses without changing the tool definitions.
7. Compacting the Conversation
Running /compact replaces your conversation history with a summary, which invalidates the conversation layer because the old messages are gone, though the system prompt and project context layers are reused and project context reloads fresh. The summarization request itself reads the existing cache, so compacting is not as expensive as it seems. The post compaction turn rebuilds a cache on the shorter summary, making subsequent turns cheaper, so it is a tradeoff of one reset for a shorter prefix going forward.
8. Upgrading Claude Code
A new version updates the system prompt and tool definitions, which rebuilds the cache from scratch, but auto update applies on the next launch, never mid session, so an upgrade will not disrupt a running session. Set DISABLE_AUTOUPDATER=1 if you want to control when upgrades happen. Expect the first session in a new version to have lower hit rates until the new system prompt is cached, which resolves after a few turns.
Eight Actions That Preserve the Cache
These eight actions do not invalidate the cache. Some do not change the prefix at all, and others change things that are read only once and not reloaded, so knowing what is safe lets you work freely without worrying about cache resets.
1. Editing Repository Files
File contents enter the context only when Claude Code reads them, so editing a file on disk does not retroactively change the conversation history where the file was previously read. If you read a file, edit it externally, then ask about it, Claude reads the new version on the next read, but the old read stays as it was. You can freely edit files in your editor while Claude Code runs, because the cache only cares about what is in the conversation, not what is on disk.
2. Editing CLAUDE.md Mid Session
Your CLAUDE.md is read once at session start, so editing it during a session does not invalidate the cache, but it also does not apply the changes, which load on the next /clear, /compact, or restart. This is a common source of confusion: developers edit CLAUDE.md, expect Claude to immediately follow the new instructions, and are surprised when nothing changes. Plan your edits for the start of a session, or accept the compact cost to reload them mid session.
3. Changing Output Style
Output style is part of the system prompt, which is read once at session start, so changing it mid session does not invalidate the cache but also does not take effect until the next session or context reload. If you need a different output style, start a new session with it configured so the cache builds a fresh prefix around it. Trying to change style mid session is futile even though it does not break the cache.
4. Changing Permission Mode
Switching permission modes does not change the system prompt, so it does not invalidate the cache, and you can move between default, accept all, and plan modes freely. The exception is plan mode when opusplan is active, because that switches the model, which is a separate invalidating action. If you rely on the cache and use opusplan, treat plan mode toggling like model switching and do it at natural break points, not mid task.
5. Invoking Skills and Commands
Skills and commands inject content as user messages at the point of invocation, appended to the conversation rather than inserted into the system prompt, so invoking them does not invalidate the cache. The injected content simply extends the conversation prefix that subsequent turns build upon. Power users can invoke custom skills and commands freely, and the cache keeps serving prior turns while only the injected content is uncached.
6. Running /recap
The /recap command generates a summary for display purposes, appended as command output rather than replacing the conversation, so nothing in the prefix changes and the cache is untouched. You get a recap without paying any cache reset cost. Use /recap freely to remind yourself what happened earlier in a long session, because it is strictly additive and cache safe.
7. Rewinding the Conversation
Running /rewind truncates the conversation to an earlier turn, and the remaining history still matches the cache prefix up to that point, so rewinding preserves the cache for the retained turns and you do not pay a full recompute. This makes /rewind a cache friendly way to backtrack. Rewinding to the fork point and trying again is cheaper than compacting or starting over, and you only pay for new tokens added after the rewind point.
8. Spawning a Subagent
When you spawn a subagent, it builds its own cache based on its own system prompt and tools, so the parent’s cache is unaffected, though a forked subagent inherits the parent’s prefix and its first request reads the parent’s cache. Subsequent requests build the subagent’s own cache, which has a 5 minute TTL even on subscription plans that otherwise get 1 hour, so subagent caches expire faster. Use subagents for bounded tasks that finish within a few minutes to get the most from the cache.
Quick Reference: Invalidating vs Preserving Actions
Prompt caching comes down to knowing which actions break the prefix and which do not. The table below summarizes all sixteen actions covered above as a quick lookup when you are about to do something mid session.
| Invalidates the Cache | Preserves the Cache |
|---|---|
Switching models (/model) | Editing repository files on disk |
Changing effort level (/effort) | Editing CLAUDE.md (deferred until reload) |
| Turning on fast mode | Changing output style (deferred until reload) |
| Connecting or disconnecting MCP servers | Changing permission mode (except opusplan) |
| Enabling or disabling plugins with MCP servers | Invoking skills and commands |
| Denying an entire tool (bare name) | Running /recap |
Compacting (/compact) | Rewinding (/rewind) |
| Upgrading Claude Code | Spawning a subagent |
The pattern is clear: actions that change the system prompt or replace the conversation invalidate the cache, while actions that only add to the conversation leave it intact. When you are unsure, ask whether an action changes the system prompt or replaces existing turns; if yes, expect a reset, and if no, the cache is safe. Some preserving actions, like editing CLAUDE.md or changing output style, defer their effect until the next reload, because the system prioritizes cache stability over immediate settings changes.
Cache Lifetime and TTL
Cached content does not live forever. There are two TTL options, 5 minutes and 1 hour, and each cache hit resets the timer, so an active session with frequent turns can keep a cache alive well beyond the base TTL.
Your default TTL depends on your auth method. The table below summarizes the defaults and how to override them.
| Auth Method | Default TTL | Override |
|---|---|---|
| Claude subscription | 1 hour (auto, included in plan) | Drops to 5 min if on usage credits |
| API key | 5 minutes | ENABLE_PROMPT_CACHING_1H=1 for 1 hour |
| Amazon Bedrock | 5 minutes | ENABLE_PROMPT_CACHING_1H=1 for 1 hour |
| Google Cloud Agent Platform | 5 minutes | ENABLE_PROMPT_CACHING_1H=1 for 1 hour |
| Microsoft Foundry | 5 minutes | ENABLE_PROMPT_CACHING_1H=1 for 1 hour |
| Any method | Force 5 min | FORCE_PROMPT_CACHING_5M=1 |
If you are on an API key and sometimes pause for more than 5 minutes to read documentation or think through a design, enabling the 1 hour TTL can significantly improve your cache hit rate. Set the environment variable before launching Claude Code:
export ENABLE_PROMPT_CACHING_1H=1
claudeTo force 5 minute TTL for testing or debugging, use FORCE_PROMPT_CACHING_5M=1. It overrides any 1 hour setting and ensures caches expire quickly, which helps you reproduce cache miss scenarios on demand.
Cache Scope: Machines and Directories
The cache is effectively scoped to one machine plus one directory, because the system prompt embeds environment specific details like your working directory, platform, shell, OS version, and auto memory paths. Two sessions in different directories have different prefixes and do not share cache, while two sessions in the same directory on the same machine can share cache, so parallel sessions in the same repo benefit from each other. Sessions on different machines never share cache even in the same directory, because platform and OS version are part of the cache key, which is why a fresh machine feels more expensive on the first session.
Checking Cache Performance
Every API response includes two token count fields that tell you exactly how prompt caching is performing. These are the most important numbers for understanding your cost, and they appear in the /cost output.
cache_creation_input_tokens
This field reports how many tokens were written to the cache on the current turn, billed at the cache write rate, which is slightly higher than the standard input rate. Cache creation happens when new tokens enter the prefix that were not cached before, such as a new turn’s content or content after an invalidation.
cache_read_input_tokens
This field reports how many tokens were served from the cache, billed at roughly ten percent of the standard input rate. A high read to creation ratio means caching is working well, while a low ratio means you are paying to reprocess content that should have been cached.
Run /cost periodically during long sessions to check your ratio. A healthy session shows cache reads many times larger than creations, and if you see creation spikes, look back at the preceding turns, where you will usually find one of the eight invalidating actions.
# Check cost and cache performance mid-session
/costThe output breaks down input, output, cache read, and cache creation tokens with their costs. If cache reads dominate, the cache is doing its job, and if cache creations stay high across consecutive turns, something is repeatedly invalidating your cache.
Subagents and the Cache
When you spawn a subagent, it starts its own conversation with its own system prompt and tools, so it builds its own cache from scratch and the parent session’s cache is unaffected. A forked subagent inherits the parent’s prefix, so its first request reads the parent’s cache, but later requests build the subagent’s own cache, which has a 5 minute TTL even on subscription plans that normally get 1 hour. The practical takeaway for prompt caching is to keep subagent tasks bounded, because if a task runs more than a few minutes the subagent’s cache may expire between turns.
When to Disable Prompt Caching
Prompt caching can be disabled for debugging purposes, which is rarely necessary in normal use but can help isolate whether unexpected behavior is caused by stale cached content or by something else. Disabling it means every request is processed from scratch at full input rate.
Several environment variables control disabling, and each targets a specific model tier. Use the one matching the model you are debugging before launching Claude Code.
# Disable for all models
export DISABLE_PROMPT_CACHING=1
# Disable for specific model tiers
export DISABLE_PROMPT_CACHING_HAIKU=1
export DISABLE_PROMPT_CACHING_SONNET=1
export DISABLE_PROMPT_CACHING_OPUS=1
export DISABLE_PROMPT_CACHING_FABLE=1Use these only for debugging. In normal operation, caching should always be enabled, since disabling it can increase your costs by ten times or more on long sessions. Once you finish debugging, unset the variable and restart Claude Code to restore normal caching.
See the official prompt caching documentation on code.claude.com for the complete technical reference. It covers up to date details on TTL behavior and model specific caveats that go beyond this guide.
Prompt Caching: Common Mistakes to Avoid
The cache fails silently: there is no error message when you invalidate the cache, you just pay more. These four mistakes account for the vast majority of wasted cache.
- Switching models mid session. Each switch forces a full recompute of your entire history at full input rate. Fix: pick your model at session start and stick with it. If you need a different model, finish your current unit of work first and open a new session.
- Compacting unnecessarily. Compacting replaces your conversation with a summary, invalidating the conversation layer. Fix: only compact when your context is genuinely too large or at natural break points. Do not compact reflexively just because the context window feels long.
- Toggling effort level frequently. Effort changes invalidate the cache just like model switches. Fix: choose your effort level at the top of the session. If a specific task needs different effort, consider whether it deserves its own session rather than disrupting the current one.
- Connecting MCP servers mid task. Servers with tools loaded into the prefix invalidate the system prompt layer. Fix: connect MCP servers at session start before you begin working. If you need a new server mid task, accept the cache reset or start a fresh session.


Prompt Caching: Best Practices
- Pick your model and effort level at session start. Do not change them mid task. The cache rewards consistency above all else.
- Connect all MCP servers and configure plugins before your first turn. Adding tools to the prefix later invalidates the system prompt layer.
- Run
/costperiodically. A high read to creation ratio means the cache is working. Spikes in creation signal an invalidation. - Enable the 1 hour TTL on API key auth if you take thinking breaks. Set
ENABLE_PROMPT_CACHING_1H=1before launching Claude Code. - Keep subagent tasks bounded to a few minutes. Subagent caches use a 5 minute TTL even on subscription plans, so long tasks lose cache hits.
Prompt Caching: Frequently Asked Questions
Does prompt caching work with all Claude models?
Yes. It works across Haiku, Sonnet, Opus, and Fable, and each model has its own separate cache, so switching models invalidates it. Pick one model per session for best results.
How much does prompt caching save?
Cached tokens are billed at roughly ten percent of the standard input rate. On long sessions with stable prefixes, this can cut input costs by up to ninety percent.
What is the difference between cache creation and cache read tokens?
cache_creation_input_tokens are tokens written to the cache this turn, billed at the write rate. cache_read_input_tokens are tokens served from cache, billed at roughly ten percent of the standard input rate.
Does editing files on disk invalidate the cache?
No. File contents enter context only when Claude Code reads them, so editing files externally does not change the conversation history. The cache only cares about what is in the conversation, not what is on disk.
Should I disable the cache for debugging?
Only when isolating whether stale cached content causes unexpected behavior, using DISABLE_PROMPT_CACHING=1 temporarily. In normal use, always keep it enabled, since disabling it can increase costs tenfold on long sessions.
Prompt caching is the most impactful cost lever in Claude Code. It works by matching the exact prefix of each request against recently processed content, serving matched tokens at roughly ten percent of the standard rate. The eight invalidating actions, from model switches to MCP server changes, force full recomputes, while the eight preserving actions, from file edits to subagent spawns, leave the cache intact. Pick your model and effort once, configure tools at session start, check your /cost ratio regularly, and let prompt caching do the rest.