Knowledge Base · Learning paths
Prompt Caching in Large Language Models: A Detailed Explanation
This article explains the core principles of Prompt Caching technology in large language models (LLMs). By distinguishing between static and dynamic context and leveraging KV Cache to skip redundant Prefill computations, it can reduce repeated token costs for long-context AI agents by up to 90%. Using Claude's 92% cache hit rate as a real-world example, we analyze its architectural design and significant cost-saving benefits.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
🔗 Original post link: https://x.com/_avichawla/status/2044670188998803855
A Case Study: How Claude Achieves 92% Cache Hit Rate
Every time an AI agent takes its next step, it sends the entire conversation history back to the LLM.
This includes the system instructions, tool definitions, and the project context it already processed three turns ago. All of this content is re-read, re-processed, and re-billed on every single turn.
For long-running agentic workflows, this kind of repeated computation is often the single most expensive part of your entire AI infrastructure.
If a system prompt contains 20,000 tokens and is reused across 50 turns, that means 1 million tokens of redundant computation are being billed at full price without creating any additional value. And this cost keeps accumulating across every user and every session.
The solution is prompt caching. But if you want to use it effectively, you first need to understand how it actually works under the hood.
Static Context vs. Dynamic Context
Before optimizing your prompt, you must first figure out which parts will change and which parts will stay the same.
Every agent request is essentially composed of two fundamentally different types of content:
-
Static prefix that remains unchanged across multiple turns: system instructions, tool definitions, project context, and behavioral guidelines.
-
Dynamic suffix that grows with every turn: user messages, assistant responses, tool outputs, and terminal observations.
It is precisely this separation that makes prompt caching possible. The infrastructure saves the mathematical state corresponding to the static prefix, so that when subsequent requests reuse the exact same prefix, it can skip that portion of the computation entirely and read the result directly from memory.
Once you truly internalize this mechanism, all the architectural design decisions discussed later in this article will feel completely natural.
How Does KV Cache Work?
To understand why caching is so effective, you first need to know what a transformer is actually doing under the hood when processing a prompt.
Every LLM inference request is divided into two distinct phases:
-
Prefill phase: Processes the entire input prompt at once. The model performs dense matrix multiplications across all tokens in the context to build internal representations. This stage is compute-bound and is by far the most expensive part.
-
Decode phase: Generates output tokens one by one. Each new token is appended to the sequence, and the model continues to predict the next one. This phase is primarily memory-bound, as it mainly involves reading previous states rather than repeating heavy computation.
During the prefill phase, the transformer computes three vectors for each token: Query, Key, and Value. The attention mechanism uses these vectors to determine the relationships between tokens. For any given token, its Key and Value vectors only depend on the tokens that came before it. Once computed, they never change again.
Without caching, these Key and Value tensors are discarded at the end of each request. The next request starts from scratch and recomputes everything. For a 20,000-token prefix, this means 20,000 tokens worth of attention computation are performed redundantly.
The purpose of KV cache is to persist these tensors on the inference server, indexed by a cryptographic hash of the token sequence. When a new request arrives with the same prefix and the hash hits, the system can directly retrieve these tensors from memory, completely skipping the prefill computation for that portion of the prompt.
This reduces the computational complexity per generated token from O(n²) to O(n). If a 20,000-token prefix is reused across 50 turns, the savings become extremely significant.
Economic Benefits
What truly makes this architectural design so critical is the pricing model behind it.
Cache read is priced at 0.1× the base input price — meaning every cached token that hits delivers a 90% discount. Cache write is priced at 1.25×, meaning you pay a 25% premium to store the KV tensors. For caches extended to one hour, the price is 2.0×.
The chart below shows exactly how this pricing looks across Anthropic’s Claude models:
This math only makes sense when the cache hit rate is sufficiently high. In production environments, the best real-world example is Claude Code.
A 30-Minute Claude Code Programming Session
The entire design of Claude Code revolves around one central goal: keeping the cache in a hot state at all times.
Below is what a real 30-minute programming session looks like from a billing perspective.
Minute 0: Claude Code first loads its system prompt, tool definitions, and the CLAUDE.md file from the project. This payload exceeds 20,000 tokens. Since all these tokens are appearing for the first time, this is the most expensive moment of the entire session. But you only have to pay for it once.
Minutes 1–5: You begin issuing instructions. Claude Code dispatches the Explore Subagent to browse the codebase, open files, and run grep commands. All of this content is appended to the dynamic suffix. Meanwhile, the 20,000-token static prefix is now being read from cache, with its price dropping from $3.00/MTok to $0.30/MTok.
Minutes 6–15: The Plan Subagent receives a summarized brief rather than the raw results, because passing the original output would unnecessarily bloat the dynamic suffix. It generates an implementation plan. Once you confirm it, Claude Code begins actually modifying the code. In every round, the static prefix is read from cache. The cache hit rate climbs above 90%, and each access refreshes the TTL, continuously keeping the cache in a hot state.
Minutes 16–25: You continue requesting changes. This means more tool calls, more terminal output, and more context being accumulated into the dynamic suffix. By this point, the entire session has processed hundreds of thousands of tokens, yet every round still reads that 20,000-token foundation from cache.
Minute 28: You run /cost in the terminal. Without caching, processing 2 million tokens at Sonnet 4.5’s pricing would cost about $6. With caching and a 92% hit rate, 1.84 million of those tokens were cache reads. The final total cost drops to just $1.15 — an 81% reduction for a single task.
This is what a hot cache looks like. You pay for the static foundation only once, after which you can keep reading it almost for free. The only part that continues to incur charges is the ever-growing dynamic tail.
How Fragile Hash-Based Caching Really Is
One of the most counterintuitive things about prompt caching is this:
“1 + 2 = 3” can hit cache, but “2 + 1” will miss immediately.
The infrastructure hashes the entire token sequence from the beginning. If any part of that sequence changes — even something as small as swapping the order of two elements — the hash value changes, and the entire prefix is recomputed at full price.
This is not a trivial implementation detail. It is the core constraint around which nearly all of Claude Code’s engineering decisions are built.
The following are real issues that have occurred in production and caused cache invalidation:
- Injecting a timestamp into the system prompt, causing a brand-new hash on every request.
- A JSON serializer that inconsistently ordered tool schema keys across requests, immediately invalidating the prefix.
- An AgentTool that updated its parameters mid-session, instantly wiping out the entire 20,000-token cache.
This leads directly to three rules:
-
Never modify tools mid-session. Because the tool definitions are part of the cached prefix, adding or removing even a single tool will invalidate all downstream caches.
-
Never switch models mid-session. Caches are model-specific. If you switch to a cheaper model during a conversation, you must rebuild the entire cache from scratch.
-
Never update state by modifying the prefix. Instead of editing the system prompt, Claude Code appends reminder tags to the next user message. This keeps the prefix itself unchanged.
Apply This Methodology to Your Own Agent
Whether you’re using Claude Code or building your own agent from scratch, the underlying rules remain exactly the same.
Organize your prompt in the following order:
-
Place system instructions and behavioral rules at the very top, and never modify them mid-session.
-
Load all tool definitions at the beginning. Do not add or remove tools during the session.
-
Follow with retrieved context and reference documents, keeping them as stable as possible throughout the entire session lifecycle.
-
Put conversation history and tool outputs at the very bottom. This section is your dynamic suffix.
If you have enabled auto-caching in the Anthropic API, the cache breakpoint will automatically move forward as the conversation grows. Without this capability, you must manually track token boundaries yourself — a single misjudgment can cause you to completely miss the cache.
When you’re approaching the context limit and need to perform context compaction, use cache-safe forking: keep the same system prompt, the same set of tools, and the existing conversation history, then append the compaction instruction as a new message. This way, the cached prefix can still be reused, and the only part that incurs fresh billing is the compaction instruction itself.
To verify that caching is actually taking effect, focus on these three fields in every API response:
cache_creation_input_tokens: Number of tokens written to cache.cache_read_input_tokens: Number of tokens read from cache.input_tokens: Tokens processed normally without caching.
You can calculate your cache efficiency using this formula:
cache_read_input_tokens / (cache_read_input_tokens + cache_creation_input_tokens)
Track this metric continuously, just like you would monitor uptime.
Core Takeaway
Prompt caching is not a feature that simply works once you flip a switch. It is an architectural discipline that you must design around.
The core idea is actually very simple: keep static content stable at the top, and let dynamic content grow only at the bottom. The infrastructure hashes the prefix, stores the KV tensors, and gives you a 90% price discount on every subsequent read.
But the real challenge lies in the details. Don’t inject timestamps into the system prompt, don’t reorder tool definitions, don’t switch models mid-session, and never modify anything before the cache breakpoint.
Claude Code provides the best demonstration of this mechanism at scale: 92% cache hit rate and 81% cost reduction. If you are building agents but have not designed your architecture around prompt caching, you are essentially leaving the vast majority of your profit margin on the table.
If you enjoyed this tutorial:
Find me → @_avichawla
Every day I share tutorials and insights on DS, ML, large language models (LLMs), and retrieval-augmented generation (RAGs).