AI Agent Prefix Caching: Optimize Cache Hits Before Switching Models
Prefix cache efficiency depends as much on the agent harness as on the model. Learn how stable prompt assembly, versioned tool definitions, append-only history, and cache-hit monitoring can reduce repeated prefill computation, input costs, and time to first token.
Once you treat an AI agent harness as a replaceable runtime, the biggest difference often comes not from switching models, but from avoiding repeated computation over the same context. For anyone managing the budget, cache efficiency has a straightforward benefit: tokens already processed during prefill may be reused instead of being charged as entirely new input. Cached input is typically priced substantially below uncached input, often by an order of magnitude. The longer the context and the more turns a task requires, the more significant that difference becomes.
What a Request Actually Computes
A completion has roughly two stages. During prefill, the model processes the system instructions, tool contracts, project constraints, conversation history, and new content, computing the intermediate attention states for each token. During decoding, it uses those states to generate a response one token at a time. With long prompts and short responses, much of the latency and cost comes from prefill rather than answer generation.
Each Transformer layer produces keys and values for the tokens it has processed. These computed states, which subsequent attention queries can use, form the KV cache. This is not the visible answer from the previous turn, nor is it text you can open and inspect. A more useful analogy is a set of computational notes left behind after the model reads the material. Whether those notes can be reused depends on whether the new request begins with exactly the same token sequence.
A Prefix Is Not “Similar Meaning”
Requests are typically assembled in a fixed order: system prompt, tool definitions, project instructions, conversation history, and finally the current message. A prefix is the uninterrupted matching sequence starting at the first token. If two requests share exactly the same first 50,000 tokens, those tokens can form a common prefix. Once token 50,001 differs, the content that follows generally needs to be recomputed along the new path.
Cache hits therefore depend on matching from the beginning, not on semantic similarity. Suppose the previous request was A+B+C and the next is A+B+C+D. If the byte-level content of A+B+C remains unchanged, the server has an opportunity to reuse the computation through C and perform prefill only for the new D. If a tool description changes midway through B, the remainder of B, followed by C and D, generally needs to be recomputed.
The more stable the beginning, the longer the reusable prefix. The earlier a change occurs, the more downstream computation it invalidates.
Why the Agent Harness Determines Cache Hit Rates
The model computes over a given token sequence. The harness determines how that sequence is assembled, when it changes, and where those changes appear. The same model can have cache hit rates that differ by orders of magnitude under different orchestration approaches, because engineering details—not model capabilities—often break the prefix.
Common sources of early prefix breaks include:
- Adding the current time, random request IDs, or unstable environment summaries to the system prompt.
- Changing tool order based on registration timing, or updating tool descriptions dynamically.
- Reordering conversation history, applying inconsistent truncation, or inserting summaries in the middle rather than appending them.
- Using nondeterministic serialization, with varying key order, whitespace, numeric formatting, or escaping.
- Placing turn-specific retrieval results or file diffs in the system prompt instead of the suffix.
These changes may look minor, but for caching purposes they can invalidate everything after the point of divergence.
Separate Stable Content from Changing Content
The practical assembly rule is simple: append rather than rewrite an already-sent prefix, and place potentially changing information as late as possible.
Version the system prompt and keep its bytes stable. Put dynamic facts the model needs in the current user message or a separate suffix block rather than writing them back into the system section.
Sort tool definitions by stable identifiers and serialize their fields deterministically. Switch tool contracts as complete, immutable versions instead of quietly changing a few words during a long conversation.
Keep conversation history append-only. When compression or summarization becomes necessary, explicitly accept a prefix break and, where possible, place the summary after the change boundary. Avoid rewriting the earlier portion on every turn.
Large project descriptions and specification documents that rarely change should sit after the tool definitions and before the conversation history, allowing multiple turns to share the same long prefix.
A representative layout is:
[Stable system prompt vN][Tool contracts sorted by name][Stable project instructions][Append-only conversation history][Current retrieval results, diffs, and user question] ← Intended change boundary
Moving the change boundary to the final block gives the earlier computational states a chance to be reused across turns.
How to Verify That Optimization Works
Do not rely on the impression that requests “feel faster.” At a minimum, record:
- The proportion of cached versus uncached input tokens.
- The approximate section where the prefix diverges.
- Time to first token.
- Input costs calculated using the provider’s published pricing.
When the cache hit rate suddenly drops, first compare the prefixes of adjacent requests rather than suspecting the model. Compare exact token sequences or consistently normalized byte representations; semantic similarity is irrelevant to a cache hit.
Caches also have limits. Servers impose capacity, retention, and length constraints. Very long prefixes, extended idle periods, or provider restarts may cause misses. The harness should keep reusable content stable within those constraints, not assume a permanent 100% hit rate.
Privacy-sensitive context should not be retained indefinitely just to improve cache hits. Design retention policies alongside compliance requirements.
Implementation Order
Start by fixing prompt assembly order and serialization. Next, remove timestamps and random values from the system section. Then make tool contracts immutable and versioned. Only after that should you refine summarization and truncation.
Validate every step using cached-token counts and the location of prefix breaks. The benefits appear in both the bill and interaction latency: avoiding repeated prefill work often means a faster first token.
For long-running AI agents, improving prefix cache hits before switching models is often the more cost-effective move.
