How Prompt Caching Works: Why Identical Prefixes Save Money
This article explains how prompt caching works in large language model APIs and why cached tokens cost less. It covers why the cache stores intermediate KV data rather than model answers, how the prefill and decode stages relate to caching, why a cache hit requires an identical prefix from the first token, why caching sometimes fails to save money, how explicit and automatic caching differ, and how to structure prompts to get more cache hits.
1. Clearing up a common misconception: the cache does not store answers
Many people first encountering “cache hits” in LLM APIs assume it works like a web page cache. In that model, the previous response is saved and returned when the same question arrives again. This understanding is wrong.
A simple counterexample: send the same prompt ten times in a row. As long as the temperature is not 0, you will most likely receive ten answers with different wording. If the cache stored answers, this could never happen. So the thing that gets “hit” is never the model’s output.
So what is it? Answering that requires looking inside the internal structure of Transformer inference.
2. The two stages of inference: prefill and decode
Processing a single request takes roughly two stages.
Stage 1: prefill (pre-filling). The model computes a set of intermediate values for every input token at each layer of the attention mechanism. These are the Key and Value vectors that people often refer to. This step is compute-intensive and requires a large number of matrix operations on the GPU. The longer the prompt, the more GPU resources and time this step consumes.
Stage 2: decode (decoding). This is the stage where the answer is produced one token at a time. To generate each new token, the model refers to the Key and Value vectors of all previous positions and uses the attention mechanism to compute the probability distribution of the next token.
The Key and Value vectors computed during prefill are stored temporarily. This data is called the KV Cache. Its original purpose is to spare the decode stage from recomputing the preceding text. When generating the 100th token, the KV values for the first 99 tokens can be used directly without recalculation.
3. The essence of prompt caching: extending KV Cache reuse across requests
Once the KV Cache is understood, prompt caching (also called prefix caching) is straightforward. It extends the reuse of the KV Cache from a single request to multiple requests.
In other words, the KV values for the first 5,000 tokens of your request may already have been computed and stored by the provider during an earlier request. When a new request arrives with the exact same opening, there is no need to compute them again. The stored KV values are loaded and used directly, skipping the full prefill computation for those tokens.
A cache hit refers to this situation: the beginning was computed before, and it can be reused directly this time. A cache miss means no reusable prefix was found, so everything must be computed from scratch. Cached tokens consume almost no GPU compute. That is why cached prices can drop to one tenth of the regular token price or even lower. The savings come from avoiding the large matrix operations.
4. The rule for hits: the prefix must match exactly from token 0
Whether content can be reused follows one basic principle: the prefix must be identical from token 0.
This requirement is stricter than many people expect. Transformer attention is computed layer by layer, and the KV of each token depends on the results of all tokens before it. If even one token differs in the middle, the KV values for every token after that position change, and the cache chain breaks at that point.
Several practical guidelines follow from this:
- Put the system prompt at the very beginning, and keep it completely fixed. The system prompt is usually the longest and most stable part of a request, so it is the main factor in cache hit rate. Changing even one punctuation mark invalidates the entire cached segment.
- Place dynamic content at the end of the request. Variable information such as the user’s specific question, timestamps, and random IDs belongs at the tail of the prompt so that it does not pollute the prefix.
- Do not insert changing content near the start of the prompt. For example, putting the current date or randomly selected few-shot examples at the beginning causes every request to miss the cache.
5. Why caching is enabled but no money is saved
With the principles above, many billing questions become easier to answer:
- Dynamic content is mixed into the prefix. For example, a session ID or timestamp placed at the start of the message body makes every prefix different, so the cache never hits.
- The interval between requests exceeds the cache lifetime. KV Cache occupies GPU memory or storage, so providers typically keep it for a limited time. After it expires, it is cleared, and the next request must recompute it.
- Too few requests, or prefixes that are too short. The savings from caching are proportional to the number of reused tokens. If each reusable prefix is only a few hundred tokens, the savings may be negligible. Scenarios such as long-document Q&A, long multi-turn conversations, and batch processing of the same long context, where prefixes can reach tens of thousands of tokens, produce much larger savings.
- Caches do not carry over between different models or parameter configurations. The cache is an intermediate result tied to a specific model and configuration, so it generally must be rebuilt after switching model versions.
6. Explicit and automatic caching: two common mechanisms
Across the industry, inference providers generally manage caching in one of two ways:
- Explicit caching: Developers mark which parts of the prompt should be cached, usually by setting cache breakpoints. The cache lifecycle is relatively controllable. With this mechanism, writing to the cache typically costs slightly more than regular input tokens, in exchange for a substantial discount on later requests. In essence, you pay a small storage and maintenance cost in return for reduced compute each time the content is reused.
- Fully automatic caching: The provider detects and caches prefixes that have appeared recently, without any markup from developers. Because KV data can be stored on lower-cost media such as hard drives, cache read prices under this mechanism can often be set very low, and the discounts on hits are more aggressive.
Each mechanism has trade-offs. Explicit caching offers strong control and clear hit boundaries, which suits scenarios where the prefix structure is fixed. Automatic caching requires no integration effort, but it is more demanding about request structure, because even a slight change to the prefix prevents a hit.
7. Prompt design recommendations for cost
Based on the principles above, the following structure helps caching reduce costs:
[Fixed system prompt: the longer and more stable, the better; always place it first][Fixed tool definitions and format instructions: keep them unchanged where possible][Stable reference documents and knowledge base excerpts: keep them consistent across turns][Variable content: the current user input, timestamps, random parameters; place it last]
The core idea fits in one sentence: put what does not change at the front and what changes at the back, so that every request builds as much as possible on the results computed for the previous one.
Once you understand the two key points, that the cache stores KV data rather than answers and that prefixes must match exactly, you can work out for yourself why cache hits are cheap, why caching sometimes does not save money, and why mechanisms differ so much across providers. For applications with high token volume and long contexts, restructuring requests to be cache-friendly is often one of the most effective ways to lower costs significantly without changing any model code.
