LLM Prompt Caching and Token Billing: How Cache Hits Actually Work
This article explains how prompt caching works in large language models and why it changes your token bill. It clarifies a common misconception: what gets cached is not the model's answer but the intermediate Key-Value (KV) tensors produced during prefill. You will learn how prefix matching works from token zero, how the three cost components (uncached input, cached input, and output) interact with write and storage charges, and how three typical caching strategies differ in trade-offs. It also includes a practical checklist for diagnosing why caching fails to reduce costs and engineering guidelines for improving cache hit rates.
1. First, a Common Misconception: The Answer Is Not What Gets Cached
When people first encounter the idea of “prompt caching,” they often assume it means storing the previous answer and returning it directly when the same question comes up again. That assumption is wrong.
A simple counterexample: send several identical requests back to back. As long as the sampling temperature is not zero, the outputs will still differ in subtle ways. If the cached object were the output text, this could not happen.
So the object that gets a “hit” is never the content the model generates. It is a set of intermediate tensors produced while the model processes your input.
2. What a Hit Really Means: The Two Stages of Inference
LLM inference can be roughly split into two stages.
The first stage is prefill. The model computes a set of intermediate values for every input token across every attention layer, commonly called Keys and Values, or KV. This step is pure compute: the longer the input, the more compute and GPU memory it consumes. For long documents or large codebases that run to tens of thousands of tokens, prefill is often the main source of time-to-first-token latency.
The second stage is decode. The model generates the answer token by token. At this point it needs the KV of all preceding tokens. Recomputing the entire prefix for every generated token would be prohibitively expensive.
Therefore, the KV computed during prefill is kept temporarily in a region called the KV Cache. Its original purpose was to avoid recomputing the prefix within a single request: when generating the 100th token, the KV of the first 99 tokens can be reused directly.
Prompt caching, also called prefix caching, extends the boundary of this reuse from within a single request to across multiple requests. The KV for the first few thousand tokens of your current request was already computed and fully retained by a previous request. If the beginning is identical this time, there is no need to recompute it; the cached KV is loaded and decoding continues.
This leads to the most important sentence in this article: a cache hit means the computation result for the prefix at the start of the request was successfully reused; a cache miss means no reusable prefix was found and prefill must start from scratch. The hit portion consumes almost no compute, which is precisely why providers can offer substantial discounts.
3. The Single Basic Rule: Exact Token-by-Token Match from Token 0
Prefix matching is strictly token by token. Comparison starts at the first token of the sequence and continues until the first position where the tokens differ. This yields several implications:
- The earlier a difference appears, the shorter the reusable length. A single extra greeting, a timestamp, or a random request ID at the beginning can turn tens of thousands of following tokens into a miss.
- A hit is a “longest common prefix,” not a “similarity” match. Semantically similar but literally different text will not hit.
- Order matters. Swapping the system instructions and the user’s background material creates a different prefix.
- Stability matters more than content quality. Any field that changes on every request should be moved as late as possible.
A schematic layout looks like this (pseudocode, expressing ordering only):
[ Stable: system role, output rules, tool definitions, fixed background knowledge ][ Semi-stable: the completed portion of the conversation history ][ Volatile: current time, user ID, the current question ]
4. How the Bill Changes: Writes, Storage, and the Hit Discount
Breaking the cost apart, a request’s charge typically consists of three parts: uncached input tokens, cached input tokens, and output tokens. Their unit prices vary greatly across schemes, but the structure is the same.
The first is the write cost. A cache does not exist out of nowhere; the prefill result has to be saved, and some schemes charge the input for this “cache write” at a price higher than normal input. This explains a common confusion: why the first request becomes more expensive after enabling caching. You are paying to build the cache.
The second is the storage cost. The KV Cache occupies GPU memory or a storage medium and is retained only within a time window, so some schemes bill per token-time. Expired windows and capacity eviction both make the cache disappear.
The third is the hit discount. The unit price of the hit portion can drop to a small fraction of the original, but the size of the discount depends on where the scheme shifts the cost: the more expensive the writes and storage, the more dramatic the hit discount tends to be, and vice versa. This is also why “how much cheaper a hit is” varies enormously between platforms, and why you cannot simply say one is giving away value while another is charging.
As for output tokens, they are always billed at the standard price; caching has no effect on them.
5. A Neutral Comparison of Three Typical Strategies
Three approaches can be abstracted from the industry. Understanding their trade-offs is more valuable than memorizing a specific product.
Fully automatic and transparent. The platform detects and reuses prefixes automatically, with no declaration required from the user, and usually no separate write fee, with a relatively moderate discount. The advantages are low integration cost and predictable behavior; the drawback is that the hit window and capacity policy are opaque to the user.
Semi-automatic with declaration. The user must explicitly mark cache breakpoints, declaring “cache up to this point.” Writes and storage are billed separately, and the hit discount is deeper. The advantage is strong control, suited to scenarios with very long prefixes and high reuse frequency; the cost is the engineering effort, and a misplaced breakpoint means paying the write fee for nothing.
Fully automatic with persistence. Automatic prefix reuse is done without extra charges, and the cache is pushed down to cheaper media such as disk to extend retention and expand capacity. Its cleverness lies in trading the cost difference between storage media for a longer lifetime and a higher hit rate, so the effective unit price can be pushed very low; the cost is that the first access must load from the medium, giving it a different latency profile from the other two.
6. Why “Caching Is Enabled but Nothing Is Saved”
You can check the following in order:
- Is the prefix truly identical character by character? Check whether the beginning injects a time, a random number, or a retry marker.
- Is volatile content placed at the front? The system prompt and tool definitions should be fixed at the very beginning.
- Does the request interval exceed the cache’s lifetime window? Sending a batch serially usually yields a higher hit rate than sending requests scattered over time.
- Are you frequently switching between more than two prefixes? Alternating use causes caches to evict each other.
- Are the write and storage fees canceling out the savings? With short prefixes and low reuse frequency, enabling caching can be a net loss.
- Is the input rewritten midway? Summarizing or trimming the history in a multi-turn conversation makes all subsequent requests miss.
7. Engineering Practice Recommendations
For developers, these practices are actionable:
- Prefix layering: arrange content in layers by how often it changes, with stable content first and volatile content last.
- Stable serialization: keep JSON key order, whitespace, and casing fixed to avoid inputs that are equivalent but literally different.
- Breakpoint planning: place cache breakpoints at the end of long prefixes so the high-reuse portion is as long as possible.
- Batching and concurrency: send requests that share the same prefix together to raise the hit rate within the window.
- Observability: use logging services and monitoring alerts to track the ratio of cached tokens, the number of writes, and storage overhead, treating the hit rate as a metric to optimize continuously.
- Cost modeling: estimate the real unit price with “hit discount × hit rate + amortized writes + storage cost” instead of looking only at the discount number.
8. Conclusion
What a cache hit saves is the compute for the batch of matrix operations the model performs while reading your text, not the answer it gives. Once you understand three things — the cached object is the prefix’s KV, the matching rule is exact token-by-token agreement from token 0, and the cost structure is uncached input plus cached input plus output with writes and storage on top — you can derive the answers to most billing questions yourself and turn the hit rate into a measurable, optimizable engineering metric. In scenarios such as long context, fixed system prompts, and batch offline processing, this optimization often makes an order-of-magnitude difference in cost.
