A Good Agent Harness Starts with Cache Hits
This article explains why prompt cache hit rate is the first engineering benchmark for a mature Agent Harness. It covers how prefill and decode shape cost, why the common prefix is the only basis for cache reuse, the common failure modes that break hit rates, and practical fixes such as layered context design, stable serialization, cache scope isolation, and observability metrics. Readers will learn how to turn cache hit rate into a measurable, optimizable engineering problem and reduce both cost and latency.
A Good Agent Harness Starts with Cache Hits
In Agent engineering, the model sets the upper limit of capability, but the surrounding execution framework that hosts the model—commonly called the Harness—determines whether that capability can be released reliably and at low cost. A mature Harness has to handle a series of engineering problems: context organization, tool calls, session state, failure retries, and observability. The first hurdle to clear, and the one most easily underestimated, is the cache hit.
To explain the value to a manager in one sentence: a higher cache hit rate means lower call cost and shorter response latency. This article starts from the underlying mechanism and breaks cache hits into an engineering problem that is understandable, measurable, and optimizable.
1. Prefill and Decode: Where the Cost Actually Goes
Processing a single request in a large model can be roughly divided into two phases.
The first phase is prefill. The model reads in the system prompt, tool definitions, project instructions, conversation history, and the new user input for this turn, and computes the intermediate state of each token across the attention layers. This phase is highly dependent on input length: the longer the input, the larger the computation.
The second phase is decode. After understanding the context, the model generates the answer token by token. This phase depends on output length, advances one token at a time, and cannot be completed in a single pass.
In the attention computation of each Transformer layer, the tokens that have been read form corresponding Keys and Values. These already-computed intermediate states are saved as the KV Cache. It is not the model’s previous answer, nor a piece of text you can open and read; it is closer to the “computation notes” the model leaves behind after reading the material. If a later request faces the same first half of the material, it can reuse those notes directly and skip the repeated computation.
This point is critical: cache optimization does not optimize the “answer”; it optimizes the cost of “reading the same material over and over.”
2. The Prefix: The Only Basis for Judging a Cache Hit
To discuss hits, we first have to define the prefix.
A request sent by an Agent to the model is usually assembled in this order:
[System prompt][Tool definitions][Project instructions][Conversation history][New message this turn]<---------- Reusable common prefix ----------><-- New suffix -->
The prefix is a continuous stretch of content that is completely identical starting from the first token. It is not keyword matching, nor “semantically close enough.” The criterion is very plain: if two requests are identical from the beginning through the 50,000th token, those 50,000 tokens form a common prefix; once the 50,001st token differs, the content after it usually has to be recomputed along a new path.
For example:
Previous turn: A + B + CThis turn: A + B + C + D
As long as A, B, and C stay unchanged, the server can reuse the state after C and compute only the new D. Conversely, if a tool definition in the middle of B is modified, then the rest of B from the change point, C, and D usually all have to be recomputed.
This yields a principle that runs through the whole article: prompt caching is first a game of “checking answers from the start.” The more stable the beginning, the longer the reusable prefix; the earlier a change appears, the more content has to be recomputed afterward.
3. Why Hit Rates Collapse: Common Failure Modes
In engineering practice, a drop in hit rate is often not the model’s problem, but a problem with how the Harness assembles context.
- Timestamps and random identifiers placed first. Inserting the current time or a random request ID at the start of the system prompt changes the very first token and invalidates the entire prefix.
- Unstable tool definition order. If the tool list comes from hash traversal, set iteration, or concurrent return order, the order differs each time, which is equivalent to rewriting the prefix.
- Dynamic content inserted too early. Putting retrieval results, user profiles, or environment information before the project instructions mixes volatile content into the common prefix.
- History rewriting and summary write-back. Compressing early conversation into a summary and replacing the original text is an in-place modification of the prefix and inevitably triggers large-scale recomputation.
- Multiple sessions sharing the same “mutable system prompt.” Sharing a prefix across sessions can improve hits, but if session-private state is mixed in, it both lowers the hit rate and causes information to bleed across sessions.
- Unstable serialization. Inconsistent floating-point formats, whitespace, newline styles, or JSON key order across different execution paths cause “looks the same, actually different” false invalidations.
4. Practical Optimization Methods
4.1 Layer the Context: Stable Layers First, Volatile Layers Last
Arrange request content in layers by how often it changes, from stable to volatile:
Layer 1: Global rules, output specs, safety constraints (almost never change)Layer 2: Tool and interface definitions (low-frequency changes)Layer 3: Project instructions and domain knowledge (medium-frequency changes)Layer 4: Long-term memory and conversation history (appended per turn)Layer 5: This turn's retrieval results, environment state, new user message (high-frequency changes)
The core technique is “append, don’t rewrite”: put new information as far back as possible and leave historical content untouched.
4.2 Move Volatile Information to the Back or Outside
Content like time, random numbers, and request identifiers should be placed in the last layer if the business truly needs it, or injected via a variable near the end. Going further, you can move volatile information out of the prompt entirely and carry it in tool call results, keeping the prefix clean.
4.3 Stable Serialization
Apply a unified serialization rule to tool definitions and structured configuration: fixed key order, fixed indentation, fixed numeric precision, and no dependence on traversal order. You can add a “context snapshot test” to CI that generates the request body multiple times for the same input and compares hashes to ensure byte-level consistency.
4.4 Isolate Session and Cache Scope
Private content from different tenants or projects should not be mixed into the common prefix. A sound approach is to keep the common prefix globally consistent and let private content appear as appended segments, which both improves hits and avoids privilege-escalation and information-bleed risks.
4.5 Observability: Treat Hit Rate as a First-Class Metric
Optimization needs measurement to support it. Collect at least the following metrics:
- Prefix token ratio: common prefix length / total input length
- Cache hit rate: hit input tokens / total input tokens
- Invalidation point distribution: histogram of the token position where the first difference appears
- Cost per request and P95 latency
Illustrative measurement logic:
def prefix_len(a: str, b: str) -> int:n = min(len(a), len(b))i = 0while i < n and a[i] == b[i]:i += 1return i# Record the common prefix length each turn to locate problems where the "change point" appears too early
When the invalidation point histogram clusters at very early positions, the problem almost certainly lies in the system prompt or tool definition layer.
5. An Intuition for the High-ROI Payoff
The value of cache hits can be understood with a simplified arithmetic example: suppose more than ninety percent of the accumulated input in a turn is a hit, then that portion is usually billed at a price clearly lower than missed input, and the overall cost can differ by an order of magnitude. For long-context, multi-turn iterative Agent scenarios, input tokens are often the main cost, and raising the hit rate from ninety percent to nearly full saves not a small change but the main expense. This is also why “getting cache hits right first” is the first touchstone of Harness maturity.
6. Deployment Checklist
- Are there residual first-token killers like timestamps or random IDs in the system prompt?
- Are tool definitions in the same order every time and serialized stably?
- Are retrieval results and environment information moved to the back?
- Is conversation history only appended, with no summary write-back?
- Are the common prefix and private content isolated?
- Have hit rate and invalidation point distribution metrics been collected?
- Has a byte-level context consistency check been added to the release process?
Conclusion
Cache hits are not black magic; they are an engineering problem about “prefix stability.” Layer the context, move volatile content to the back, fix serialization, and measure the hit rate, and the Harness takes the key step from “it runs” to “it runs cheaply.” Models can be swapped out, but a Harness that respects the rules of the prefix will keep accumulating returns over the long term.
