Prefix Cache Hits: A Foundation for Reliable Agent Harnesses
Prefix caching can make a substantial difference to the cost of running agents with long contexts and repeated model calls. This article explains prefill, decode, and KV cache reuse, then outlines how stable prompts, deterministic tool definitions, append-only history, and monitoring help an agent harness maintain cache hits without depending on them for correctness.
1. Why an Agent Harness Should Prioritize Cache Hits
Agent frameworks have moved beyond demonstrations of whether they can call a model. The engineering challenge is now whether they can run reliably over time. Tool orchestration, context management, and error recovery all matter, but one frequently underestimated metric directly affects commercial viability: the cache hit rate.
The reason is straightforward: cost. When an agent works through multiple iterations in a project with a long context, each request carries system instructions, tool definitions, project information, and substantial conversation history. If this repeated content is processed as entirely new input every time, costs grow rapidly with the number of iterations. When prefix caching is available and hits, the repeated portion can typically cost only a small fraction of the uncached price.
For production systems making thousands of calls a day, that difference can determine whether the system is economically sustainable—not merely whether it is well optimized.
A mature agent harness—the software that organizes requests and manages the agent’s execution—should therefore establish reliable cache reuse before pursuing more sophisticated planning and reasoning. This is infrastructure work, not a showcase feature.
2. Prefill and Decode: Where the Cost Comes From
A model request can be divided broadly into two stages.
Prefill: The model processes the system instructions, tool definitions, project information, conversation history, and new user question, computing the intermediate states needed for attention. Longer inputs require more work, making this stage the main target for caching.
Decode: The model generates its response one token at a time based on the context it has processed. The work grows with output length; prefix caching does not eliminate the computation required to generate new output.
Within the attention mechanism of each Transformer layer, processed tokens produce corresponding keys and values. These stored intermediate states form the KV cache.
The KV cache is not the previous response text, nor is it a document that can be opened and read. It is more like the model’s computational notes after processing the input. If a later request begins with exactly the same input prefix, those states may be reused, avoiding prefill work for that portion.
3. Prefix Matching Starts at the First Token
The key concept behind cache hits is the prefix. An agent’s request is often organized like this:
[System instructions][Tool definitions][Project context][Conversation history][New message]<-------------------- Reusable shared prefix --------------------><-- New suffix -->
A prefix is a continuous sequence of matching tokens starting at the very beginning of the request. Several details are important:
- Matching is exact, not semantic. Similar meaning or shared keywords do not qualify. The token sequences must match.
- Matching starts at the first token. If the beginning differs, identical material later in the request cannot be reused as part of that shared prefix.
- Content after a change generally needs to be recomputed. If the previous request was
A+B+Cand the next isA+B+C+D, the unchangedA+B+Cmay be reused, leaving onlyDto process. If a tool definition changes partway throughB, however, the remaining portion ofB, along withCandD, must be computed along the new path.
Prompt caching is therefore a matter of matching from the start. A stable beginning produces a longer reusable prefix. An early change leaves more content to recompute. This behavior should guide the harness’s engineering decisions.
4. Common Engineering Problems That Break Cache Hits
Low cache hit rates are often caused not by the model or service, but by the harness introducing unnecessary changes to the prefix.
1. Injecting timestamps or random content into the system prompt
Adding a changing field such as Current time: 2024-XX-XX XX near the beginning can invalidate the reusable prefix from that point onward, even if only a few characters change.
XX
Place this information in the new content at the end of the request, or retrieve it through a tool when needed.
2. Reordering tools or changing serialization between requests
Differences in JSON field order, whitespace, or how default values are included can change the token sequence.
Keep tool ordering and serialization rules consistent. Update definitions only when the tools actually change.
3. Frequently rewriting conversation history
Summarizing, deduplicating, or rewriting earlier messages can change the middle of the request and invalidate reuse for everything that follows.
Prefer appending to history rather than rewriting it. When a full restructuring is necessary, perform it at a clearly defined session boundary.
4. Adding changing version numbers or hashes to the header
A header value that changes on every iteration effectively gives up cache reuse from that point. Review every seemingly harmless header field for stability.
5. Using different prompt templates across request paths
Multiple template variants for the same task make prefixes harder to align. Consolidate them into a consistent template and place variable content later in the request.
5. A Practical Checklist for Improving Cache Hits
The mechanics of prefix matching lead to several straightforward design principles.
Keep the beginning stable and the end dynamic. Put long-lived content—system instructions, tool definitions, and project information—first. Place new user messages, retrieval results, timestamps, and other changing content later.
Prefer append-only updates. Build each request by extending the previous conversation rather than rewriting its history. The later new content appears, the longer the reusable prefix can be.
Minimize changes to tool definitions. Update the definition section only when the tool set genuinely changes. Use deterministic serialization, including consistent key ordering, separators, and field order.
Keep the model and configuration consistent within a session. Changes to the model, its version, or settings that affect tokenization can invalidate reuse. Maintain consistency throughout a session.
Measure cache behavior. Record input token counts and the cached and uncached portions of each request. Treat the cache hit rate as a core operational metric. When it drops unexpectedly, first check for unintended changes near the beginning of the request.
Plan for cache misses. Misses are inevitable, including on the first request and after context restructuring. Treat caching as an optimization, not a requirement. The system must remain correct even when no cache is available.
6. An Illustrative Request Layout
The following example shows the intended organization of stable and changing content:
messages = [{"role": "system", "content": SYSTEM_PROMPT}, # Fixed{"role": "system", "content": TOOLS_SPEC}, # Update only when tools change{"role": "system", "content": PROJECT_CONTEXT}, # Stable within the session*conversation_history, # Grows through appending{"role": "user", "content": new_user_message}, # Changes each turn]
Combined with deterministic serialization and the absence of changing header fields, this layout maximizes the shared prefix and supports consistent cache reuse.
7. Conclusion
Cache hit rate is an often-overlooked indicator of agent harness quality. It does not make the model more intelligent, but it directly affects operating costs and scalability.
Treat the prefix as a first-class design concern: keep the beginning stable, append rather than rewrite, serialize deterministically, and monitor cache behavior continuously. These basic practices can deliver substantial cost reductions without elaborate optimization.
Establish dependable prefix cache reuse first, then build more complex agent capabilities on top of that foundation.
