Protecting the Prefix Cache: Key Design Rules for Runtime Request Assembly
This article explains why prefix cache hits depend not only on pricing but on deterministic runtime request assembly. It covers what prefix caching actually reuses, why agent loops often break stable prefixes, six engineering constraints for cache-friendly request construction, observability metrics, a pseudocode pattern, and a simple cost model showing why a 99% hit rate matters for both cost and runtime stability.
In public tests, prefix cache hit rates can reach 99%. In some publicly available input pricing examples for model services, the unit price for a cache hit versus a cache miss differs by about 30x. Put those two numbers together, and the first reaction is usually cost: if the vast majority of input tokens can reuse an old prefix, the bill should drop noticeably. But for an agent runtime, there is a more important question: on every step, can the request assembly chain preserve the unchanged parts exactly as they were? Cache hit rate is not just a financial metric. It is also an echo of runtime stability.
1. What Prefix Caching Reuses: Not the Previous Answer, but the KV State of a Contiguous Token Prefix
Caches in business systems usually have explicit keys. An in-process cache retrieves data by object identifier, a distributed cache retrieves results by business key, and a content delivery network retrieves static resources by URL. Their common goal is to avoid doing again what has already been computed, fetched, or transmitted.
In a large model request, the cached object is different: the model provider is not reusing the previous natural-language answer. It is reusing the KV state left after the model processes an input prefix.
This means a cache hit is not determined by semantic similarity. It is determined by a contiguous token prefix starting from the beginning of the request. As long as the model, tokenization method, system prompt, tool definitions, historical messages, and their token order remain consistent, the next request has a chance to continue computation from the old prefix. Once a position in the prefix changes, everything after that position may lose the opportunity for reuse. Think of it as a log that can only be appended at the head: appending at the tail is safest, while rewriting the head or middle is most expensive.
This is the biggest difference between prompt prefix caching and ordinary business caching. Ordinary caches can have explicitly designed keys, but prefix caching is implicitly determined by request text and serialization results. If a tool changes position, a current timestamp is inserted before the system prompt, or old messages are re-serialized, two requests that look “about the same” to a human may no longer be the same prefix from the cache’s perspective.
2. Why Agent Pipelines Are Most Prone to “Looks Unchanged, Actually Changed”
A typical agent loop works like this: read system rules and tool descriptions, call search or another capability, return the result to the model, and decide the next step. In the next request, a large earlier portion may be unchanged: the model, system prompt, tool definitions, and previous conversation are still there, with only one tool call and result added at the end. If that prefix is preserved exactly, the model provider has a chance to reuse the already-computed KV state directly.
The problem is that runtimes often perform “request cleanup” operations that break prefix stability:
- Reordering tool definitions: If the tool list is emitted by hash, concurrent return order, or runtime registration order, the order may differ on every turn. Tool definitions usually sit near the front of the request, so once their order changes, the token sequence of everything after them may change.
- Prepending dynamic information: If dynamic fields such as current time, request ID, or user state are inserted at the start of the system prompt, the prefix head is rewritten on every turn. The correct approach is to place them later or in separate metadata so they do not contaminate the stable segment.
- Rewriting old messages: To trim context, correct roles, or normalize formats, the runtime may go back and rewrite historical messages. Even if the semantics are the same, the token sequence may change, and the cache cannot treat “semantically equivalent” as “identical prefix.”
- Replacing early messages through context compression: Compression itself is necessary, but if every turn re-summarizes and replaces the beginning of history, the stable prefix is continuously broken. A safer approach is layered compression: keep the stable segment immutable, and apply compression only to the tail or to a separate summary area.
- Non-deterministic serialization: When the same internal object is converted into an external request format, differences in field order, empty-field handling, whitespace, or tool-call format from one turn to the next can also cause prefix drift.
- Inconsistent boundary adaptation: Conversion from the runtime’s internal representation to the model provider’s request format must be deterministic. Different boundaries may handle roles, tool calls, and empty fields differently. If the adaptation layer re-normalizes on every turn, it may produce unstable token sequences.
Individually, these issues may look minor. But in a multi-step agent loop, they accumulate. A falling cache hit rate is only the result; the root cause is often some non-deterministic link in the request assembly chain.
3. Making the Request Assembly Chain Cache-Friendly: Six Engineering Constraints
1. The Stable Prefix Must Be Immutable
The system prompt, project rules, tool schema descriptions, fixed safety policies, and similar content should belong to the stable prefix and remain unchanged at the byte or token level for the duration of a session. The stable segment is not “best effort unchanged”; it is “immutable by default.” Any information that needs to change dynamically should not be inserted into the stable segment.
2. Tool Definitions Need Deterministic Ordering
Tool definitions should use a stable sorting rule, such as sorting by tool name, namespace, and version number, rather than relying on runtime registration order. Optional fields, default values, and descriptions in tool schemas should also be normalized. Tool definitions often occupy a long prefix, and the benefit of stable ordering far outweighs the cost of sorting once.
3. Put Dynamic Information at the End
Dynamic information such as current time, request tracing identifiers, and temporary switches should be placed at the end of the request or in a separate metadata area. If the business requires the model to see the time, it can be appended as a trailing system message or user message instead of rewriting the head system prompt.
4. Append Historical Messages Instead of Rewriting Them
Conversation history should use an append-only log. New events, tool calls, and tool results are appended at the end in order, without going back to modify old messages. If roles or formats must be corrected, they should be finalized once at write time as much as possible, avoiding re-serialization of history on every turn.
5. Use Layered Compression
Context compression should not mean “rewrite the prefix on every turn.” A layered strategy can be used: keep the stable prefix unchanged; append recent messages as-is; compress older history into a separate summary block placed after the stable segment and before recent messages; and keep the summary block as stable as possible once generated. This controls context length while reducing damage to the already-cached prefix.
6. Serialization and Boundary Conversion Must Be Deterministic
Conversion from the internal request to the external request should be deterministic: fixed field order, fixed empty-field handling, fixed tool-call format, and fixed whitespace handling. After assembly, a prefix fingerprint can be computed to detect unexpected changes. The boundary adaptation layer should not introduce new normalization differences on every turn.
4. Observability: Treat Hit Rate as a Runtime Health Metric
For cache hit rate to become an engineering metric, its definition must first be clear. Is it measured by request hit rate, or by the proportion of reusable tokens among input tokens? Different denominators give different meanings to 99%. At minimum, record the following fields: stable prefix fingerprint, input tokens per step, hit tokens, miss tokens, invalidation reason category, tool definition hash, history message hash, and serialization version.
Invalidation reasons can be broadly categorized as: tool ordering change, dynamic field prepending, history rewriting, compression replacement, serialization change, boundary adaptation change, and model or tokenization change. Once hit rate is correlated with these causes, the cache metric is no longer just a billing number. It becomes a regression-test signal for the request assembly chain. In continuous integration, recorded requests can be used to compare prefix fingerprints between two runtime versions. If the stable-segment fingerprint changes unexpectedly, the release should be blocked or an alert should be raised.
5. Illustrative Implementation: Separate the Stable Prefix from the Dynamic Suffix
The pseudocode below expresses the core principles of request assembly: the stable segment is read-only, tool definitions are sorted deterministically, dynamic information is placed at the end, and history is append-only.
function build_request(session, new_event):stable = session.stable_prefix// stable contains: system prompt, fixed rules, tool schema descriptionstools = canonical_sort(stable.tool_schemas)canonical_tools = canonical_json(tools) // fixed field order and empty-value handlinghistory = session.append_only_historytail = history + [new_event]dynamic = {now: current_time(),trace_id: new_trace_id()} // placed at the tail or in a separate metadata area, not inserted into stableprefix_fingerprint = hash(stable.system_prompt +canonical_tools +serialize(history))return {prefix: stable.system_prompt,tools: canonical_tools,messages: tail,metadata: dynamic,fingerprint: prefix_fingerprint}
The point of this pseudocode is not the exact syntax but the order: fix the stable segment first, then normalize tool definitions, append history only, and place dynamic information last. Only if this order stays consistent across every request turn does the prefix cache have a stable basis for reuse.
6. Cost Model and the Real Meaning of 99%
Assume the input unit price ratio between cache misses and cache hits is 30:1 and the hit rate is 99%. A simple estimate follows. Let the miss unit price be 3 and the hit unit price be 0.1. With hit rate h, the input cost ratio relative to all misses is:
cost_ratio = (h * 0.1 + (1 - h) * 3) / 3h = 0.99cost_ratio = (0.99 * 0.1 + 0.01 * 3) / 3= (0.099 + 0.03) / 3= 0.043
In other words, under this assumption, input cost is about 4.3% of the all-miss cost, saving more than 95%. But the real value of 99% is not only cost savings: it indicates that the runtime has most likely preserved the request prefix across a multi-step loop. Conversely, if the hit rate suddenly drops, the first thing to check is not the pricing rule but whether the request assembly chain has introduced new uncertainty.
Conclusion
Prefix cache design can be divided into three layers. The first is prompt layering: keep the stable prefix as unchanged as possible and append tool results and new messages at the end. The second is cost awareness: understand the unit price difference between cache hits and misses. The third is the runtime request assembly chain: ensure that the system prompt, tool ordering, conversation history, context compression, runtime state, and boundary conversion do not break the prefix. The third layer is the easiest to overlook, yet it determines whether the first two layers can actually work. Protecting the request prefix is essentially protecting runtime determinism; cache hit rate is simply one of the most visible measures of that.
