Prefix Cache Hit Rates in Coding Scenarios: Causes and Troubleshooting
This article explains how prefix caching matches LLM requests and why coding workloads often reach high cache hit rates. It covers how to organize context so that prefixes stay stable, how to define and calculate hit rate metrics, and how to troubleshoot a noticeable drop in hit rate. It also includes a Python example for common prefix detection and block-level reuse estimation.
1. How Prefix Matching Works
LLM inference has two stages. Prefill reads the entire input at once and computes a key-value representation (KV cache) for each input token. Decode generates output tokens one by one, and each new token requires reading the KV entries of all previous content. The cost of prefill grows as the input gets longer. The linear parts of the computation, such as linear layers and embedding layers, scale roughly in proportion to input length. The attention part, under a simplified model, grows approximately with the square of the length. Combined, the prefill cost of a long input rises faster than its length.
Prefix caching works as follows. The server stores the KV results of past requests. When a new request arrives, the system compares tokens one by one from the first token, finds the longest prefix that matches a past request, reuses those results, and computes only the part that follows and differs.
Matching only looks at the beginning. If any position differs, all cache entries after that position become invalid, even if the later content is identical. The cache checks whether a prefix matches, not whether a piece of content has appeared anywhere in the history.
Most implementations manage the cache in fixed-size blocks, for example 16 tokens per block. If even one token in a block differs, the entire block cannot be reused. As a result, only complete blocks are actually hit.
2. Why Hit Rates Are Often High in Coding Scenarios
Coding scenarios have three properties that keep the prefix stable.
First, sessions are cumulative. Each conversation turn includes the full content of the previous turn, and the new request only appends content at the end. If the history stays exactly the same, most of the earlier tokens can be reused. For example, if the context has 20,000 tokens and 500 new tokens are appended, the first 19,500 tokens can be reused in theory, which is 97.5%. This is a theoretical upper bound. The actual value is somewhat lower due to block rounding and other factors.
Second, code changes are local. A single edit usually touches a few lines or one file. If the tool arranges repository context in a fixed order, content outside the modified file remains unchanged.
Third, system prompts and tool definitions are usually fixed. The system rules and tool schemas of a coding tool rarely change within a session, so they form the most stable opening part.
These three properties depend on stable content order and an unchanged beginning. The following factors break the prefix:
- Changing the beginning of a file invalidates all file content after it.
- The system prompt contains dynamic fields such as the current time, random request IDs, or usernames.
- Retrieved snippets are sorted differently each time, so the same files appear in a different order.
- Field order in JSON or tool definitions is not fixed.
- New content is inserted in the middle of the context instead of appended to the end.
3. How to Organize Coding Context
Arranging content from the least to the most frequently changing maximizes the length of the stable prefix. A practical order is:
- System prompt and behavior rules (almost never change)
- Tool definitions (fixed within a session, sorted by name)
- Project-level stable information, such as directory structure, dependency notes, and coding conventions
- File-level context, sorted by path, with each file’s content kept as is
- Conversation history, append-only and never rewritten
- The current user question and dynamic information (changes every time, placed last)
With this order, dynamic content only affects the end, and the stable parts before it can still be reused.
For retrieval results, use a fixed sorting rule, such as file path and line number, rather than relevance scores. Relevance scores may shift slightly between runs, and the resulting change in order breaks the prefix. If results must be sorted by relevance, apply one stable sort right before the final output, so identical snippets always stay in the same position.
4. Defining Hit Rate Metrics
Before discussing hit rates, agree on the definitions. Otherwise, two teams’ numbers cannot be compared.
- Token-level hit rate = number of input tokens served from cache / total number of input tokens. This is the most common definition, and it directly reflects the saved prefill computation.
- Block-level hit rate = number of complete blocks hit / total number of input blocks. This is used to analyze the effect of block size.
- Request-level hit rate = number of requests whose hit rate exceeds a threshold / total number of requests. This shows the distribution and keeps a few very long requests from hiding the overall picture.
When collecting statistics, use the cached token count returned by the service provider. Vendors may use different field names and meanings in their responses. Some include output tokens and some do not. Before integrating, read the relevant documentation to confirm the definition, and fix one calculation method in your own logs.
No single number defines a reasonable hit rate range. The range depends on whether sessions are cumulative, whether the context is stable, and whether the interval between requests exceeds the cache retention time. In coding scenarios, hit rates above 90% for long sessions are common. This reflects one type of workload, so it should not be treated as a guaranteed value for all scenarios.
To judge whether a hit rate is reasonable, check the following items one by one.
- Does the current request continue the history of the same session?
- Does the prefix contain dynamic fields such as timestamps or random IDs?
- What is the common prefix length L with the previous request, and what proportion of the input length N does L represent?
- Under block size B, what is the theoretical upper bound of the hit rate?
- Is there a clear gap between the actual hit rate and the theoretical value? If so, see Section 6 for troubleshooting.
5. Block Size and Estimation Method
The inference engine determines the block size. Common values range from about ten to several dozen tokens. Let B be the block size, L the common prefix length of two requests, and N the number of input tokens in the current request. The reusable token count is:
Reusable tokens = floor(L / B) × B
The estimated hit rate is:
Hit rate ≈ floor(L / B) × B / N
The loss caused by block rounding is L mod B, which is the part that does not fill a complete block. If the divergence point is evenly distributed within a block, the average loss per request is about (B - 1) / 2 tokens. This assumes a uniform distribution, so validate the actual distribution with logs.
Example: N = 8000, L = 6500, B = 16. Then floor(6500 / 16) × 16 = 406 × 16 = 6496, and the estimated hit rate is about 6496 / 8
