What Is LLM Cache Hit and How Does It Reduce Token Costs?
This article explains what a cache hit means in large language model (LLM) inference and why it lowers token costs. It covers the prefix reusability enabled by causal attention, the role of KV Cache, the hard constraints that determine hit rates, and a cost model for AI Agent workloads. It also outlines cache-friendly context engineering practices, observability metrics, and the platform-side capabilities required to make caching work reliably.
1. A Counterintuitive Pattern: Hundreds of Calls, No Exploding Bill
When a coding agent completes a single end-to-end task, it may trigger hundreds of model calls internally. Intuitively, if every round had to resend the full conversation history of hundreds of thousands of tokens, the cumulative input volume would be astronomical, and the cost should grow linearly or even superlinearly.
Yet the real bill is often far lower than that intuition suggests. The reason is not mysterious: usage details usually contain two side-by-side fields, one for “input tokens served from cache” and another for “input tokens that went through full computation.” Different platforms name these fields differently, but the semantics are the same — the former is billed at roughly one tenth of the standard input price, while the latter is billed at the standard rate.
A measured profile of a typical single agent step looks roughly like this:
Reusable history prefix: ~119,000 tokens -> billed at ~1/10 priceNew content this round: ~ 875 tokens -> billed at standard price
In other words, more than 99% of the input in a single request is content that has been “read but does not need to be recomputed.” Understanding this rule is the key to understanding the cost structure of modern LLMs.
2. The Technical Essence of a Cache Hit: Prefix Reusability in Attention Computation
2.1 Why Autoregressive Inference Can “Compute Less”
Autoregressive generation in LLMs has an important property: under a causal attention mask, the representation at position i depends only on the tokens before it and is independent of anything that comes after. This means that when the prefix of a request is identical to the previous request (system prompt, tool definitions, conversation history, contents of files already read), the intermediate state for that portion — the Key/Value tensors — does not need to be recomputed mathematically and can be reused directly.
This reused intermediate state is what is commonly called the KV Cache. A “cache hit” essentially means the new request’s prefix matches the cached prefix token by token, so the inference system skips the matrix operations for that prefix and performs a full forward pass only for the newly added tokens.
2.2 Why a Hit Is “Cheaper”
The cost difference comes from differences in hardware resource consumption:
- Compute side: Processing a 119K prefix requires a massive number of matrix multiplications, a compute-intensive operation; with a cache hit, this compute overhead is eliminated.
- Memory access side: On a miss, the weights and activations of the long prefix must be repeatedly moved into the compute units; on a hit, only the KV tensors in the cache need to be read.
- Scheduling side: The prefill phase of a long prompt takes considerable time and stretches time-to-first-token; with a cache hit, the first token arrives noticeably sooner.
Precisely because what is saved is real resources, providers have room to offer a significant discount on the cached portion. This is not a marketing giveaway but a natural mapping of the cost structure.
3. Key Constraints That Determine the Hit Rate
Caching is not “cache exists, therefore hit.” It comes with a set of hard prerequisites, and breaking any one of them forces the entire prefix to be recomputed.
- Strict prefix identity: The prefix must match token by token, compared from the very first token; everything after the first point of difference is invalidated.
- Order sensitivity: Reordering history messages or rewriting earlier content causes everything after it to miss.
- Limited time window: The cache has a lifetime (usually on the order of minutes) and is evicted after a long idle period.
- Capacity constrained by GPU memory: The cache occupies GPU memory, and the cluster evicts entries by policy when memory is tight, so long-tail prefixes are more likely to be evicted.
- Isolation boundaries: The cache is isolated per tenant/session and cannot be reused across entities.
- Binding to model and parameters: Switching model versions or changing sampling or template parameters that affect prefix encoding usually invalidates the cache.
The first item is the most easily overlooked and the most often broken unintentionally in practice.
4. The Cost Model in Agent Scenarios
Let the standard input price be P, the cache-hit discount be 0.1P, the history prefix length be H, the per-step addition be Δ, and the total number of steps be N with a steadily growing prefix. Then:
Without caching: Cost ≈ N × (H + Δ) × PWith cache hit: Cost ≈ N × (H × 0.1P + Δ × P)
When H ≫ Δ (the typical agent profile), the cost can drop by close to an order of magnitude. But note two factors that “eat into” the savings:
- Cache write cost: Establishing the cache for the first time is usually billed at slightly above the standard price, so if the prefix is used only once, it actually costs more.
- Sunk cost of a cache miss: Once the prefix is modified and recomputed, you pay both the write fee and the standard price.
So the economics of caching hold under one condition: a long prefix + multiple reuses + a stable prefix.
5. Cache-Friendly Context Engineering Practices
5.1 Layered Structure: Separate the Stable from the Volatile
A recommended approach is to organize context into a “stable layer + volatile layer”:
[Stable layer] System instructions -> Tool/function definitions -> Project conventions -> Long-term unchanged file contents[Volatile layer] Current user input -> Current tool execution results -> Temporary reasoning drafts
There is only one principle: the more stable the content, the earlier it goes; the more volatile the content, the later it goes.
5.2 A Checklist of Common “Cache-Breaking” Operations
- Inserting the current timestamp, a random request ID, or a live counter into the system prompt;
- Prepending tool return results to the very front of the history every round;
- “Compressing and summarizing” earlier messages and replacing them in place;
- Dynamically trimming the history window, which shifts the starting point of the prefix;
- Switching models or parameters such as temperature that affect encoding back and forth within the same session.
5.3 How to Handle Long Documents and Retrieval
When dealing with a large repository or long documents, prefer “retrieval + stable injection”: inject the retrieved fragments into the stable layer in a fixed format at a fixed position, rather than re-retrieving every round and changing the concatenation result. If the content needs to change frequently, put it in the volatile layer to avoid polluting the prefix.
5.4 Observability: Measure Before Optimizing
The prerequisite for optimizing the cache is being able to see the cache. On a self-built pipeline, it is advisable to instrument and collect: cached tokens per request, hit rate, time-to-first-token, and the number of cache writes and their failure reasons. General-purpose logging services, monitoring and alerting, and message queue capabilities can be used to aggregate usage data into a dashboard and set trend alerts on the hit rate. Without measurement, cache optimization is guesswork.
6. Platform-Side Supporting Capabilities (A General View)
For caching to take effect reliably, the underlying inference platform typically needs: tiered GPU memory management and cache pooling, session-affinity cluster scheduling (routing the same session to the instance holding its cache), cache lifetime and eviction policies, and fine-grained usage metering with billing fields split apart. In the combination of general-purpose infrastructure such as Baidu AI Cloud’s LLM services, container platform, and object storage, these capabilities are the platform’s responsibility; what developers control is how requests are constructed and how context is organized.
7. Conclusion
A cache hit is not an “optional optimization” but the cost foundation of long-context agents. It is determined by the prefix reusability of causal attention, constrained by consistency, timeliness, and GPU memory capacity, and forms a complete chain of constraints across API billing, GPU memory management, cluster scheduling, and agent framework design. For developers, the implementation can be summed up in three sentences: put stable content first, put volatile content last, and make the hit rate an observable metric. Only by doing these three things will the capability gains from long context not be canceled out by the growth of the bill.
