Zero Labs
Industry News / AI

Prompt Caching

Source · Towards AI By Akilesh KR

From the publisher’s feed, collected in the ZeroLabs newsroom.

Indeed generated using ChatGPTOkay so real talk before we start….There was this phase I went through, and honestly I am not ashamed of it because I think most people who got into building with LLMs went through the exact same thing, where I was just asking the model everything. Like everything.Bro can you code this → bro this function is broken can you debug → cool now write the tests → now write the docs → now refactor this whole file while you are at it!!I asked it to do git commits for me. I asked it to explain stack traces I did not feel like reading. I was asking it to write emails I was too tired to write ( lazy is the right word ). There was one point, I am not making this up, where I literally typed can you open Netflix inside VS Code so I do not have to switch windows..Anyway, the point is I was using these chat UIs constantly. Left right centre. No hesitation. And it felt free; it genuinely felt like this thing that just existed and you could ask it whatever and it would answer and there was no meter running anywhere.Then I started Building. Not just chatting → actually building. Agents, workflows, a support bot, some RAG pipelines. Started calling the API properly. Deployed things. Got a little too confident.Came back a week later and looked at the API bill.….yeah.It was not great. I had been sending the same 8,000-token context on every single request; the system prompt, the tool definitions, the reference docs…. fresh. From scratch. Every time. The model was re-reading the same instructions on every request while I was blissfully assuming ~ yeah the API probably handles that.~Somehow prompt became a household word before most of us understood what it actually costs. And that is where the trap starts….In the chat interface a prompt feels free. You type more context. Paste a document. Add a few examples. Throw in one more instruction because the model was acting slightly possessed yesterday and you are not taking chances. So you just… keep adding stuff. Because why not → it is not like it costs anything, right?wait what.In the API world, the world where you are building actual products, actual agents, actual workflows; every extra token has a price tag.Your system prompt + conversation history has a price tag.And the part I genuinely find humourous is this → if you send the same 8,000-token system prompt 5,000 times a day, the model does not go:relax dood. I already read this yesterday.So that is the whole setup → the user asked 6 tokens. The API charged 8,006 input tokens. And it will do it again on the next request, and the one after that; same system prompt, same tools, full price, every single time. This is not a bug. It is just… how it works. And nobody really talks about it in plain language because it gets buried under documentation and pricing pages that assume you already know what prefill means.The Hidden taxThere are things about LLM inference that changes how you think about cost.The model does two very different jobs on every single request.Job 1 → Reading (Prefill) : Before the model writes a single word, it has to process your entire input; all of it. The system prompt + the tools + the docs + the history + the question. This is called prefill. It runs in parallel across all your input tokens, it is compute-heavy, and it scales directly with how long your input is.Job 2 → Writing (Decode) : Then it generates your response, one token at a time. This is called decode. In a sequential manner btw, each token depends on the one before it. Cheaper per token than prefill.TTFT — time to first token — is that cursor-blinking pause between you hitting send and the first word appearing. That gap is almost entirely prefill. The model is not being dramatic; it genuinely cannot start writing until it has finished reading. The moment prefill ends, decode kicks in and tokens start flowing.So a slow TTFT usually means one thing: a long prompt. And a high API bill usually means one thing: a long prompt being sent repeatedly.Here is the kicker….The expensive part is not answering the question. The expensive part is reading everything before the question.So when your 6,000-token system prompt gets processed fresh on every request,6,000 tokens × 5,000 requests × $3.00 per million × every single dayJust because nobody told it that it already did this work yesterday. And the day before. And every day since you deployed this thing. And here is the thing that should make you slightly annoyed when you realise it….The model is not learning anything new by re-reading your system prompt on request number 4,999. It is just doing the same computation it did on request number 1. Computing the same internal numbers, storing them in memory for the duration of that one request, then throwing them away when the response is done. So the next request starts again from zero. Full read. Full compute. Full price.That is the waste. Right there. That is all it is.So the obvious question is → can the provider just… not throw those numbers away? Can it keep them around and reuse them when request 4,999 arrives with the same prefix as request 4,998?Yes. That is prompt caching.A dry runWithout caching, here is what happens across five consecutive requests:Request 1 → [system: 6000 tokens] [tools: 1000] [docs: 1000] [user: 8] → answerRequest 2 → [system: 6000 tokens] [tools: 1000] [docs: 1000] [user: 9] → answerRequest 3 → [system: 6000 tokens] [tools: 1000] [docs: 1000] [user: 7] → answerRequest 4 → [system: 6000 tokens] [tools: 1000] [docs: 1000] [user: 11] → answerRequest 5 → [system: 6000 tokens] [tools: 1000] [docs: 1000] [user: 6] → answerThe first three blocks are identical on every single row. The only thing that changed was the last 6–11 tokens,i.e the actual question. But you paid for all 8,000 tokens each time.With caching:Request 1 → [system: 6000 ← write] [tools: 1000 ← write] [docs: 1000 ← write] [user: 8] → answerRequest 2 → [system: ✓ reuse ] [tools: ✓ reuse ] [docs: ✓ reuse ] [user: 9] → answerRequest 3 → [system: ✓ reuse ] [tools: ✓ reuse ] [docs: ✓ reuse ] [user: 7] → answerRequest 4 → [system: ✓ reuse ] [tools: ✓ reuse ] [docs: ✓ reuse ] [user: 11] → answerRequest 5 → [system: ✓ reuse ] [tools: ✓ reuse ] [docs: ✓ reuse ] [user: 6] → answerRequest 1 pays to read and store. Requests 2–5 skip the prefix entirely and pay 0.10× on those tokens. The user question always runs fresh. The model generates a completely new response every time. It is just starting from a warmer place.Okay so what is actually being cached?Under the hood, and I will keep this short because you genuinely do not need to know every matrix multiplication to use this well ( i’ve been writing about those in my previous blogs do check them out )here is what happens during prefill.The model runs your prompt through its attention layers.For each token, it computes internal representations called Keys and Values. These K/V states are what let the model understand context and relationships between tokens. And for your system prompt tokens; which are identical on every request, those K/V states are also identical on every request.The model is computing the same numbers, storing them temporarily, throwing them away at the end of the request, then computing them again on the next one.That is the waste. That is all it is.Prompt caching tells the provider: Technically, this reusable state comes from the attention mechanism’s Key/Value computation across transformer layers. But the intuition is simpler, the model already did the expensive reading work for that prefix. Cache it, and you do not pay for it again.This confused me for a while and wanted to clear things..People say KV cache as well and there is prompt cache as wellKV cache happens inside a single generation. When the model is writing token 50, it should not recompute the K/V states for tokens 1 to 49 again. So it keeps them around in memory during that one request. That is normal KV caching during decode, it has always been there, you get it automatically, you do not configure it.The second one is prompt caching. It says: if request 2 starts with the exact same prefix as request 1, why throw away the K/V states for that prefix when request 1 finishes? Keep them. Reuse them when request 2 arrives.So →Normal KV cache → saves work inside one response. Prompt caching → saves work across repeated requests.The setupThis is the vanilla setup that most people ship,# what most people are running right nowresponse = client.messages.create( model="claude-sonnet-4-6", system=large_system_prompt, # 6000+ tokens, full price, every request messages=[{"role": "user", "content": user_question}])This is what you add:# with prompt caching, same result, very different billresponse = client.messages.create( model="claude-sonnet-4-6", system=[{ "type": "text", "text": large_system_prompt, "cache_control": {"type": "ephemeral"} # }], messages=[{ "role": "user", "content": [ { "type": "text", "text": rag_context, "cache_control": {"type": "ephemeral", "ttl": "1h"} # }, {"type": "text", "text": user_question} # always fresh, no cache_control ] }])Anthropic requires you to explicitly mark what you want cached using cache_control. You pay a small premium on the write, then 0.10× on every subsequent read. Minimum 1,024 tokens in the cached block.On OpenAI you do not add anything special → just make sure static content comes first and the prefix is at least 1,024 tokens. Caching happens automatically. The discount shows up in your usage response.The response is identical. The model behaviour is identical. The cost is not.The StructureThere is one hard rulethe cache references everything from the beginning of the prompt up to and including the cache_control breakpoint.Change anything before that breakpoint → cache key changes → full miss → full prefill → full price.Boring stuff first. Dynamic stuff last. Always.System prompt → almost never changes → cache always, no debate↓ breakpoint #1Tool definitions → changes per deployment, not per request → cache it↓ breakpoint #2Reference documents → changes per knowledge update → cache with 1h TTL↓ breakpoint #3 (optional)Conversation history → grows each turn → cache up to last assistant message↓ always freshCurrent user message → changes every time → never cache, never tryAnthropic supports up to 4 cache_control breakpoints per request. Each one can independently hit or miss. System prompt cached, docs missed because they just got updated → fine, you still save on the system prompt.Cache hit and missEvery cache system has these two characters sitting in the middle of the story, cache hit and cache miss. We have seen this in normal software also. Browser cache, CDN cache, Redis cache...The feeling is the same.The system either finds something it already stored, or it does not. But in prompt caching, what it is trying to find is not an image, not a webpage, and not the final answer from the model. It is trying to find the already-computed internal state for the beginning of your prompt.That beginning is what people call the prefix. ~ Prefix ~ is just the stable beginning of your prompt. In a real LLM application, that usually means your system prompt, tool definitions, output format rules, and maybe some reference documents.fyi : The current user message is not the prefix, because that changes every request.The prefix is the boring repeated part at the top, the part you secretly hope the model does not reread every single time like it has never seen your application before.So the provider takes that prefix and runs it through the tokenizer. That text becomes token IDs. The cache does not sit there and understand your prompt like a person. It is not looking at your system prompt, it is looking at the token sequence produced by the tokenizer. From that token sequence, the system creates a cache key, which you can think of as a fingerprint for that prefix. Same token sequence, same fingerprint. Different token sequence, different fingerprint.The cache checks the prefix fingerprint, not the meaning. Same prefix gives a hit. One tiny change before the breakpoint gives a missA cache hit means the provider found a stored K/V state for that exact prefix, and the cache entry has not expired yet.So instead of running the full prefill computation again for those tokens, it loads the stored K/V tensors and continues from there. The transformer layers do not need to process those prefix tokens again. The same repeated matrix multiplications do not need to happen again. That is why time-to-first-token improves. The model is not suddenly smarter. It is not skipping reasoning. It is just not rereading the same opening section for the hundredth time.And there is an important catch,a cache hit is not a semantic shortcutThe model is not retrieving a summary of your system prompt. It is reusing the internal state that would have been produced if prefill had run normally for that exact prefix. So from the model’s point of view, the context is still there. The difference is that the provider avoided recomputing it. That is the cleanest way to think about prompt caching: same context, less repeated work.A cache miss is where the pain comes back. It means the provider could not reuse the stored state.Maybe the prefix hash did not match. Maybe the TTL expired. Maybe the cached block was below the minimum token size. Maybe you put a date, a user name, or a session ID above the breakpoint. Whatever the reason, the result is the same, full prefill runs again. The model reads the entire prefix again.The annoying part is that two prompts can look almost identical to us and still miss. For example, these two JSON objects mean the same thing to a human:{"b": 1, "a": 2}{"a": 2, "b": 1}But the text order is different, so the token sequence can be different, and the cache fingerprint can be different. Same with an extra space. Same with a timestamp. If a value changes every request, keep it below the cached prefix. The cache is strict in a way humans are not.How the key is actually constructedThe cache key is a hash of the token ID sequence, everything from token 0 to the breakpoint boundary, as integers, after tokenisation. Not the raw string. The hash of what the tokeniser produces from that string.This is where it gets precise in ways that catch people off guard."tool_name": "search" and "tool_name": "search" (one extra space) produce different token sequences, different hash, guaranteed miss.This is also where breakpoints become important. When you add cache_control, you are basically telling the provider, ~ this section up to here is worth remembering ~ The provider can then check whether that prefix has already been cached. With multiple breakpoints, the result does not have to be all-or-nothing. Your system prompt might hit. You still saved the cost of reading the system prompt and tools again, even if the lower section had to be recomputed.The real lesson is not ~ cache everything ~ The real lesson is ~ keep the beginning stable ~ Prompt caching rewards boring structure. Put the repeated stuff first. Put dynamic stuff later. Do not casually insert timestamps, random IDs, user-specific values, or unordered JSON above the breakpoint. Because the cache is not a generous friend who understands your intention. It is a strict accountant checking whether the fingerprint matches.Same prefix, discount…Different prefix, full bill.What silently guarantees a missA model version change. K/V states are architecture-specific. A silent model update invalidates your entire cache. No warning.Block below minimum size. A breakpoint placed at 800 tokens does not error, it silently does not cache. Check cache_creation_input_tokens in your usage response. If it is 0, the write never happened.Things which worked for me to improve cache hitsBoth OpenAI and Anthropic have tips in their docs. The main idea is the same across both, maintain the longest possible stable prefix. But the official docs are not very nuanced, and there is a lot of room to make expensive mistakes in the gaps they leave.Here is what I actually changed at the thing I was building.Make the prefix stable, strip dynamic content from the system promptThe payoff is not just your own cache hits. A completely static system prompt means every user of your application shares the same prefix. The K/V states get written once and reused across all of them. The moment you personalise anything above the breakpoint, even a single field you have fragmented one shared prefix into thousands of unique ones. Cache hits across your user base drop to zero.2. Keep context append-only : : stop truncating mid-conversationThis one I got wrong for a while and it cost me without me realising it. I had a feature with multiple tool calls, and the outputs were getting long. I was worried about context rot on longer conversations so I was truncating the tool call outputs in the messages array once the conversation hit a certain length. What it was actually doing was mutating the prefix on every truncation, different token sequence, different hash, cache miss. I stopped the truncation. The context is now append-only → old messages stay, new ones get added at the end. The prefix stays stable through the conversation.Cache hit rate went up immediately!!Interesting side note, I am fairly confident Claude Code’s compaction works the same way, append-only to preserve the prefix, with compaction happening at the end rather than by mutating the middle.3. Use deterministic serialisation, sort_keys=True everywhereI experimented about the first two... This one I missed until I read the Manus’ blog and then went and verified it the hard way.When you serialise tool call outputs or config objects to JSON, Python dict ordering is insertion-order as of python 3.7+. That means two dicts with identical keys and values but built in different order produce different JSON strings, different token sequences, different hash, miss every time.# these produce different token sequences — different cache keyjson.dumps({"model": "gpt-4", "temp": 0.7}) # built one wayjson.dumps({"temp": 0.7, "model": "gpt-4"}) # built another way----# this always produces the same token sequence regardless ofinsertion orderjson.dumps(config, sort_keys=True)One line. sort_keys=True on every json.dumps() call that produces content above a breakpoint. The kind of thing you do not think about until you benchmark your hit rate and it is lower than it should be.4. Do not change tool definitions dynamicallyTool definitions live at the start or end of the system prompt internally, before the user messages. This means if you remove or reorder tools between requests, you are mutating the prefix at a very early position. Everything downstream of that change gets a different hash. All your breakpoints below it miss.The implication, tool definitions should be as stable as your system prompt. Add tools, do not remove them mid-session. If you need to conditionally expose tools, consider whether the cost of the cache miss is worth the cleaner interface.One worth knowing about, Anthropic’s Tool Search Tool https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool,which lets the model search for tools on demand rather than having all definitions upfront. I was curious whether this would break caching since tool definitions normally sit near the top. The docs clarify that these definitions are appended to the context, so the prefix stays intact and the pattern stays append-only. Cache-safe.5.prompt_cache_key on OpenAI, routing hintOn OpenAI, your API request needs to be routed to the same machine to hit the cache. OpenAI routes based on a hash of the initial prefix, roughly the first 256 tokens. You can pass a prompt_cache_key parameter which gets combined with that prefix hash, giving you some influence over routing when many requests share long common prefixes.Worth being precise about what this is and is not, it is a routing hint, not a cache breakpoint. You are not marking a cache boundary the way you do with Anthropic’s cache_control. You are helping the infrastructure route your request to a machine that is likely to have the right K/V states already loaded. I have not benchmarked this thoroughly yet but it is worth experimenting with if you are running high-volume workloads where routing variance is eating into your hit rate.TTL aka Time to Live ( specific to claude setups )I just want to mention TTL here because this part is mostly specific to Claude style prompt caching. OpenAI’s caching is more automatic. You do not sit there choosing between a 5-minute cache and a 1-hour cache. But with Claude, when you use cache_control, TTL becomes an actual decision you have to make.And the first thing to understand is this, TTL is not the first thing to optimize. If invalidation is breaking your keys, TTL is irrelevant.TTL only becomes a meaningful decision once the prefix is stable and the hits are actually landing. That ordering is not accidental, it is how the system works. When it does matter, it is not a cost dial. It is a question about the shape of your traffic.The write cost is higher than normal input,1.25× for 5-minute TTL2.0× for 1-hour TTLYou are paying a premium to store the entry. The assumption baked into that premium is that you will get enough reads within the TTL window to offset it. If you do not, you paid more than if you had not cached at all.5-minute TTL at 1.25× is built for sustained traffic. Requests arriving continuously against the same prefix, the cache is almost always warm, the write premium amortises across dozens of reads per window, and your effective cost on the prefix approaches 0.10×. The risk is gaps. Traffic drops for six minutes, the cache goes cold, the next request pays the write premium again.1-hour TTL at 2.0× is built for intermittent workloads. Agentic pipelines with gaps between steps. Long sessions where a user takes 20 minutes to respond. Batch jobs on a schedule. You are paying a higher write cost to buy a longer window of warmth. The math works if you get roughly 3+ reads within the hour — that is approximately break-even against no caching at all.One thing that changes the calculus, a cache read resets the TTL from that point. A cache entry under active traffic does not expire on a fixed clock, it stays alive as long as reads keep coming. The TTL is the length of silence the entry can tolerate before going cold. For high-traffic apps the 5-minute TTL is effectively immortal under load. For intermittent workloads the 1-hour TTL is insurance against natural pauses in traffic, not a hard expiry.Check cache_read_input_tokens in production. If you are seeing writes without matching reads, your traffic has gaps and the 1-hour TTL will serve you better.What prompt caching is notBefore I close, one thing is worth being very precise about because this is where people mix up two very different ideas.Prompt caching does not reuse responses. It does not save one old answer and replay it later. It does not look at two user questions and say, close enough, give the same thing.Two users asking the same question through the same cached prefix may get the same answer at low temperature, but that is not because the cache replayed anything. The model still generates the output from the current request. The cache only touched the reading phase, not the writing phase.That is why prompt caching is much safer than semantic response caching. It is not guessing meaning. It is not deciding which old answer deserves to come back. It is only reusing the repeated prefix computation inside the provider’s cache boundary. In boring engineering words, it saves prefill work.In humanistic words, it stops the model from rereading the same brief like it has never met your application before.And the price pages kind of prove why this matters. Claude prices normal input, cache writes, and cache reads differently (https://platform.claude.com/docs/en/build-with-claude/prompt-caching). OpenAI’s Standard pricing also separates normal input from cached input ( https://developers.openai.com/api/docs/pricing?latest-pricing=standard ). So cached tokens are not just some backend detail that sounds good in a docs page. They literally show up as a different price category. When your app sends an 8,000-token prefix 5,000 times a day, that is 40 million repeated input tokens daily. If those tokens are processed fresh every time, you are paying the full reading cost. If they become cache reads, that repeated part can drop by a large margin. Same app, same users, same model behavior. The difference is whether the system had to read the same beginning again.That is the cleanest way I can think about prompt caching now. It is not AI memory in the magical sense. It is not the model becoming more intelligent. It is not a shortcut around reasoning. It is just the reasonable kind of memory → remembering work, not answers.And honestly, that is a fair thing to cache.If I hand someone the same 40-page project brief every morning, at some point I also expect them to say, “bro, I have read this already.”That is prompt caching.But there is another cache in LLM systems that is much less innocent. That one does not ask, “Have I seen this exact prefix before?” It asks, “Have I seen something close enough?”And the moment a cache starts reusing answers based on closeness, it is no longer just saving computation, it is influencing what answer comes back.Prompt Caching was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.