LLM Prompt Caching and Prefix Stability: Engineering for a 99% Cache Hit Rate

    This article explains why a 99% prompt cache hit rate is a runtime stability metric rather than a cost metric, and why prefix stability is a first-class engineering goal for AI coding harnesses. It covers how LLM caching reuses the KV state of an input prefix instead of prior results, why agent loops are highly sensitive to prefix changes, and how request assembly chains introduce non-determinism. It then presents append-only design constraints, guidance on context compaction and session handling, a method for using hit rate as a runtime health check with metrics and alerts, and a practical implementation checklist.

    1. Two Numbers Side by Side: The Real Problem Is Not the Bill

    In the public pricing of some high-performance inference services, peak-hour input billing shows a clear two-tier structure: cached tokens cost about CNY 0.10 per million tokens, while uncached tokens cost about CNY 3 per million tokens. The gap is roughly 30x. Meanwhile, a set of public benchmarks for AI coding scenarios shows prompt cache hit rates approaching 99%.

    Put these two numbers together and the first reaction is usually “how much cost was saved.” That conclusion is correct, but it hides more valuable information: 99% is not fundamentally a financial metric; it is a runtime stability metric. The hit rate is high not because billing was optimized well, but because unchanged content was preserved as-is when each request round was assembled.

    The reverse also holds: if the hit rate suddenly drops to 60% or 40%, it is almost never because “the model got more expensive,” but because some part of the runtime is quietly rewriting the context. So the core argument of this article is that prefix stability is a first-class engineering goal for AI coding harnesses, and the cache hit rate is merely its externally observable signal.

    2. The Cached Object Has Changed: From “the Previous Answer” to the KV State of the Input Prefix

    Traditional business caches reuse results: a query result, a rendered HTML fragment, a serialized object. Their invalidation is controlled by explicitly designed keys, with clear semantics and clear responsibility boundaries.

    The cached object in large model inference is completely different. On the provider side, what is reused is the intermediate state left after the model processes an input prefix, namely the Key/Value tensors corresponding to historical tokens in the attention mechanism. The cost of computing these states depends on sequence length, number of layers, and number of attention heads, and is the main overhead of the initial prefill stage. If the beginning of the next request is exactly the same as the previous one, this prefill can be skipped and computation can continue directly from the old state.

    This leads to three properties that differ from traditional caching:

    • The matching criterion is the longest common prefix starting from token 0; there is no key at the business-semantic level.
    • Invalidation is position-sensitive: a change in one early token disqualifies all subsequent content from reuse.
    • The reuse window is constrained by server-side policies (lifecycle, capacity eviction, visibility delays, and so on). Clients cannot fully control it and can only increase the probability that content is reusable.

    3. Why AI Coding Scenarios Are Most Sensitive to Prefixes

    A typical agent loop looks roughly like this: load project rules and the system prompt → provide the tool list → the model decides to call retrieval → the tool returns results → the results are written back into the conversation → the next round begins.

    From the second step onward, most tokens in each request round are actually repeated: the system prompt, tool definitions, and conversation history are all still there, with only a tool call and its result appended at the tail. This is the ideal shape for prefix reuse: a huge, static head and a small-growing tail.

    The problem is that the runtime often breaks this static shape out of “engineering goodwill”:

    • The tool list is reordered by availability, popularity, or hash order.
    • The system prompt injects the current time, current branch, or current file path.
    • Conversation history is re-serialized, with changes in whitespace and escaping.
    • After context compaction, earlier messages are rewritten instead of only appending a summary.
    • Multi-tenancy or canary switching changes the model version or parameter template without anyone noticing.

    Comparing two requests by eye makes them look “basically the same,” but the prefix matching algorithm sees a divergence starting at some position. Cost therefore doubles silently.

    4. Breaking Down the Request Assembly Chain

    To keep the prefix stable, you must first see how requests are assembled. A typical assembly chain can be abstracted as:

    1. Session state
    2. → System prompt template (with variable injection)
    3. → Tool/function schema serialization
    4. → History messages (including tool calls and results)
    5. → Context compaction/truncation policy
    6. → Runtime parameters (sampling, template version)
    7. → Provider boundary (model identifier, API protocol)

    Every link in the chain can introduce non-determinism. The most effective engineering approach is to turn this chain into an append-only structure:

    1. # Bad example: rebuild every round, prefix drifts at any time
    2. def build_messages_bad(ctx, now):
    3. tools = sorted(ctx.tools, key=lambda t: hash(t.name))
    4. system = f"Current time {now}\n" + ctx.rules
    5. return [system] + tools + ctx.history
    6. # Good example: freeze the stable segment, put volatile content last
    7. def build_messages_good(ctx, now):
    8. head = ctx.stable_head # rules + tool schemas, generated once at build time and cached
    9. tail = ctx.history + ctx.new_events
    10. return head + tail + [f"[runtime] {now}"] # put volatile info at the tail

    The key constraints can be summarized in four points:

    1. Freeze the order: the ordering of tools and rules is fixed for the session lifecycle, generated by deterministic rules such as lexicographic order by name.
    2. Put volatile content last: time, paths, branches, random identifiers, and the like all go at the end of the prefix or the tail of messages.
    3. Append only, never revise: once a history message is written, it is not rewritten; corrections are expressed by adding new messages.
    4. Unique serialization: the same message allows only one serialization result, avoiding jitter in whitespace, escaping, and field order.

    5. Context Compaction and Sessions Are the Two Easiest Places to Fail

    Context compaction is a hit-rate killer. If the compaction policy rewrites early messages as the window limit approaches, the prefix becomes invalid as a whole starting from the compaction point. A more stable approach is layering: freeze a stable summary as the fixed head of the session, apply compaction only to the tail sliding window, and ensure the summary never changes once generated; when necessary, start a new session, trading “one cold start” for high reuse over subsequent rounds.

    At the session level, distinguish a “logical session” from a “reusable prefix.” If a model switch, tool-set change, or template upgrade occurs within the same session, treat it proactively as the start of a new prefix rather than letting the runtime quietly splice things together. Modeling these changes explicitly as version numbers is the basis for later attribution.

    6. Using the Hit Rate as a Runtime Health Check in Reverse

    The most valuable use of the hit rate is as input for regression tests and production alerts. It is recommended to compute a local fingerprint on the client based on “the hash of the first N tokens of the request,” compare it with the cache usage returned by the server, and form three metrics:

    • Prefix fingerprint change rate: whether the head fingerprints of two adjacent request rounds match.
    • Reuse coverage: cached tokens / reusable tokens.
    • Mismatch localization: the token offset where divergence first appears and the component it belongs to (tool segment / system segment / history segment).

    Illustrative monitoring structure:

    1. metric: prefix_stability{component="tools|system|history"}
    2. = 1 - changed_head_tokens / total_head_tokens
    3. alert: average of component="system" within 5 minutes < 0.95

    Once an alert points to the system segment, it is usually timestamp injection or template drift; if it points to the tools segment, it is most likely non-deterministic ordering; if it points to the history segment, check compaction and re-serialization. In this way, a billing anomaly becomes a locatable engineering defect.

    7. Implementation Checklist

    • Build-time design: treat the system prompt and tool schemas as immutable build artifacts, generated once and reused throughout.
    • Deterministic ordering: explicitly sort before traversing any collection; forbid hash order and dictionary traversal order from affecting output.
    • Variable injection governance: classify prompt variables, putting stable variables in the head and volatile variables in the tail.
    • Message immutability: history messages are read-only after being written; corrections are expressed by appending.
    • Layered compaction: fixed summary head plus sliding tail window, avoiding rewriting early content.
    • Explicit versioning: model, template, and tool-set changes are all recorded as new prefix versions.
    • Observability loop: collect prefix fingerprints and reuse coverage, and incorporate them into CI regression and production alerts.
    • Cost attribution: break down savings by component to evaluate the actual benefit of context governance.

    8. Conclusion

    The 30x unit-price gap sets the ceiling for cost optimization, while the 99% hit rate determines how close we are to that ceiling. What lies between them is not a billing strategy, but whether the runtime has the ability to “keep the unchanged parts as-is.” Context layering addresses “how things should be ordered,” the cost perspective addresses “whether it is worth doing,” and the harness layer addresses “whether it is actually done every round.” Only by making prefix stability a measurable, alertable, regression-testable engineering constraint can the cache hit rate turn from a nice benchmark number into a long-term stable system property.