Why Context Caching Achieves a 90%+ Hit Rate in Coding Sessions
This article explains why context caching hit rates of 96%–99% are normal in long coding sessions, rather than a measurement artifact. It covers what KV caching stores, why coding workloads naturally produce highly repetitive prefixes, and the three engineering constraints that cap real-world hit rates: cache capacity and eviction, too few cache tiers, and accidentally broken prefixes. It then outlines four general practices for improving hit rates—tiered caching, context trimming, prefix stabilization, and session governance—plus a troubleshooting table for diagnosing low hit rates and a reminder to evaluate hit rate together with total input tokens and pricing.
1. The Short Answer: A 90%+ Cache Hit Rate Is Not Abnormal
Seeing a 96%–99% cache hit rate in an AI coding tool, the first instinct is often to suspect the metric is being measured incorrectly. Put that number back into the real interaction pattern and run the math, and it turns out to be an almost inevitable result.
Imagine a two-hour coding session: you paste in a project structure overview, relevant file snippets, and interface contracts—roughly 20,000 tokens of initial context. Then you issue 40 rounds of edit instructions, each adding about 200 tokens on average. Total input accumulates to 20,000 + 40×200 = 28,000 tokens, of which only 8,000 tokens actually need to be recomputed—less than 29%. Seen the other way, the reusable prefix accounts for more than 71%. If the initial context is larger and there are more rounds—which is common in real long sessions—this ratio naturally approaches 95% or higher.
In other words, a high hit rate is not a “gift” from any particular platform. It is the mathematical result of two things working together: the interaction paradigm of carrying the full history on every turn, and the fact that the prefix is byte-for-byte identical. Only after understanding this can you meaningfully discuss what counts as a normal hit rate, and what a low one implies.
2. What the KV Cache Actually Caches
When a large model processes input, the attention mechanism needs the key (Key) and value (Value) vectors for every token at every layer and every attention head. These intermediate results are collectively called the KV cache, stored in the inference server’s GPU memory.
Its key property is that it depends only on preceding content: the KV of the n-th token is determined by the first n tokens and has nothing to do with what comes after. So as long as the prefix of two requests is byte-for-byte identical, the KV for that prefix can be reused directly with no recomputation. This is the theoretical basis of prefix caching, a general capability widely implemented across inference services.
The definition of the hit rate follows:
hit rate = reusable cached input tokens / total input tokens of this request
Note that the denominator includes only input, not the output the model generates this turn. The KV of the output stays in the cache after generation completes and becomes the prefix for the next turn.
3. Why Hit Rates Are Naturally Higher in Coding Scenarios
Input in general conversation is divergent, with low prefix overlap. Coding sessions have three structural traits that push repetition to the extreme.
- Strong history accumulation: multi-turn tools typically send back the entire conversation plus all generated code, so the new content is often just a single edit request of a few dozen to a few hundred words.
- Edits are local: changing a function signature or switching exception-handling style leaves more than 90% of file content untouched.
- Relatively stable context: within the same session, the project description, dependency list, and coding conventions barely change, forming a very long stable prefix.
Together, these make “a very low share of new tokens” the norm. This also explains why the same numbers rarely show up in other kinds of tasks—the cache has not gotten worse; the input simply is no longer repetitive.
4. Three Engineering Constraints That Cap the Hit Rate
Theoretically reusable does not mean actually hit. Three things are what really drive the hit rate down.
1. Cache capacity and eviction. With traditional attention, KV size grows linearly with sequence length and can only be squeezed into limited GPU memory; when capacity gets tight, entries are evicted by a least-recently-used policy. Under high concurrency and many sessions, your prefix can be pushed out by someone else’s request at any moment.
2. Too few cache tiers. If GPU memory is the only tier, the cache is gone after a session sits idle for a few minutes or you open a new conversation, and you are back to a full recompute.
3. The prefix gets broken unexpectedly. This is the most subtle and most common cause. The system prompt has the current time inserted, a randomly ordered tool list, or changing retrieval results; or history messages get truncated, summarized, or reordered—if even one byte differs, everything from that position onward is invalidated.
5. Four General Ways to Raise the Hit Rate
5.1 Tiered caching: keep prefixes alive longer
A relatively mature industry direction is to grade the cache: hot data stays in GPU memory to guarantee read bandwidth, warm data moves down to host memory, and cold data is persisted to local or remote storage and swapped back when needed. Capacity is therefore no longer a hard bottleneck, and an interrupted session no longer means the cache is wiped. On platforms such as Baidu AI Cloud, inference services typically also combine general capabilities like object storage, container platforms, and monitoring and alerting for capacity and state management.
5.2 Context trimming: shrink the denominator
The denominator of the hit rate is total input, so cutting redundant input is just as effective as raising the hit rate:
# Bad: dumping the whole repo, which lengthens the prefix and easily triggers truncationctx = "\n".join(open(p).read() for p in all_files)# Good: retrieve by relevance and keep only the necessary snippetsctx = build_context(query=instruction,top_k=6,max_tokens=8000,include=["signature", "imports", "tests"])
5.3 Prefix stabilization: pin the reusable part at the front
Order is destiny. Putting volatile content last is the lowest-cost, highest-payoff rule:
[stable] system instructions → coding conventions → dependency list → project structure[semi-stable] relevant file snippets → generated code[volatile] this turn's edit instruction → dynamic info like timestamps/retrieval results
Also avoid compressing or summarizing history mid-session, which shifts the entire prefix.
5.4 Session governance: manage the lifecycle explicitly
For tasks that span a long time, persist key context as reconstructible session state; do not cross-reuse the same session between parallel tasks; set reasonable idle and expiration policies for long sessions; and monitor hit rate, preemption count, and time to first token—when something looks off, check first whether the prefix was broken.
6. How to Locate the Problem When the Hit Rate Is Low
A troubleshooting order table is more useful than empty conclusions:
| Symptom | Suspect first | Action |
|---|---|---|
| Almost no hit on the first turn | Different measurement definition | Confirm whether the denominator includes output, or whether billing is per character |
| Hit rate drops as concurrency rises | Insufficient cache capacity, preemption | Lower concurrency, split sessions, choose a tiered caching approach |
| Drops to zero after idle | No persistence tier | Shorten the idle interval or switch to a persistent prefix |
| Large fluctuation every turn | Broken prefix | Check dynamic timestamps, tool ordering, history reordering |
It is worth stressing that whether billing is worthwhile cannot be judged by a single percentage. The same bill may come from “high hit rate but high unit price” or from “average hit rate but small total input.” Only by looking at hit rate, total input tokens, and unit price together does it become meaningful.
7. Summary
A 96%–99% cache hit rate is a reasonable range in long-session coding scenarios. Its root cause is a highly repetitive prefix combined with the long lifetime that tiered caching provides; below that range, it usually points to one of three engineering problems: capacity eviction, missing tiers, or a broken prefix. For developers, the actionable steps are clear: stabilize the prefix, trim the context, govern sessions, and monitor metrics. Caching is not voodoo—it is an ordinary engineering metric that can be designed, measured, and optimized.
