AI Engineering · Concept Library · Free article
Prompt Caching
Prompt caching reuses the work the model already did on a repeated prompt prefix, so a call that begins with the same system prompt, examples and policies skips re-reading them: cheaper input tokens and a faster first token. It is what makes context engineering's big stable block affordable to send. The catch is that it's a prefix cache, so one stray value at the top can throw the whole discount away.
After context engineering, a big slice of your prompt is identical on every call, the system prompt, voice guide, examples, tool schemas, maybe a policy doc. Without caching you re-process all of it every request, paying full price in money and first-token latency each time. Prompt caching stores the model's computed state (the KV cache from the prefill phase) for a stable prefix and reuses it on later calls: reads are heavily discounted (around a tenth of normal input price), though the first write carries a small premium of about a quarter. It's a PREFIX cache, matching runs from the first token, so one changed value near the top (a timestamp, a user id) invalidates everything after it. The design rule is simple: keep everything stable at the front, let only the per-request tail vary, and make sure your traffic is frequent enough to keep the cache warm.
Context engineering gave Wrenlet a proper briefing: a crisp system prompt, a voice guide, four gold example replies, the tool schemas, and the policy section for each ticket. Quality went up. But look at what you're now sending on every call, several thousand tokens of setup that never changes, in front of a customer message that's maybe a hundred tokens. The model dutifully re-reads that whole standing block from scratch, every request, and you pay for it every request: in money, and in the seconds before the first word appears. You've made the prompt good and, without noticing, made it expensive to send.
Two kinds of number appear on this page and they come with different warnings. The provider ratios are real, published figures, and they drift, so check them against the live docs before you quote them. The token counts, timings and dollar amounts in the panels are Wrenlet's, and they are illustrative: each panel is sized to make one relationship visible rather than measured off a production cluster.
That's the problem prompt caching solves. If the front of the prompt is the same as last time, why make the model, and your bill, do that work again? Cache it once, reuse it cheaply. Done right, Wrenlet's big stable briefing becomes nearly free to re-send, and the first token comes back faster. Done carelessly, you get none of that and sometimes a worse bill. The difference is understanding exactly what gets cached, and what quietly breaks it.
What does prompt caching actually cache?
The model's own working state for the tokens it has already read, not the prompt text and not the reply. Recall from streaming that generation has two phases. Prefill reads your entire prompt in one pass and builds up the model's internal working state. This is the expensive, up-front part that sets your time to first token. Decode then emits the reply one token at a time. Prompt caching operates on the prefill half: it saves the internal state the model computed while reading a stretch of your prompt (the key-value cache, or KV cache), keyed to those exact tokens, and reuses it next time instead of recomputing it.
Why does prompt caching only work from the front?
Because the state the model builds at any token depends on every token before it, so a stretch of prompt can only be reused when everything ahead of it is identical too. That is what makes this a prefix cache. The match runs from the very first token forward, and it holds only for as long as the tokens are byte-for-byte identical to a previous call. The instant one token differs, the match ends, and everything from that point to the end of the prompt has to be re-processed at full price, because the model's state from there on depends on it. You can cache the head that repeats; you can never cache past the first thing that changed. Click through where a call differs and watch how much survives:
The interactive version of this example is available when JavaScript loads.
The discount, the premium, and the break-even
Caching isn't quite free. The first call that establishes the cache, the write, usually costs a little more than a normal call (commonly around 1.25× the base input price, more for a longer-lived cache). Every later call that hits the cache, the read, costs far less, often around a tenth of the normal input price. So the economics are a trade: pay a small premium once to bank a big discount many times. That only comes out ahead if you reuse the prefix enough to amortize the write. Slide the reuse count and the prefix size and watch the two bills cross:
The interactive version of this example is available when JavaScript loads.
Do that arithmetic and the break-even turns out to be lower than almost anyone guesses. At 1.25× to write and 0.1× to read, caching overtakes not caching at 1.3 calls: the second call is already about a third cheaper, by five calls you are paying a third of the naive bill, and by twenty you are paying about a sixth. A single reuse pays for the write. That is worth holding onto, because it means the only way to lose money on caching is to not reuse the prefix at all, which is exactly what a lapsed cache does to you, and is the subject of the next section. The numbers move by provider and model generation, so treat the exact ratios as ballpark, not gospel; the shape is what's durable.
How should you lay out a prompt for caching?
Stable content first, volatile content last. Now the ordering rule from context engineering earns its second payoff. To cache well, structure every prompt the same way: the stable, repeated content first: system prompt, voice guide, examples, tool definitions, then any large reference doc that's constant for a while, and the volatile, per-request content last: the freshly retrieved snippets and the customer's actual message. That way the whole expensive head is one cacheable prefix, and only the cheap tail changes call to call.
One practical floor to know: providers only cache prefixes above a minimum length, because caching a tiny one isn't worth the bookkeeping. The floor runs from about one to four thousand tokens depending on the model, and the spread matters more than it sounds. Wrenlet's stable head in the panel below is around 3,500 tokens, which clears the floor comfortably on some models and falls under it on others, so “is my prefix long enough” is a question with a per-model answer, not a yes. And there are two ways to switch it on: automatically, where the provider spots the repeated prefix itself, or explicitly, where you mark the boundary with a cache breakpoint or hold a named cache object. Most providers now offer both. Either way, the design job is the same, keep the front stable.
Caches expire, and sparse traffic can lose you money
A prompt cache is short-lived, though how short depends on whose it is. Anthropic's default tier lives about five minutes, current OpenAI models hold a prefix for thirty, a Gemini cache you create explicitly lives exactly as long as the TTL you pay for, and several providers offer extended tiers measured in hours. All of them refresh on a hit. If your next call arrives before the cache expires, you get the cheap read. If your traffic is sparse enough that the cache lapses between calls, every call becomes a fresh write, and you pay the premium every time with no discount to show for it. Caching a rarely-hit prefix can genuinely cost more than not caching at all.
Set the dials below and watch the run of calls flip between a warm hit and a cold re-write. Push the calls further apart than the cache lives and the discount evaporates; turn on a warming heartbeat and even a slow path stays warm.
The interactive version of this example is available when JavaScript loads.
One comparison decides that whole panel: the gap between your calls, against how long the cache lives. Inside it, every call after the first reads cheaply and pushes the expiry further out. Outside it, the run never changes state at all: each call writes at the premium and finds nothing to read, which is the one arrangement where switching caching on leaves you worse off than before. The heartbeat is worth being precise about, because it is easy to read as a way around the lifetime and it is not. It keeps a cache alive by touching it from inside the window, so a slow path stays warm only for as long as something keeps paying those visits.
Why isn’t my cache hitting?
When caching “doesn't work,” it's almost always one of a short list. Run down it before blaming the provider.
The usual suspects
- A volatile value at the front. A timestamp, user id, session UUID, or A/B-varied system prompt sitting ahead of the stable block. Diff two consecutive raw prompts byte-for-byte and hunt for what changed near the top.
- Below the minimum length. The cacheable prefix is under the provider's floor, so nothing is cached.
- Traffic slower than the TTL. Calls arrive further apart than the cache lives, so it expires before it's reused. Warm it or accept the miss.
- Non-determinism in assembly. Tool definitions serialized in a different order, JSON keys in a different order, locale-dependent number formatting, any of these silently changes the prefix bytes even when the content is “the same.” Serialize deterministically.
- A different model or version. Caches don't carry across model versions; pinning matters.
There's also a scale wrinkle worth knowing. The cached state lives in the memory of one specific serving machine. Behind a naive load balancer, your second request might land on a different machine that never saw the prefix: a cold miss, even though “the cache exists.” Large deployments fix this with cache-aware routing: send requests that share a prefix to the same node (a hint like OpenAI's prompt_cache_key, or routing that hashes on the prefix), trading a little load-balancing evenness for cache locality. You rarely build this yourself early on, but it explains why caching that worked in a notebook can underperform behind a real fleet.
Run the same request stream through both routers and watch the hit rate move. Round-robin scatters each prefix across nodes that never cached it; cache-aware routing sends every request sharing a prefix to its home node, so each prefix is written once and every repeat hits.
The interactive version of this example is available when JavaScript loads.
Verify the hit, don’t assume it
Every provider returns usage fields that separate cached from uncached tokens, cache-read versus cache-creation input tokens, or a cached_tokens count. Log them. The difference between “I turned caching on” and “my cache is actually hitting” is exactly these numbers, and a cache you assume is working while a stray timestamp quietly busts it is a common, invisible money leak. If the read count isn't climbing, your cache isn't hitting, go back to the checklist.
How do the providers ship prompt caching?
Every major provider caches the same thing the same way: the prefill state of a stable prefix, matched from the front, so the concept you just learned transfers everywhere. What differs is the switch you flip, whether there's a write premium, the minimum prefix length, and how long the cache lives. There used to be two camps here, automatic and explicit, and that line has mostly dissolved: the major providers now offer both, an automatic mode that finds the repeated prefix for you and an explicit marker for when you want to place the boundary yourself. Which is a good thing to notice, because it means the switch was never the hard part. Keep the numbers below as ballpark: they move by model and month.
| Provider | How you turn it on | The economics | Min prefix & lifetime |
|---|---|---|---|
| Anthropic | Both: a top-level cache_control field caches automatically and moves the boundary forward as a conversation grows, or place up to 4 explicit breakpoints yourself. | Read 0.1× input (0.025× on the newest models); write 1.25× for the 5-minute cache and 2× for the 1-hour one. | Min 512 to 4,096 tokens by model; 5-min default TTL, refreshed on hit, with a 1-hour opt-in tier. |
| OpenAI | Automatic, nothing to add once the prefix clears the floor; pass a prompt_cache_key to keep a group of requests on its own cache. | Read 0.1× input on current models; write 1.25× on current models, with no write charge on older ones. | Min 1,024 tokens; 30-minute retention on current models, and older ones idle out in minutes or hold up to 24 hours on the extended tier. |
| Google Gemini | Both, implicit on by default for every Gemini 2.5 and newer model, plus an explicit CachedContent handle you create and hold. | Read heavily discounted; the explicit cache also bills storage by token-hour for as long as you keep it. | Min 2,048 tokens on Gemini 2.5 and 4,096 on Gemini 3.x; the explicit cache lives exactly as long as the TTL you pay for. |
| vLLM / SGLang (self-host) | Automatic prefix caching, vLLM calls it APC and SGLang calls it RadixAttention; on by default in current vLLM. You own the KV memory. | No per-token bill, the win is skipped prefill compute and lower first-token latency. | Bounded by GPU memory, not a token floor; a prefix lives until it is evicted. |
Turning it on, in code
The mechanism is identical everywhere; only the switch differs. There are three moves, mark the prefix (or let it happen), pin the routing, and prove the hit, and none of them is more than a line or two.
The four lines that matter
- Mark the stable prefix (explicit). In Anthropic's Messages API you attach
"cache_control": { "type": "ephemeral" }to the last content block you want cached: the end of yoursystemtext, or the last entry intools. Everything from the start up to that marker becomes the cacheable prefix; add"ttl": "1h"to hold the longer-lived cache. You get four breakpoints per request, and the automatic mode spends one of them, so treat them as a budget rather than a per-block habit. - Or let it happen (automatic). With OpenAI's or Gemini's implicit caching there's nothing to add, once your stable prefix clears the token floor, repeats are cached for you. Your whole job is to keep that prefix genuinely stable and at the front.
- Pin the routing at scale. Pass a stable
prompt_cache_key(OpenAI) so requests sharing a prefix land on the same cache, and so their hits are accounted separately from everyone else's: the code-level version of the cache-aware routing from before. On a fleet you run yourself, this is where you hash on the prefix instead. - Prove it's hitting. Read the usage object on every call: Anthropic returns
cache_creation_input_tokensandcache_read_input_tokens; OpenAI exposesusage.input_tokens_details.cached_tokenson the Responses API (usage.prompt_tokens_details.cached_tokenson Chat Completions); Gemini reportscachedContentTokenCounton the RESTusageMetadata, surfaced asusage.total_cached_tokensin the current SDKs. A rising read count is the only real confirmation.
Prompt-caching mistakes that reach production
The ones that actually bite
- A per-call value ahead of the stable block. The number-one cache killer. Keep timestamps, ids, and anything variable in the tail.
- Caching a low-traffic prefix. If calls are sparser than the TTL, you pay the write premium every time. Caching rewards frequency; warm it or skip it.
- Non-deterministic serialization. Reordered tool defs or JSON keys change the prefix bytes and silently prevent hits. Serialize the same way every time.
- Assuming it works. Not logging the cache-read counters, so a busted cache leaks money unnoticed. Verify from the usage fields.
- Expecting faster generation. Caching cuts first-token latency and input cost, not decode speed. It won't make a long answer stream faster.
- Putting private data in the shared prefix. Keep user-specific content in the uncached tail.
Habits that keep a cache hitting
What senior teams wire in from day one
- Order stable-first, always. System prompt, voice guide, examples, tool schemas, then any long reference doc at the front; retrieved snippets and the customer's message last. One layout rule buys cheaper context and cache hits at once.
- Serialize deterministically. Freeze JSON key order and tool-definition order, and keep locale-dependent formatting out of the prefix. The bytes must be identical every call, or the match breaks at the first difference.
- Verify from the counters, not by feel. Log the cache-read tokens on every call and alert if the hit rate drops: a silent bust is a slow, invisible money leak.
- Warm the high-value prefixes; skip the low-traffic ones. A steady-but-slow path can be kept warm with a cheap heartbeat; a prefix touched only occasionally shouldn't be cached at all.
- Keep private data in the tail. The stable prefix is shared across your users, so never bake one user's data into it. Volatility ordering already puts per-user content where it belongs.
- Pin the model version. Caches don't survive a model or version change; an unplanned upgrade silently cold-starts every prefix you had warm.
- Route for locality once you're behind a fleet. Add a prefix key or prefix-aware routing so repeat requests land on the node that actually holds the KV state.
Interview cheat-sheet, intern to principal
- What does prompt caching cache, and which phase does it speed up?
- It caches the model's computed internal state (the KV cache) from the prefill phase for a stable prompt prefix, so later calls reuse that work instead of re-reading the prefix. It improves time to first token and input-token cost, the prefill half, not decode speed, so the reply still generates at the same per-token rate.
- Why is it called a prefix cache, and what’s the consequence?
- Matching runs from the first token forward and holds only while the tokens are byte-for-byte identical to a prior call. The moment one token differs, the match ends and everything after it must be re-processed. The consequence: keep all stable content at the front, and never let a per-request value (timestamp, user id) sit ahead of the stable block, or you bust the whole cache.
- Walk me through the economics. When does caching NOT pay off?
- The first write costs a small premium over a normal call (commonly ~1.25× input price); each later read is deeply discounted (often ~0.1×). Put those two numbers together and the break-even is 1.3 calls, so a single reuse already pays for the write. It does NOT pay off when traffic is sparser than the cache TTL (each call re-writes and pays the premium with no discount), when the prefix is below the minimum length, or for one-off/highly-personalized prompts with no shared prefix.
- My cache never seems to hit. How do you debug it?
- Diff two consecutive raw prompts byte-for-byte and look for a volatile value near the top (timestamp, id, reordered JSON/tool defs, locale formatting). Confirm the prefix clears the minimum length, that traffic is frequent enough to beat the TTL, and that the model version is pinned. Then check the cache-read usage counters, if they aren't rising, it isn't hitting.
- How does prompt caching interact with load balancing at scale?
- The cached KV state lives in one serving node's memory. A naive round-robin balancer can route the next request to a different node with a cold cache, so you miss despite the cache “existing.” Large deployments use cache-aware / sticky routing, send requests sharing a prefix to the same node (e.g. a prefix hint or hashing on the prefix), trading some load-balance evenness for cache locality.
- The provider caches automatically, is there anything left to design?
- Yes, automatic caching only helps if the prefix is genuinely stable and at the front, clears the minimum length, and your traffic beats the TTL. A prompt with a timestamp on top caches nothing no matter how automatic the feature is. The real design work, stable-first layout, deterministic serialization, warming sparse paths, and cache-aware routing at scale, is the same whether the switch is automatic or an explicit marker. Automatic removes one line of code, not the thinking.
- A steady-but-slow path keeps cold-missing. What are your options?
- Three, in order: warm it (a cheap priming or heartbeat request keeps the cache alive between real calls), extend the TTL if the provider offers a longer-lived tier (worth its higher write premium only above a few reads per lifetime), or accept it isn't a caching candidate and leave it uncached. Caching a rarely-hit prefix pays the write premium on every call and banks no discount, so if warming isn't worth it, don't cache it.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.