How Prefix Cache Hit Rates Approach the Limit: Cutting LLM Agent Costs
This article explains why a 4-point difference in cache hit rate, such as 95% versus 99%, can translate into several times the cost for high-volume coding agents. It contrasts general-purpose adapter architectures with model-specific designs built around prefix caching, then lays out three engineering constraints that maximize the longest common prefix: strict append-only context, immutable prefixes locked at session start, and keeping volatile drafts local. It also covers reproducible measurement methods and common pitfalls, offering practical guidance for controlling token costs in LLM agent deployments.
1. The Problem: Why 4 Percentage Points Can Mean 5x the Cost
When evaluating AI coding tools, many people compare numbers like “95% cache hit rate” and “99% cache hit rate” and assume the difference is trivial—just 4 percentage points, so the real-world experience should be nearly identical. In demanding, high-intensity development scenarios, that intuition is wrong.
Imagine a developer triggering roughly 435 million input tokens of inference requests in a single day. At a 99.82% hit rate, only a small fraction of tokens are billed at full price while the vast majority are billed at a discounted rate, bringing the total daily cost down to the low tens of dollars. If the hit rate falls back to around 95%, the proportion of full-price tokens rises by an order of magnitude under the same request volume, and the cost balloons several times over. The root of the difference is not “4 percentage points” but which base the uncached tokens are calculated from, and whether the billing discount applies to the entire prefix or only to fully identical requests.
For this reason, discussing the performance of coding agents cannot stop at surface-level metrics like “how many models are supported” or “how friendly the interface is.” It has to go deeper, into the coupling between cache semantics, how context is organized, and the billing model.
2. Two Architectural Paths: General Adaptation vs. Model-Specific
2.1 General-Purpose Adapter Architecture
A common type of general-purpose coding assistant in the industry is designed around the goal of “one shell that adapts to many model capabilities.” This forces an abstraction at the architecture level: smoothing over interface differences across model providers and normalizing them into a single internal request format. The advantage is flexibility; the drawback is that it cannot deeply optimize for the caching characteristics of any one specific model.
Tools of this kind typically build their own local cache layer whose hit condition is “the request content is completely identical.” Its practical effect resembles the following illustrative logic:
key = hash(messages + tools + params)if key in local_cache:return local_cache[key] # only a byte-for-byte match hits
As soon as the context gains one more message, a single character in the system prompt changes, or the order of tool declarations shifts, the key changes and the entire cache is invalidated. What it optimizes is “repeated identical questions,” not “long-context reuse.”
2.2 Model-Specific Architecture
Another approach designs from the first line of code around the prefix caching mechanism of a particular class of model service. The semantics of prefix caching are: if the beginning of a request is byte-for-byte identical to a historical request, those tokens can reuse the computed result and are billed at only a lower proportion; newly added content afterward does not affect the reuse of the earlier portion.
This brings a key shift: the optimization goal changes from “whole-request deduplication” to maximizing the longest common prefix length. This is an entirely different engineering problem, and it explains why the two types of tools can show a several-fold cost difference under the same model and the same request volume.
It is worth stressing that this article does not point to any specific product; the two architectures above are abstractions of technical paths that commonly exist in the industry.
3. Three Engineering Constraints to Push the Prefix Hit Rate to the Limit
3.1 Strict Append: Context Only Grows, Never Changes
Conversation history must retain an “append-only” property: user messages, model replies, and tool call results are all preserved verbatim in the order they occur—no modification, no deletion, no reordering, and no summary substitution.
A counterexample is the common “context compression” strategy: when history grows long, earlier content is rewritten into a summary. This is necessary in a general-purpose architecture, but under prefix caching semantics it is a disaster—the summary happens at the head of the file, causing the entire prefix to mismatch from the very first byte.
[system prompt][tool declarations][examples][turn 1][turn 2]...[turn N] ← append-only, prefix stays stable[system prompt][summary(turn 1..turn k)][turn k+1]... ← head rewritten, whole prefix invalidated
3.2 Immutable Prefix: Locked at Session Start
Fixed content—the system prompt, tool and function declarations, few-shot examples, project conventions, and so on—should be determined once and frozen at session initialization, and remain unchanged for the entire session cycle. In engineering terms, several kinds of subtle “prefix pollution” must be avoided:
- Concatenating the current timestamp, a random ID, or a request sequence number into the prompt;
- Iterating over a directory and then outputting the tool list in a varying order;
- Dynamically inserting version numbers or paths based on the runtime environment.
These changes may look minor, but they sit at the very front of the request and break the longest common prefix itself.
3.3 Localize Volatile Drafts: Keep the Thinking Process Off the Wire
The model’s intermediate reasoning, temporary plans, candidate approaches, and debugging self-dialogue are highly volatile content. If mixed into the outbound request, they continually change the tail of the context and squeeze the prefix structure. A more sensible approach is to keep them in local state and write only conclusive content (final code, necessary tool results) into the conversation history.
4. A Verifiable Measurement Method
Do not trust any hit-rate number that has not been reproduced—including local cache hit rate and upstream cache hit rate; the two are not the same thing. It is advisable to build your own measurement:
# Pseudocode: count the "longest common prefix tokens" for each requestcommon = longest_common_prefix_tokens(prev_request, cur_request)ratio = common / cur_request.total_input_tokens# record separately: local dedup hit rate, upstream prefix hit rate, full-price token share
At the same time, bring “number of full-price input tokens” into monitoring, alerting, and logging as a first-class metric, aggregated by project and by session. Only then can you pinpoint which context rewrite ate away the savings.
5. Implementation Advice and Common Pitfalls
- Choose the architecture by scenario: when you need to mix multiple models or migrate across vendors, general-purpose adaptation is more suitable; with a single model, ultra-long context, and high-frequency tool calls, the gains from model-specific optimization are significant.
- Manage prompts like code: version them, review them, and forbid concatenating volatile fields at runtime.
- Keep tool declarations stable: fix the count and order; let newly added tools take effect at session boundaries.
- Watch out for “fake hits”: a local cache hit only saves local compute and produces no upstream billing discount.
- Attribute cost to the session: combine monitoring and logs to form a traceable chain of “hit rate → full-price tokens → cost,” and use a container platform for load-test reproduction when necessary.
6. Conclusion
The performance gap between AI coding tools is, in essence, not about the interface or multi-session capability, but about whether the way context is organized aligns with the billing and caching semantics. By understanding the “byte-level identical” constraint of prefix caching, using the three disciplines of strict append, immutable prefix, and localized volatile drafts to constrain context generation, and pairing them with a reproducible measurement system, you can keep costs within a reasonable range under massive token volumes. This methodology is independent of any specific tool and can be applied directly to model service integration on Baidu AI Cloud and to cost governance for self-built agents.
