LLM Prompt Caching and Token Cost Reduction: How Cache Hits Work
This article explains how prompt caching reduces token costs in large language model inference. It covers what the KV cache actually stores, why exact prefix matching is required under causal attention, why multi-turn conversations benefit naturally, and how different inference backends implement caching. It also provides a practical engineering checklist for improving cache hit rates and discusses design trade-offs for AI agents. The result is a measurable cost-reduction approach that applies to both cloud API billing and self-hosted GPU memory management.
1. Why Your Bill Doesn’t Scale With Call Volume: Where the Problem Comes From
An automated task can finish after hundreds of model calls, each carrying a full context of hundreds of thousands of tokens, yet the cost does not grow proportionally. The answer is hidden in a field in the usage response: different platforms expose this metric under names such as “cached tokens.” Measured behavior on coding-agent tasks shows that a single-step request often reads roughly 119K tokens of historical prefix, performs full computation only on about 875 newly added tokens, and bills most of the former at a discounted fraction of the standard input price.
This field is not a marketing concept. It is the external projection of a low-level rule in the inference system. API pricing, GPU memory management, cluster scheduling, and even agent framework design all operate under its constraints. Understanding it means understanding both the cost structure and the performance boundary at the same time.
2. What Is Actually Cached: Intermediate Computation, Not Answers
Before generating each token, an autoregressive model performs a forward pass over the current input, a step commonly called prefill. Prefill produces two tensors for every input position at every layer, the Key and the Value, collectively known as the KV cache. The Query of subsequent tokens only needs to attend to these existing K and V tensors; the intermediate results for the historical portion do not need to be recomputed.
The physical essence of the KV cache is therefore “the intermediate state already computed for this prefix,” not a ready-made answer. This determines that its reuse conditions are extremely strict.
The Hard Rule Imposed by Causal Attention
Cross-request reuse relies on one property of causal attention: the K and V at position i are determined only by the tokens before it. The same word preceded by a different prefix produces completely different tensors. This yields the hard matching rule:
- Only a prefix that is identical token by token from the very first token can be reused;
- Any difference anywhere in the sequence invalidates all KV tensors after it;
- Two prompts that are semantically close will not hit at all if their token sequences differ.
There are also solutions on the market that return old answers directly based on semantic similarity. Those belong to retrieval systems, and the risk of wrong answers depends on retrieval quality. That is a separate mechanism from the exact prefix reuse discussed here, and the two should not be conflated.
3. Why Multi-Turn Conversations Benefit Naturally
Multi-turn reuse is built directly on this rule. On every turn the client still sends the complete history from the system prompt to the latest message, and the server does not receive any fewer tokens. In a self-hosted inference engine, the input KV computed in the previous turn remains in GPU memory after the request ends, and the output KV of the generation phase continues on the same sequence. The prefix of the next request is exactly identical, so the hit can extend all the way to the end of the previous reply, and the engine only runs prefill on the newly appended tail.
Cloud APIs present the same thing through breakpoints and billing fields: the cache object is the KV tensors corresponding to the rendered prefix, the current turn’s output is always billed at the output price, and the previous turn’s reply enters the cache range only when it is resent as input in the next turn. How much is actually hit is determined by the usage fields, and identical input does not guarantee identical output.
A sample usage structure is shown below (field names are for illustration only):
{"prompt_tokens": 120000,"completion_tokens": 900,"prompt_tokens_details": { "cached_tokens": 119000 }}
4. Implementation Differences Across Inference Backends
Different engines implement caching in different ways, but the goal is the same: keep the prefix KV alive in GPU memory and reuse it correctly.
- Paged GPU memory management: KV memory is split into fixed-size blocks (typically 16 tokens), requests allocate by block, and a logical block table maps to non-contiguous physical blocks, which alleviates fragmentation; on a prefix hit, the engine only reuses existing blocks and appends new ones.
- Prefix-tree indexing: cache nodes are organized with the token sequence as the path, a new request matches the longest common prefix along the tree, and the hit length determines how much prefill can be skipped.
- Runtime files and memory mapping: in single-machine or local deployment scenarios, a computed prefix is persisted and loaded again to avoid repeated computation.
The shared constraint of all three is still an exactly identical prefix; the differences lie only in block granularity, eviction policy, and concurrent scheduling.
5. Improving the Hit Rate: An Engineering Checklist
- Keep the prefix stable: put the system prompt, tool descriptions, and examples at the front and keep them byte-level stable; avoid timestamps, random IDs, and lists with unstable ordering entering the prefix.
- Append rather than rewrite: append historical messages to the end, do not rewrite or reorder earlier content, since a single change invalidates everything after it.
- Converge tokenization differences: standardize numbers, whitespace, line breaks, and formatting templates to prevent the rendering layer from introducing inconsistencies.
- Reuse the same session context: bind consecutive steps to the same prefix to reduce cold starts.
- Control eviction risk: under high concurrency, GPU memory blocks may be reclaimed and the hit rate will fluctuate, so observe it with monitoring alerts and logging services.
- Make it observable: build a hit-rate metric from cached tokens and total input tokens, and include it in capacity and cost dashboards.
6. Design Trade-offs for Agent Frameworks
The single-step shape of an agent determines the upper bound of the benefit: the longer the prefix and the shorter the addition, the higher the proportion covered by the discount. In design, deterministic content should be placed first and volatile content last; tool return values should be structured and serialized stably as much as possible; for early content that must change, consider isolating the change to the tail with a “reference plus appendix” approach. It is worth emphasizing that caching only reduces input-side cost, while output tokens and failed retries remain the main variables. Compressing ineffective loops and reducing repeated file reads is often more effective than tuning parameters.
7. Conclusion
The essence of a cache hit is the exact reuse of the prefix KV. The rule is simple but the constraints are hard. By keeping the prefix stable, pushing changes to the end, and making the hit rate an observable metric, you can obtain cost benefits on both the API billing path and the self-hosted GPU memory path. On top of the general inference and monitoring capabilities of platforms such as Baidu AI Cloud, this approach can be implemented directly as a measurable cost-reduction practice.
