11B.4 Token Caching in Depth: How It Works, Who Supports It, and How to Use It
Lesson 03.7 showed you how to read cache fields from usage and price them. Lesson 11B.3 gave you the strategy: which caches exist and when each pays. This lesson answers the questions underneath: what is actually being cached, why must the prefix match exactly, how do the providers differ, when does caching lose money, and how do you debug a cache that is not hitting.
"Token caching" here means provider-side prompt caching: the provider keeps the computed state for a prompt prefix and skips recomputing it when a later request starts with the same prefix. It is not response caching and not semantic caching (Part 9 contrasts them).
What you'll learn
- What a KV cache is, why prefill is the part a cache removes, and why caching cuts input cost and time to first token but not output cost or decode speed
- Why the match must be an exact prefix: causal attention, block hash chains, and what engines like vLLM, SGLang and TensorRT-LLM actually do
- Cache locality: why caches live on individual machines, and what routing hints (
prompt_cache_key, session IDs) do - Provider by provider: Anthropic, OpenAI, Google Gemini, xAI, DeepSeek, Mistral, Azure, Bedrock, Vertex, Groq, Together, Fireworks, OpenRouter and self-hosted engines, in one comparison table
- The break-even formula, derived, and the cases where caching loses money
- Patterns with code: system prompt and tools, multi-turn chat, a large reused document, agent loops, few-shot libraries, keep-warm and pre-warm
- A runnable prefix-cache simulator that makes the rules visible
- A twelve-step debugging checklist and the hit-rate formulas
What you don't need
- API keys. The runnable sample is a pure-Python simulator; provider code is illustrative and marked so.
- A GPU. Part 2 explains the engine internals in prose and the simulator reproduces their hashing idea.
Setup
Python 3.11+ and the standard library only. Save the simulator as prefix_cache_sim.py and run it with python prefix_cache_sim.py.
uv init prefix-cache --bare --python 3.13 && cd prefix-cache
# nothing to install: the simulator uses only the standard libraryProvider details change often and many provider pages carry no date. Everything below was read from the providers' own pages on 20 November 2026; claims that could not be confirmed are marked unverified. Re-check prices and limits before you rely on them.
What you must be able to do after this lesson#
- Explain what a provider stores in a prompt cache and why only prefill is saved, not decode or output cost
- Explain why one changed character early in the prompt invalidates everything after it
- Structure a prompt so the stable prefix comes first and the variable part last
- Compute the break-even for caching and name three cases where it raises the bill
- Read cache fields in the usage object, including what input_tokens includes on Anthropic
- Diagnose a 0% hit rate with the debugging checklist
- Isolate tenants with per-tenant cache keys or salts
Why this matters for an AI engineer#
| Situation | What you need from this lesson |
|---|---|
| Your agent re-reads a 50k-token context on every step | Caching turns the re-read into a discounted read; know the layout rules that make it hit |
| Your bill did not drop after you "enabled caching" | The hit-rate formulas and the checklist in Part 8 |
| You must choose between Anthropic's 5-minute and 1-hour TTL, or OpenAI's 30-minute and 12-hour | The break-even formula in Part 5 |
| You are building on several providers | The comparison table in Part 4 |
| You self-host a model | Prefix caching in vLLM, SGLang, TensorRT-LLM and llama.cpp |
Common questions this lesson answers#
| Question | Where |
|---|---|
| "What exactly does the provider store?" | Part 1 |
| "Why does one changed token ruin the cache?" | Part 2 |
| "Does caching make the answer cheaper or faster to generate?" | 1.3 |
| "Which providers support it, and how?" | Part 4 |
| "When does caching cost me money?" | Part 5 |
| "Show me code." | Part 6 |
| "Why is my hit rate low?" | Part 8 |
Part 1: What is cached#
1.1 The KV cache#
A transformer processes a prompt in layers. In each attention layer, every token produces a key and a value vector, and every later token looks back at the keys and values of all earlier tokens. Those vectors are what the model "remembers" about the prompt. The KV cache is that stored set of keys and values for a sequence of tokens.
Two phases of generation use it differently (this is general transformer background, not a provider claim):
- Prefill processes all the prompt tokens in parallel and builds the KV cache. It is compute-heavy and is what makes the first token slow on long prompts.
- Decode emits one token at a time, reading the whole KV cache for each token. It is limited by memory bandwidth, and it produces the output you pay for.
Prompt caching keeps the prefill result. OpenAI's documentation says it directly: caching "reuses saved key-value (KV) states for a shared prefix... It stores KV tensors, not the tokens themselves." Anthropic's retention page adds that KV representations and cryptographic hashes of cached content are held in memory only and not stored at rest, and that Anthropic does not store the raw prompt text for caching.
1.2 What is not cached#
- The response. A cache hit still runs the model and generates a fresh answer. Output is unchanged by caching (Anthropic: "responses are identical to uncached ones"), and identical requests are not guaranteed identical outputs, as before.
- Your text as a lookup key. The lookup is by hash of the token prefix, not by comparing strings you could inspect.
- Anything after the first difference. Part 2.
1.3 What caching does and does not speed up#
| Metric | Effect of a prompt-cache hit |
|---|---|
| Input cost | Cut: cached tokens are billed at a discounted read rate |
| Time to first token | Cut roughly in proportion to the cached share of the prompt, because prefill is skipped |
| Output cost | No change |
| Decode speed (tokens per second) | No change. vLLM's documentation states the limit plainly: prefix caching "does not reduce the time of generating new tokens (the decoding phase)" |
| Rate limits | Provider-specific: Anthropic does not deduct cache reads from input-token limits; OpenAI says cached input tokens still count toward tokens-per-minute |
Launch-era latency figures from Anthropic's prompt-caching announcement: a 100,000-token book prompt went from 11.5 s to 2.4 s (-79%), a 10,000-token many-shot prompt from 1.6 s to 1.1 s (-31%), a 10-turn conversation from about 10 s to about 2.5 s (-75%), with input cost reductions of 90%, 86% and 53%. The page's date is unreliable and the figures describe older models; use them for shape, not as current numbers. Fireworks claims up to about 80% lower time to first token. Short prompts and long outputs gain little.
Part 2: Why the prefix must match exactly#
2.1 Causal attention#
In a causal language model, the key and value vectors for token i depend on all tokens before i. Change a token near the start and the vectors for every later token change too. There is no safe way to reuse the old values after an early edit, so a cache can only be reused up to the first difference. That is why every provider says the same thing in different words:
- Anthropic: "Hits require 100% identical prefixes, including all text and images up to the breakpoint." The prefix order is tools, then system, then messages.
- OpenAI: "A cache hit requires the entire rendered prefix to match. A change before a breakpoint stops matching for everything after it."
- Azure: "A single character difference in the first 1,024 tokens results in a cache miss."
A practical corollary from Anthropic's troubleshooting guide: keep the JSON key order of tool_use blocks stable. Some languages (they name Swift and Go) randomise map key order, which silently breaks the cache.
2.2 Blocks and hash chains#
Engines do not hash the whole prompt once. They split it into fixed-size blocks of tokens and hash each full block together with the hash of the block before it. The result is a hash chain: each hash commits to its own tokens and to everything earlier. Lookup walks the chain from the front and stops at the first block that is not stored.
- vLLM (automatic prefix caching, built on PagedAttention; Kwon et al., Sept 2023): each block's hash covers the parent block's hash, the block's exact tokens and extra values such as LoRA IDs, multimodal hashes and a cache salt. "We only cache full blocks." Eviction is LRU, and the last block of a request is freed first because it is least likely to be reused. Default hash is SHA-256 as of v0.11.
- SGLang (RadixAttention; Zheng et al., Dec 2023): a radix tree in which each node maps to the GPU-resident KV for a consecutive span of tokens, so requests sharing a prefix share nodes. The paper reports up to 6.4x higher throughput on its workloads. HiCache extends it across GPU memory, host memory and a storage backend.
- TensorRT-LLM: only full blocks are shared, the default is 128 tokens per block (larger blocks make reuse less likely), the model engine must be built with paged context attention, and KV becomes reusable only after the request that computed it finishes, so a burst of simultaneous requests with the same prefix does not benefit at first.
- Hosted APIs hide the block size but the effect is visible: Mistral reports
cached_tokensas a multiple of 64, and OpenAI (earlier models) rounds cached tokens down to a multiple of 128.
The simulator in Part 3 reproduces the hash-chain idea so you can watch it behave.
2.3 Locality: caches live on machines#
A KV cache is large GPU-resident data, so it lives on one machine. Several documented consequences:
- OpenAI: "Cache lives on individual machines." When one prefix exceeds roughly 15 requests per minute, overflow can be routed to machines without the entry. Routing depends on machine load and a hash of the initial tokens; on earlier models
prompt_cache_keyalso influences it. Caches are not shared across organisations or regions. - Anthropic and Bedrock: a cache entry is stored on the server that processed the request, and a later request can read it only if that server handles it. An entry becomes readable only after the first response starts, so parallel cold requests all miss.
- xAI: the
x-grok-conv-idheader (orprompt_cache_keyon the Responses API) routes a conversation to the same server. Fireworks: caching works only within a replica; senduserorx-session-affinityfor sticky routing. OpenRouter: sticky routing to the provider that served the cached request, with a 60-minute inactivity window. - Self-hosted fleets need cache-aware routing or a shared storage tier (SGLang HiCache's storage layer is the only tier shareable across instances).
Routing hints improve the odds. They do not guarantee a hit, and most providers say entries can be evicted at any time. Design your application to work with no hits.
2.4 Order: static first, volatile last#
If the prefix is what is matched, the prompt's layout is the cache strategy:
tools (fixed order, deterministic schemas)
system prompt (constants only)
static reference material, few-shot examples
--- breakpoint ---
conversation history (append-only)
volatile bits: timestamp, user ID, retrieved chunks, the questionProvider guidance converges: Anthropic says not to put a breakpoint on a block that changes every request (timestamps, per-request context, the user message), and its cache-diagnostics page describes system_changed as typically "a timestamp, request ID, or other per-request value interpolated into the system prompt", with the fix "make the system prompt a byte-stable constant and put the changing value in the user message". Fireworks, Together and Groq give the same advice.
2.5 What invalidates a cache#
Anthropic's hierarchy is tools, then system, then messages; a change invalidates that level and everything after it. From its documentation:
| Change | Effect |
|---|---|
| Tool definitions (names, descriptions, parameters) | Invalidates the whole cache |
tool_choice changes |
Invalidates system and message caches |
| Images added or removed anywhere | Invalidates system and message caches |
Web-search or citations toggle, speed: "fast" |
Invalidates the system and message caches; the tools cache stays valid |
| Thinking parameters, effort | Model-specific for tools and system; the message cache is always invalidated |
| Switching model | A miss; the cache is per model |
The rows above were checked against Anthropic's live table; Anthropic also lists rows for non-tool-result content with thinking and for dropped thinking blocks. OpenAI lists the settings that change the rendered prefix: model, tools (names, descriptions, schemas, ordering), parallel_tool_calls, text.format, reasoning.effort, text.verbosity and compaction settings. xAI's multi-turn page calls failing to send back reasoning_content "the top cause of cache misses" for reasoning models. Azure notes that image detail must stay the same and that a structured-output schema is prepended to the system message, so schema changes invalidate.
Part 3: A prefix cache you can run#
The simulator below is a toy, but it follows the real design: full blocks only, a hash chain, a TTL, LRU eviction, and a price that uses the discounted read rate. Words stand in for tokens and the block size is 16.
3.1 prefix_cache_sim.py#
"""prefix_cache_sim.py - a toy prefix cache: block hash chains, TTL, LRU, and the price of a hit."""
import hashlib, time
from collections import OrderedDict
BLOCK = 16 # tokens per block (real engines: 16-128; hosted APIs hide this)
def block_hashes(tokens):
"""Hash chain: each full block's hash covers its tokens AND the previous block's hash."""
parent, out = "", []
for i in range(0, len(tokens) - len(tokens) % BLOCK, BLOCK): # only FULL blocks are cached
h = hashlib.sha256((parent + " ".join(tokens[i:i + BLOCK])).encode()).hexdigest()[:8]
out.append(h)
parent = h
return out
class PrefixCache:
def __init__(self, capacity_blocks=1000, ttl=300):
self.store, self.cap, self.ttl = OrderedDict(), capacity_blocks, ttl
def lookup_and_write(self, tokens, now):
hashes, hit = block_hashes(tokens), 0
for h in hashes: # longest matching prefix, block by block
if h in self.store and now - self.store[h] <= self.ttl:
hit += 1
else:
break
for h in hashes: # write/refresh every block
self.store[h] = now
self.store.move_to_end(h)
while len(self.store) > self.cap: # LRU eviction
self.store.popitem(last=False)
return hit * BLOCK, len(tokens)
def words(s, n=None):
t = s.split()
return t if n is None else (t * (n // len(t) + 1))[:n]
POLICY = words("You are a support agent for Acme. Follow the refund policy exactly.", 480) # 480 tokens
TOOLS = words("tool schema get_order refund search_kb", 160)
def price(cached, total, w=1.25, r=0.1):
"""Relative input cost, base price 1 per token. Cached read = r; fresh tokens = 1 (write premium ignored here)."""
return (total - cached) + cached * r
def show(label, cache, tokens, now):
c, n = cache.lookup_and_write(tokens, now)
print(f"{label:<44} cached {c:>4}/{n:<4} ({c/n:5.0%}) relative cost {price(c, n)/n:4.2f}")
if __name__ == "__main__":
cache = PrefixCache(ttl=300)
q = lambda s: words(s)
print("-- layout A: static prefix first, volatile last")
show("req 1 (cold)", cache, TOOLS + POLICY + q("Where is order 123 ? please check it now"), 0)
show("req 2 (same prefix, new question)", cache, TOOLS + POLICY + q("Refund order 456 because it arrived broken today"), 10)
show("req 3 (after 400 s, TTL 300 s)", cache, TOOLS + POLICY + q("Where is order 789 ? any news about shipping"), 410)
print("-- layout B: timestamp at the START of the system prompt")
cache = PrefixCache(ttl=300)
for i, t in enumerate(["12:00:01", "12:00:07", "12:00:19"]):
show(f"req {i+1} (clock {t})", cache, ["Now:", t] + TOOLS + POLICY + q("Where is order 123 ? please check it now"), i * 6)
print("-- layout C: one early tool changed")
cache = PrefixCache(ttl=300)
show("req 1 (cold)", cache, TOOLS + POLICY + q("Where is order 123 ? please check it now"), 0)
tools2 = TOOLS[:]; tools2[3] = "CHANGED"
show("req 2 (tool 3 edited)", cache, tools2 + POLICY + q("Where is order 123 ? please check it now"), 5)
print("-- append-only conversation, 6 turns of ~120 new tokens each")
cache, convo = PrefixCache(ttl=300), TOOLS + POLICY
for turn in range(1, 7):
convo = convo + words(f"turn{turn} user and assistant text", 120)
show(f"turn {turn}", cache, convo, turn * 20)
print("-- break-even: caching wins when N > (w - r) / (1 - r)")
for name, w, r in [("5-min write 1.25x, read 0.1x", 1.25, 0.1), ("1-hour write 2x, read 0.1x", 2.0, 0.1),
("12-hour write 2.5x, read 0.1x", 2.5, 0.1), ("read 0.05x, 5-min write 1.25x", 1.25, 0.05)]:
be = (w - r) / (1 - r)
n = int(be) + 1
print(f"{name:<34} threshold N > {be:4.2f} -> first profitable N = {n} (cost {w + r*(n-1):4.2f} vs {n} uncached)")Real output:
-- layout A: static prefix first, volatile last
req 1 (cold) cached 0/649 ( 0%) relative cost 1.00
req 2 (same prefix, new question) cached 640/648 ( 99%) relative cost 0.11
req 3 (after 400 s, TTL 300 s) cached 0/649 ( 0%) relative cost 1.00
-- layout B: timestamp at the START of the system prompt
req 1 (clock 12:00:01) cached 0/651 ( 0%) relative cost 1.00
req 2 (clock 12:00:07) cached 0/651 ( 0%) relative cost 1.00
req 3 (clock 12:00:19) cached 0/651 ( 0%) relative cost 1.00
-- layout C: one early tool changed
req 1 (cold) cached 0/649 ( 0%) relative cost 1.00
req 2 (tool 3 edited) cached 0/649 ( 0%) relative cost 1.00
-- append-only conversation, 6 turns of ~120 new tokens each
turn 1 cached 0/760 ( 0%) relative cost 1.00
turn 2 cached 752/880 ( 85%) relative cost 0.23
turn 3 cached 880/1000 ( 88%) relative cost 0.21
turn 4 cached 992/1120 ( 89%) relative cost 0.20
turn 5 cached 1120/1240 ( 90%) relative cost 0.19
turn 6 cached 1232/1360 ( 91%) relative cost 0.18
-- break-even: caching wins when N > (w - r) / (1 - r)
5-min write 1.25x, read 0.1x threshold N > 1.28 -> first profitable N = 2 (cost 1.35 vs 2 uncached)
1-hour write 2x, read 0.1x threshold N > 2.11 -> first profitable N = 3 (cost 2.20 vs 3 uncached)
12-hour write 2.5x, read 0.1x threshold N > 2.67 -> first profitable N = 3 (cost 2.70 vs 3 uncached)
read 0.05x, 5-min write 1.25x threshold N > 1.26 -> first profitable N = 2 (cost 1.30 vs 2 uncached)Read the output as the rules:
- Layout A: the first request is a cold miss. The second reuses 640 of 648 tokens (the last 8 are a partial block, which is never cached) and costs 0.11 of an uncached request. The third arrives after the TTL and is a miss again.
- Layout B: one changing token at the very start gives a 0% hit rate for every request, however long the rest of the prompt is. This is the single most common production mistake.
- Layout C: editing one early tool is enough to miss everything behind it.
- The conversation: with an append-only history the hit rate climbs towards 90% and the relative cost falls towards 0.18, because each turn's prefix is the previous turn's whole prompt.
(The simulator's price function prices a hit at 0.1 and a miss at 1 and ignores the write premium, so it shows the read saving; Part 5 adds the write premium.)
Part 4: Provider by provider#
Reference
4.1 Anthropic (Messages API)#
The full treatment, with runnable code, is in 03.7, Part 6. What you need to read the comparison table in 4.6b:
- Two ways to cache: automatic (one top-level
cache_control) or explicit blocks, up to 4 breakpoints per request, with a 20-block lookback for reads (03.7, 6.1 and 6.2). - Lifetime and price: 5 minutes (refreshed free on every use) or 1 hour; a write costs 1.25x or 2x the base input price and a read 0.1x, or 0.05x and 0.025x on newer models (6.3).
- Minimum length: 512 to 4,096 tokens by model, and a shorter prefix is silently not cached (6.4).
- Usage fields:
input_tokenscounts only the tokens after the last breakpoint, so total input is the sum of the three fields (03.7, 3.3). - Operations: pre-warm with
max_tokens: 0(6.6), isolation per workspace (6.7) and thediagnosticsparameter (6.8; how to use it to debug is in 8.3 here).
4.2 OpenAI#
The full treatment is in 03.7, Part 7. There are two regimes, which matters when you read older blog posts:
- GPT-5.6 and later use
prompt_cache_options(modeimplicit or explicit,ttlof 30 minutes or 12 hours as a minimum lifetime, up to 4 cache writes, aprewarmoption) andprompt_cache_breakpointon content blocks. Writes cost 1.25x or 2.5x, reads 0.1x on most models, and the minimum is 1,024 visible input tokens (7.1 to 7.4). - Earlier models cache automatically with no write charge.
prompt_cache_retentionisin_memoryor24h, andprompt_cache_keyonly influences routing; keep one prefix and key under roughly 15 requests per minute (7.2 and 7.4). - Usage fields:
usage.input_tokens_details.cached_tokens(billed reads, excluding writes) andcache_write_tokenson GPT-5.6 and later; Chat Completions usesprompt_tokens_details(7.8). - The direct-API model identifiers for the newest OpenAI models were not confirmed, so the sample in Part 6 uses a variable.
4.3 Google Gemini#
The full treatment is in 03.7, Part 8, which is optional reading there.
- Implicit caching is on by default for Gemini 2.5 and newer, with a minimum of 2,048 or 4,096 tokens by model (8.1). On Gemini 4 a multi-turn request caches the previous one fully only if it adds at least 2,050 tokens.
- Explicit caching (
client.caches.create) works on Gemini 3 and 2.5 throughgenerateContent, not on Gemini 4 or the Interactions API. You pay storage per million tokens per hour on top of the discounted read price (8.2 and 8.3); 5.3 here turns it into a break-even. - Discounts are about 0.1x for most listed models and 0.05x for Gemini 4. Google's pages state prices, not percentages, so the ratios are arithmetic. OpenRouter's documentation quotes different multipliers; prefer the provider's own page (03.7, 9.1).
- Observe:
usage_metadata.cached_content_token_countongenerateContent,usage.total_cached_tokenson the Interactions API (8.1).
4.4 Other hosted providers#
- xAI (Grok): automatic, with the routing hint above. Append-only context; for reasoning models send back
reasoning_content. Observecached_tokens. The cached price is "substantially lower"; the minimum and TTL are not stated, and entries "can be evicted at any time". - DeepSeek: context caching on disk, on by default, no code change. Cached prefix units are written at the end of user input and model output, when a common prefix is detected, and at intervals for long inputs. No fixed TTL: unused caches are cleared "usually within a few hours to a few days". Fields
prompt_cache_hit_tokensandprompt_cache_miss_tokens. Listed prices put a hit at about 2% of a miss for the flash model (off-peak: $0.003 versus $0.15 per million). DeepSeek lists peak and off-peak prices, so recheck. - Mistral: opt-in
prompt_cache_keyhint, 64-token blocks, cached input at 10% of the standard price. Whether caching is automatic without the key was not stated. - Groq: automatic on three gpt-oss models, no extra fee, cannot be turned off, expires after 2 hours without use, cached input 50% cheaper (and does not stack with the batch discount). Cached tokens do not count toward rate limits but are subtracted after processing.
- Together: automatic, writes free on serverless, TTL about an hour on a best-effort basis, hits still count toward rate limits. Fireworks: automatic, default 50% discount on cached prompt tokens for serverless, TTL from minutes to hours, session affinity through
userorx-session-affinity.
4.5 Clouds and gateways#
- Amazon Bedrock: explicit cache checkpoints (
{"cachePoint": {"type": "default", "ttl": "1h"}}in Converse;cache_controlfor Claude's InvokeModel), implicit best-effort caching for some models, not available in batch inference. Usage fieldscacheReadInputTokensandcacheWriteInputTokens. Bedrock keeps its own per-model minimums for Claude. OpenAI models on Bedrock: 30-minute TTL only. - Azure OpenAI and Microsoft Foundry: the same model as OpenAI: first 1,024 tokens must match, 128-token increments on GPT-5.5 and earlier,
prompt_cache_optionson GPT-5.6 and later. Caches are not shared between subscriptions. Cache writes can be charged on GPT-5.6 and later (the page says 12-hour write charges start from 1 November 2026). - Claude on Vertex AI:
cache_controlas on Anthropic, 5-minute and 1-hour TTLs, writes +25% / +100%, reads -90%; caches are unique to your Google Cloud project. - OpenRouter: pass-through with sticky routing. Automatic for several providers,
cache_controlrequired for Anthropic and Gemini explicit. Usage fieldscached_tokens,cache_write_tokensand acache_discount. A cache is cold when routing moves you to another provider, so pin the provider order when caching matters. Batch lines running concurrently may not see each other's writes. Data governance: a gateway means your prompts may be routed through third-party providers you did not choose, so check the gateway's and the upstream providers' data policies, retention and zero-data-retention (ZDR) options before sending enterprise data.
4.6 Self-hosted engines#
| Engine | Mechanism | Notes |
|---|---|---|
| vLLM | Automatic prefix caching; hash-chained blocks; LRU | --enable-prefix-caching; whether it is the default was not stated on the fetched page; cache_salt isolates tenants; helps prefill only |
| SGLang | RadixAttention tree; HiCache tiers | Tiering across GPU, host and storage; the only cross-instance tier is storage |
| TensorRT-LLM | KV cache reuse over full blocks | 128 tokens per block by default; needs paged context attention at build time; reuse after the first request finishes |
| llama.cpp server | Per-slot KV reuse | cache_prompt defaults to true; -np sets parallel slots; --cache-ram host prompt cache (default 8192 MiB); observe timings.cache_n; route similar prompts to the same slot or the cache is lost |
A security note for shared self-hosted caches: cache hits are faster, so an attacker who can measure latency can probe whether another tenant's prompt was cached. vLLM's cache_salt and Fireworks' isolation keys exist to prevent that, and OpenAI says distinct prompt_cache_key values help prevent cache-hit probing across users.
4.6b The comparison table#
| Provider | Mode | Min tokens | TTL | Write price | Read price | How to observe |
|---|---|---|---|---|---|---|
| Anthropic | Automatic or up to 4 explicit breakpoints | 512 to 4,096 by model | 5 min (refresh free) or 1 h | 1.25x (5 min), 2x (1 h) | 0.1x (0.05x or 0.025x on newer models) | cache_creation_input_tokens, cache_read_input_tokens |
| OpenAI GPT-5.6+ | Implicit or explicit breakpoints | 1,024 visible | 30 min or 12 h (minimums) | 1.25x, 2.5x | 0.1x (0.05x on some) | cached_tokens, cache_write_tokens |
| OpenAI earlier | Implicit; prompt_cache_key |
1,024, 128 increments | In-memory (about 5 to 10 min) or 24 h | None | Model-dependent | cached_tokens |
| Gemini 2.5 / 3.x | Implicit plus explicit caches.create |
2,048 to 4,096 implicit | Explicit default 1 h | Storage per hour | About 0.1x | usage_metadata |
| Gemini 4 | Implicit only | 4,096; +2,050 per agent turn | Not stated | Not stated | About 0.05x | total_cached_tokens |
| xAI | Automatic plus routing ID | Not stated | Evictable any time | Free (per OpenRouter) | Cheaper (not stated) | cached_tokens |
| DeepSeek | Automatic, on disk | Not stated | Hours to days | None separate | About 2% of miss (flash) | prompt_cache_hit_tokens |
| Mistral | prompt_cache_key hint |
64-token blocks | Not stated | Not stated | 10% of input | cached_tokens |
| Groq | Automatic | 128 to 1,024 | 2 h idle | Free | 0.5x | cached_tokens |
| Together | Automatic | Model-dependent | About 1 h | Free (serverless) | Model's cached rate | cached_tokens |
| Fireworks | Automatic | Not stated | Minutes to hours | Not stated | Default 50% off | Headers (dedicated) |
| Bedrock Claude | cachePoint / cache_control |
512 to 4,096 | 5 min, 1 h | Model-specific | Model-specific | cacheReadInputTokens |
| Vertex Claude | cache_control |
Not stated | 5 min, 1 h | +25% / +100% | -90% | Not stated |
| vLLM, SGLang, TRT-LLM | Engine prefix cache | Block size | LRU | n/a | n/a | Engine metrics |
"Not stated" means the provider's page did not say, not that the value is zero.
Part 5: The economics: break-even and losses#
5.1 The formula#
Let the base input price be 1, the write multiplier w, the read multiplier r, and N the number of requests that share the prefix within the TTL.
cost with caching = w + r(N - 1)
cost without caching = N
caching wins when N > (w - r) / (1 - r)| Cache | w | r | Threshold | First profitable N | Reading |
|---|---|---|---|---|---|
| Anthropic 5 min | 1.25 | 0.1 | 1.28 | 2 | Pays on the first re-read (1.35 vs 2) |
| Anthropic 1 h | 2 | 0.1 | 2.11 | 3 | Needs two re-reads (at N = 2, 2.1 vs 2 loses 5%) |
| OpenAI 30 min | 1.25 | 0.1 | 1.28 | 2 | OpenAI's own example: one write and nine reads cost 2.15x versus 10x |
| OpenAI 12 h | 2.5 | 0.1 | 2.67 | 3 | 2.7 vs 3 at N = 3 |
| Pre-5.6 OpenAI, Groq, Together | 1 | 0.1 to 0.5 | none | 1 | No write premium: any hit is a pure saving |
| Gemini explicit | storage | 0.1 | per hour | see 5.3 | Storage turns it into a rate: reads per hour |
5.2 When caching costs you money#
- A prefix reused less than about once per TTL: the write premium is never recovered. Anthropic 5-minute: 1.25x on a prefix you never read again.
- A breakpoint on volatile content: you write every request and never read.
- 1-hour TTL for traffic that would have refreshed a 5-minute entry anyway: 2x instead of 1.25x for nothing.
- Padding a prompt to reach the minimum for a rarely reused prefix, without the break-even check. On OpenAI, padding a short prompt to the 1,024-token minimum pays only if the original length L is at least M·(r + (w−r)/N), with M = 1,024, which for N = 10 is about 221 tokens.
- A stored Gemini cache nobody reads: storage accrues by the hour.
- OpenAI implicit mode on a changing suffix: it writes a new suffix each turn you may never read; use explicit mode.
- Many parallel cold requests: each pays a write because the entry is not readable until the first response starts. Warm once, then fan out.
- Compaction or truncation that rewrites history: the first request after compaction misses the old prefix. The saving is in fewer total tokens afterwards, not in that request.
5.3 Gemini's storage break-even#
For Gemini 3.1 Pro Preview (up to 200k context) a read saves $2.00 − $0.20 = $1.80 per million tokens and storage costs $4.50 per million tokens per hour, so a cache needs more than 4.5 / 1.8 = 2.5 reads per hour to cover storage for that hour. For Gemini 2.5 Flash the saving is $0.27 per read against $1.00 per hour, about 3.7 reads per hour. (Assumes no write premium, which Google's page does not list.)
5.4 Keep warm or pay the 1-hour write#
A 5-minute Anthropic entry is refreshed by every use. If traffic is sparse you can ping with a cache-hitting pre-warm every few minutes: a refresh read costs r = 0.1x of the prefix, so pinging every 4 minutes is about 15 pings per hour × 0.1 = 1.5x per hour, against a single 1-hour write at 2x refreshed free on each use. The 1-hour TTL is usually simpler unless traffic is very sparse. Whatever you choose, measure it (Part 8) rather than assuming.
Part 6: Patterns with code#
All provider code below is illustrative: it follows the documented parameters, was not run against a live API in this course phase, and model IDs and beta parameters should be re-checked before use. Keep the provider call behind your client wrapper from 03.11.
6.1 System prompt and tools (Anthropic, explicit)#
import anthropic
client = anthropic.Anthropic()
TOOLS = [ # fixed order, deterministic schemas; cache_control on the LAST tool caches all tools
{"name": "get_order", "description": "Look up an order by id.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
{"name": "refund", "description": "Refund an order.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]},
"cache_control": {"type": "ephemeral"}},
]
SYSTEM = [{"type": "text", "text": LONG_POLICY_TEXT, # byte-stable: no timestamps, no user ids
"cache_control": {"type": "ephemeral"}}]
resp = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024, tools=TOOLS, system=SYSTEM,
messages=[{"role": "user", "content": f"Today is {today}. {question}"}], # volatile data goes here
)
u = resp.usage
print(u.cache_creation_input_tokens, u.cache_read_input_tokens, u.input_tokens)6.2 Multi-turn chat (Anthropic, automatic)#
history = []
def turn(user_text):
history.append({"role": "user", "content": user_text})
r = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
cache_control={"type": "ephemeral"}, # moves to the last cacheable block each turn
system=SYSTEM, messages=history)
history.append({"role": "assistant", "content": r.content}) # echo back verbatim, never re-serialise
return rIf one turn can add more than 20 content blocks (tool-heavy turns), add a second explicit breakpoint earlier in the conversation; otherwise the 20-block lookback misses.
6.3 A large document reused across questions#
doc_block = {"type": "text", "text": f"<document>{DOC}</document>",
"cache_control": {"type": "ephemeral", "ttl": "1h"}}
r = client.messages.create(
model="claude-sonnet-5-5", max_tokens=800,
system=[{"type": "text", "text": "Answer only from the document."}],
messages=[{"role": "user", "content": [doc_block, {"type": "text", "text": question}]}])Cache a fixed document or corpus. Per-question top-k retrieval returns different chunks each time and defeats the prefix. If you must retrieve, put the retrieved chunks after the breakpoint (07).
6.4 An agent loop#
messages = [{"role": "user", "content": task}]
while True:
r = client.messages.create(model="claude-sonnet-5-5", max_tokens=2048,
cache_control={"type": "ephemeral"},
tools=TOOLS, system=SYSTEM, messages=messages)
messages.append({"role": "assistant", "content": r.content})
calls = [b for b in r.content if b.type == "tool_use"]
if not calls:
break
messages.append({"role": "user", "content": [run_tool(c) for c in calls]}) # tool_result blocksKeep the tool list and tool_choice constant for the whole run. Do not add or remove tools mid-run (Manus builds its agent around this rule and masks tool choices instead); if you must, use the provider's mid-conversation tool mechanism. Harness-level consequences are in 08A.4.
6.5 Pre-warm and keep warm (Anthropic)#
def prewarm():
client.messages.create(model="claude-sonnet-5-5", max_tokens=0,
system=SYSTEM_WITH_CACHE_CONTROL,
messages=[{"role": "user", "content": "warmup"}])Run it at start-up, before a known traffic burst, or every few minutes for a 5-minute cache. It must use the same thinking and effort configuration as real traffic, or it warms a different prefix.
6.6 OpenAI GPT-5.6+, explicit breakpoint and 12-hour TTL#
from openai import OpenAI
client = OpenAI()
r = client.responses.create(
model=OPENAI_MODEL, # read it from config; do not hard-code
extra_body={"prompt_cache_key": "support:v3",
"prompt_cache_options": {"mode": "explicit", "ttl": "12h"}}, # SDK may lag the API
input=[
{"type": "message", "role": "developer", "content": [
{"type": "input_text", "text": STABLE_INSTRUCTIONS_AND_FEWSHOT,
"prompt_cache_breakpoint": {"mode": "explicit"}}]},
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": question}]},
],
)
d = r.usage.input_tokens_details
print(d.cached_tokens, d.cache_write_tokens)Sending these parameters to a pre-5.6 model returns a 400. On those models you do not need them: keep the layout stable, optionally set prompt_cache_key, and read cached_tokens.
6.7 Gemini explicit cache (Gemini 3 and 2.5)#
from google import genai
from google.genai import types
client = genai.Client()
cache = client.caches.create(
model=GEMINI_MODEL,
config=types.CreateCachedContentConfig(
display_name="contract-q3", system_instruction="You answer questions about the contract.",
contents=[contract_file], ttl="3600s"))
resp = client.models.generate_content(
model=GEMINI_MODEL, contents="List termination clauses.",
config=types.GenerateContentConfig(cached_content=cache.name))
print(resp.usage_metadata)
client.caches.update(name=cache.name, config=types.UpdateCachedContentConfig(ttl="7200s"))
client.caches.delete(cache.name)caches.create, update, delete and the cached_content= field follow Google's documentation; the usage field name is usage_metadata.cached_content_token_count (03.7, 8.1). On Gemini 4 there is no explicit cache: put large static content first and send similar prefixes close in time.
6.8 Few-shot libraries#
Put a fixed few-shot block directly after the system prompt, byte-stable and in a fixed order, and version it (prompt_cache_key=...:v3) so a deliberate change is a deliberate miss. Dynamic example selection (04.2) kills the prefix if the examples sit before the breakpoint; put dynamically selected examples after it, or accept the miss.
6.9 Use cases#
| Use case | What to cache | Provider fit |
|---|---|---|
| Support agent with long policy and tool list | Tools, policy, few-shot (static); user and order data after the breakpoint | Any; Anthropic explicit or OpenAI explicit gives control |
| Chat over one long document | The document, with a 1-hour TTL | Anthropic 1 h; Gemini explicit if you control TTL; OpenAI 12 h |
| Coding agent | Tools, instructions, growing history (automatic) | Anthropic automatic top-level caching; OpenAI implicit |
| Batch classification with a shared instruction | The instruction block | Caches are best-effort in async batches; do not count on the saving |
| Multi-tenant SaaS | Per-tenant prefixes with per-tenant keys or salts | Use prompt_cache_key per tenant; cache salt when self-hosting |
| RAG over changing chunks | The system prompt and any fixed corpus only | Caching helps little when most of the prompt is retrieved per request |
Part 7: Cache-aware design checklist#
- Tools first, in a fixed order, with sorted keys and deterministic serialisation.
- System prompt as constants: no timestamps, request IDs, usernames or feature flags.
- Static reference and few-shot next; a breakpoint after them.
- History append-only. Never edit, reorder or summarise early turns without accepting the miss.
- Volatile content last: date, user, retrieved chunks, the question.
- Do not toggle
tool_choice, images, thinking or effort mid-conversation. Prefer disabling a tool by instruction or masking over removing it. - Echo assistant content and tool results verbatim; do not re-serialise or normalise whitespace.
- Pick the TTL from your traffic gaps (Part 5), then verify with real hit rates.
- Warm once before fanning out parallel requests.
- Use routing hints (conversation ID,
prompt_cache_key, session ID) where the provider supports them, with per-tenant values. - Plan for no hits: the system must still work and be affordable uncached.
Part 8: Debugging low hit rates#
8.1 Measure#
The five metrics (request hit rate, token hit ratio, write ratio, net saving and prefix churn) and a hit-rate analyser you can run are in 03.7, Part 10; 11B.3, 2.6 puts them in a production loop. The only per-provider difference is which fields you divide:
- Anthropic:
cache_read / (cache_read + cache_creation + input_tokens), becauseinput_tokenscounts only what came after the last breakpoint. - OpenAI, Azure, xAI, Groq, Mistral:
cached_tokens / input_tokens(prompt_tokens). - DeepSeek:
prompt_cache_hit_tokens / (hit + miss). - Any provider: effective input price =
(fresh·1 + writes·w + reads·r) / total; compare it with 1.0.
Track the rate per prompt version and route, and alert on a sudden drop (a deploy changed a prompt), not on an absolute floor. A common logging mistake on Anthropic is recording only input_tokens, which hides the cached portion.
8.2 The checklist, in the order it usually bites#
- Under the minimum? Anthropic 512 to 4,096 by model, OpenAI 1,024, Gemini 2,048 to 4,096. On Anthropic both cache fields being 0 usually means this.
- Did anything change before the breakpoint? A timestamp or ID in the system prompt (
system_changed), tools reordered, added or serialised with unstable key order (tools_changed), history edited, truncated or summarised (messages_changed), a fallback to another model (model_changed). - Silent invalidators:
tool_choice, images added or removed, thinking or effort,text.format,reasoning.effort,parallel_tool_calls, fast mode, citations or web-search toggles. - Re-serialisation: SDK JSON key order, assistant content or tool results not echoed verbatim, whitespace or Unicode normalisation.
- TTL: gaps longer than the TTL (counted from the request start on Anthropic). Use a longer TTL or a keep-warm ping.
- Concurrency: parallel cold requests all write. Warm first, or wait for the first byte, then fan out. TensorRT-LLM reuses only after the first request finishes.
- Routing: per-machine caches; over about 15 requests per minute per prefix on OpenAI; missing or changing conversation ID on xAI; no session affinity on Fireworks; a provider change on OpenRouter.
- Lookback: more than 20 blocks since the last write on Anthropic. Add an intermediate breakpoint.
- Mode (OpenAI 5.6+): implicit-only covers the longer request, not your shared static part; explicit-only requests do not read implicit writes; extending a message breaks its boundary.
- Isolation: another Anthropic workspace, Azure subscription or Vertex project is a separate cache.
- Eviction: caches are best-effort on xAI, Bedrock implicit, DeepSeek, Together and Groq.
- Reasoning models: thinking blocks dropped, or reasoning content not sent back.
8.3 Use the provider's tools#
Anthropic's diagnostics parameter is the most direct. Illustrative shape, after the documentation:
r1 = client.beta.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
cache_control={"type": "ephemeral"}, system=SYSTEM, messages=msgs,
diagnostics={"previous_message_id": None})
r2 = client.beta.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
cache_control={"type": "ephemeral"}, system=SYSTEM, messages=msgs2,
diagnostics={"previous_message_id": r1.id})
d = r2.diagnostics
print("ok" if d is None else d.cache_miss_reason and d.cache_miss_reason.type)Read it together with usage: null plus high reads is a hit; null plus low reads means no entry (expired or under the minimum); a *_changed type plus low reads means fix the request. There are two more outcomes: previous_message_not_found and unavailable (also returned when tool_choice, thinking, context management, output config or beta headers differ between the two requests), and {"cache_miss_reason": null} means the comparison is still pending. null is also what you get on a first turn with no previous message ID, so the "null plus low reads" reading assumes a real previous_message_id. OpenAI offers a Prompt Caching dashboard and a Prompt Cache Diagnostics tool; llama.cpp reports timings.cache_n.
8.4 Common mistakes#
Logging only input_tokens; treating cached_tokens as including writes; assuming a cache is a security boundary (it is per organisation or workspace, so use per-tenant keys or salts); caching per-request retrieved chunks; padding to the minimum without the break-even check; expecting lower output cost or faster decoding; putting the breakpoint on the user message.
Part 9: Other caches, for contrast#
Deep-dive
Three other caches sit beside the prompt cache, and each skips something different: an exact response cache (whole responses keyed by a hash of the normalised request, skips the model call, risk is stale answers), a semantic cache (responses found by embedding similarity, skips the model call, risk is false hits and cross-tenant leaks) and an embedding cache (vectors keyed by hash of text, model and dimensions, skips re-embedding). 11B.3 Part 1 maps the whole stack, 11B.3 Part 3 and Part 4 teach the first two, and 06.2 the third.
One line to remember: a prompt cache is provider-side, stores computed state, needs an exact prefix, and still generates; a response or semantic cache is your side, stores text, and skips generation.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Caching stores the answer." | It stores KV state for the prefix. The model still generates every output token. |
| "Caching makes generation faster." | It cuts prefill and so time to first token. Decode speed and output cost are unchanged. |
| "Any similar prompt will hit." | Only an exact token prefix, up to the first difference. |
| "Enabling caching always saves money." | With a write premium, a prefix reused less than about once per TTL costs more. |
| "A longer TTL is always better." | The 1-hour Anthropic write is 2x; it needs two re-reads to pay. |
| "Every provider works the same way." | Minimums, TTLs, write charges and observability differ widely (Part 4). |
| "A cache hit is guaranteed if the prompt is identical." | Caches are per machine and evictable; routing and load can cause misses. |
| "Caching is a free security layer." | Shared caches leak timing; use per-tenant keys or salts. |
| "Put the date in the system prompt, it's small." | One changing token at the front defeats the whole prefix. |
Key takeaways#
- Prompt caching saves the prefill of an exact token prefix: the KV state is reused, the response is generated fresh.
- Hash chains make any early change a miss for everything behind it, so layout is strategy: static first, volatile last, append-only history.
- Caching cuts input cost and time to first token. It does not cut output cost or decoding time.
- Caches live on machines and are evictable. Routing hints raise the odds; design to work without hits.
- Break-even is N > (w − r)/(1 − r): Anthropic's 5-minute and OpenAI's 30-minute tiers pay on the first re-read, the 1-hour tier on the second.
- Measure hit rate per prompt version, log the cache fields, and use the provider's diagnostics before guessing.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Prefill | The phase that processes all prompt tokens in parallel to build the KV cache |
| Decode | The phase that generates output one token at a time, reading the KV cache |
| Prefix cache | A cache that reuses computed state for an exact prompt prefix, rather than a response |
| Hash chain | Block hashes that each include the previous block's hash, so a hit means the whole prefix matches |
| RadixAttention | SGLang's prefix cache, a radix tree of KV spans shared across requests |
| PagedAttention | vLLM's KV-memory scheme that stores the cache in fixed-size pages |
| Cache salt | A per-tenant value mixed into block hashes so tenants cannot probe each other's cache by timing |
| Sticky routing | Sending requests with the same key to the same machine or provider so cached state can be found |
| Cache write premium | The extra charge (for example 1.25x) for creating a cache entry, recovered by discounted reads |
| Cache pre-warm | Populating a cache before real traffic, without generating output |
| Cache diagnostics | A provider feature that reports why a request missed an earlier cache (Anthropic's diagnostics) |
Exercises#
- Layouts (3.1): change the timestamp in layout B to the end of the prompt. What hit rate do requests 2 and 3 get? What does that say about where volatile data belongs?
- TTL (3.1): with a TTL of 300 s, send requests every 200 s, then every 400 s. When does the hit rate collapse, and what is the cheapest way to survive the 400 s gap on Anthropic: 1-hour TTL or keep-warm pings? Use the Part 5 formulas.
- Block size (3.1): the shared prefix in layout A is 640 tokens. Predict the cached count for request 2 with
BLOCK= 16, 64 and 256, then rerun to check. Why does it only fall at 256, and how does this relate to TensorRT-LLM's 128-token default? - Break-even (Part 5): compute the threshold N for w = 1.25 and r = 0.05, and for a 1-hour write at w = 2 and r = 0.025. Which models in 03.7, 6.3 and 4.6b do these correspond to?
- Padding (5.2): a prefix is 400 tokens, the minimum is 1,024 and you expect 10 requests per TTL. Use the OpenAI formula to decide whether padding to the minimum pays at w = 1.25, r = 0.1.
- Debug (Part 8): an agent shows
cache_creation_input_tokensof about 40,000 on every turn and almost no reads. Name three causes in order of likelihood and the diagnostic that distinguishes them. - Gemini (5.3): a 100,000-token document on Gemini 2.5 Flash is queried 6 times per hour. Does an explicit cache pay for itself? Show the arithmetic.
- Design (Part 7): rewrite a prompt that begins "Current time: ... You are talking to {user_name}..." so that it caches, and say where each piece goes.
Check yourself#
- What does a provider actually store when you use prompt caching?The computed key and value tensors (KV state) for a token prefix, in memory or GPU-local storage, plus hashes for lookup. Not the response.
- Why does a one-character change early in the prompt cost you the whole cache behind it?With causal attention, the KV values for later tokens depend on earlier tokens. After an early edit none of the later state is reusable.
- Does caching reduce output cost or decode speed? Why not?No. It skips prefill only. Output tokens are generated and billed normally, and decode reads the KV cache each step regardless.
- What is a hash chain, and why do engines cache only full blocks?Each block's hash includes the previous hash, so a match proves the whole prefix matches. Partial blocks are not complete units to hash and share.
- Why can parallel first requests all miss on Anthropic?An entry is readable only after the first response begins. Requests sent at the same time all find nothing and all write.
- What do
prompt_cache_key,x-grok-conv-idand OpenRouter's session ID have in common?They are routing hints that send related requests to the same server or provider so the cached state can be found. - State the break-even formula and what it implies for Anthropic's 1-hour TTL.N > (w − r)/(1 − r). With w = 2 and r = 0.1 that is N > 2.11, so it pays only from the third request.
- Name three situations in which caching makes a bill larger.A prefix reused less than once per TTL; a breakpoint on volatile content; a long TTL on traffic a short TTL would have kept warm; padding to the minimum; unused Gemini explicit storage.
- On Anthropic, what does
input_tokensin the usage object include?Only the tokens after the last breakpoint. Total input isinput_tokensplus cache reads plus cache creation. - What is the difference between a prompt cache and a semantic cache?A prompt cache stores computed state for an exact prefix and still generates. A semantic cache stores responses, matches by similarity and skips the model.
- Why do shared caches need per-tenant keys or salts?A cache hit is faster, so timing can reveal whether another tenant's prompt was cached. Per-tenant keys or salts keep tenants separate.
- Your hit rate is 0% with a 30,000-token prompt on a model with a 1,024-token minimum. What do you check first?Something before the breakpoint is changing: a timestamp or ID in the system prompt, unstable tool order, or a fallback to another model. Use the provider's diagnostics.
Further resources#
- Prompt caching and cache diagnostics (Anthropic)
- Prompt caching (OpenAI) and the Azure OpenAI version
- Context caching (Google), KV cache on disk (DeepSeek) and the xAI, Together and Fireworks pages
- Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023) and SGLang (Zheng et al., 2023)
- vLLM automatic prefix caching
- In this course: 03.7 Cost and caching, 11B.3 Caching strategies, 11B.1 Cost and latency, 11B.2 Tokenomics and 08A.4 Harness engineering
Not verified in this lesson: Anthropic's launch-post latency figures for current models; the direct-API OpenAI identifiers; Gemini's usage field on generateContent; xAI, Mistral, Together and Fireworks minimums, TTLs and discount percentages; Bedrock prices; vLLM's default state.
← 11B.3: Caching Strategies | Module 11B overview | 11B.5: Model Selection and Routing →