A Good Agent Harness Starts With Cache Hits

    This article explains why prompt caching is one of the most overlooked yet highest-impact optimizations in an Agent Harness. It covers how KV Cache works, why exact prefix matching determines cache hits, five common causes of cache invalidation, and six practical techniques for improving hit rates—layering context, deterministic serialization, append-only history, session isolation, observability, and evaluation. It also illustrates the potential cost impact and provides a checklist for keeping your prefix cache-friendly.

    A Good Agent Harness Starts With Cache Hits

    When building agent systems that actually work, the industry keeps rediscovering the same formula: Agent ≈ Model + Harness. The model sets the upper bound on capability, while the Harness—the runtime framework that handles prompt organization, tool calls, context management, retries, and evaluation—determines whether that capability can be delivered reliably and affordably. The Harness is no longer just an engineering wrapper; it has become a decisive factor in whether an agent succeeds or fails.

    Among all the metrics a Harness can optimize, one is consistently underestimated yet delivers results fastest: cache hit rate. The reason is simple—it saves money. When more than 90% of input tokens in a session hit the cache, the shape of your bill changes by an order of magnitude. Conversely, if the prefix keeps shifting, even the best model will be dragged down by repeated computation in both latency and cost.

    1. What the Cache Actually Stores: Start With KV Cache

    Processing a single request in a large language model can be roughly split into two phases.

    Phase one: Prefill. The model reads the system prompt, tool definitions, project notes, conversation history, and the new message for this turn, in order, and computes the attention state for every token at every layer. This phase is compute-intensive and scales heavily with context length.

    Phase two: Decode. Once the context is understood, the model generates the response token by token. This phase is memory-bandwidth-intensive: each step does little computation but must repeatedly read the intermediate states of all previous tokens.

    The key lies in those “intermediate states.” In the attention mechanism of each Transformer layer, tokens that have already been read produce Keys and Values. Caching these computed artifacts is what we call the KV Cache.

    A common misconception is worth clearing up: the KV Cache is not the previous turn’s answer, nor is it a piece of text you can open and read. It is closer to the “computational notes” the model leaves behind after reading the material—unreadable, not directly editable, but reusable by subsequent requests. The benefit of prompt caching is essentially reusing those notes to skip repeated prefill computation.

    2. The Prefix: The Only Criterion for a Cache Hit

    To understand caching, you first have to understand the prefix.

    A request sent by an agent to the model is usually assembled in a fixed order:

    1. [System prompt][Tool definitions][Project notes][Conversation history][New message this turn]
    2. <---------- Reusable shared prefix ----------><-- New suffix -->

    The prefix is the segment of content that is byte-for-byte identical starting from the very first token. It is not keyword matching, and it is not “semantically close enough”: even if two blocks of text mean almost the same thing, a single differing token means everything from that point on usually has to be recomputed.

    Two typical scenarios:

    • The previous request was A + B + C, and this turn is A + B + C + D. As long as A+B+C is completely unchanged, the runtime may reuse up to C and only compute the new D.
    • If a tool definition is inserted or modified in the middle of B, then B, C, and D from the point of change onward usually all have to be recomputed.

    So prompt caching is first and foremost a game of “matching from the top down”: 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: Five Common Sources of Failure

    In engineering practice, cache invalidation is usually not the model’s fault—it is a problem with how the Harness organizes context. The five most common sources are below.

    1. Injecting timestamps or random IDs into the system prompt. Putting the current time, a request ID, or a random nonce at the front makes the prefix diverge within the first few dozen tokens of every request.
    2. Unstable tool definition ordering. If the tool list comes from hash traversal, concurrent assembly, or dynamic filtering, the shifting order causes mid-section changes.
    3. Placing dynamically retrieved content up front. Inserting each turn’s retrieved material after the system prompt but before the history is like burying a landmine in the middle of the shared prefix.
    4. Rewriting conversation history in place. For example, summarizing, correcting, or trimming earlier messages changes the prefix itself.
    5. No explicit cache markers or session isolation. Multiple tenants or sessions sharing unstable context repeatedly flush the cache.

    4. Six Practices to Make Your Hit Rate Solid

    1. Layer the context: stable layers first, volatile layers last

    The recommended order is: globally stable system constraints → tool definitions → project-level notes → session history → this turn’s input. Anything that “may change every time” (timestamps, retrieved snippets, environment info) should go last, ideally inside the current turn’s message.

    2. Normalize serialization

    For structured data such as tool definitions, directory trees, and dependency lists, use deterministic ordering (for example, lexicographic order by name) and never rely on traversal order. Example:

    1. def stable_tools(tools):
    2. return sorted(tools, key=lambda t: t["name"])

    3. Append first; never modify in place

    Treat conversation history as an append-only log. When a correction is needed, add a new message that clarifies it instead of going back to rewrite an old one. Summaries should also be appended as a new segment rather than replacing the original text.

    4. Session-level cache isolation and reuse boundaries

    Maintain a stable context baseline for each session and avoid mixing context across sessions. At the same time, keep long prefixes that can be safely shared (such as common specifications and shared tool sets) byte-for-byte identical, so they can be reused across sessions.

    5. Observability: treat hit rate as a first-class metric

    At minimum, record total request tokens, cached tokens, hit rate, and prefill latency. Without measurement there is no optimization. Hit rate should be part of the Harness’s routine monitoring and alerting, alongside error rate and latency.

    6. Guard quality with evaluation

    Cache optimization must not come at the expense of output quality. Build a fixed evaluation set and compare task success rate and output quality before and after enabling the caching strategy, making sure that “what you save is repeated computation, not necessary reasoning.”

    5. The Scale of the Benefit: A Simple Calculation

    Suppose a certain class of model prices cached input tokens and uncached input tokens differently, with a clear multiplier between them. If a long-running workload accumulates roughly 947 million cached input tokens, billing at the cached rate comes to only a single-digit dollar amount; if all of it were billed at the uncached rate, it could reach the low hundreds of dollars—a gap of tens of times.

    The point of this arithmetic is not the specific numbers but the conclusion: when input is dominated by a “long shared prefix plus a short new suffix,” a small improvement in hit rate gets amplified by the token volume into a significant cost difference. This amplification is especially pronounced for long sessions, repository-level code context, and batch offline jobs.

    6. Deployment Checklist

    • Does the system prompt still contain timestamps or random IDs?
    • Are tool definitions deterministically sorted?
    • Is retrieved content placed in the middle of the prefix?
    • Is history rewritten in place or replaced by summaries?
    • Is there a monitoring dashboard for hit rate and prefill latency?
    • Is there a fixed evaluation set verifying that the optimization did not hurt quality?

    Conclusion

    The maturity of a Harness often does not begin with more complex orchestration, but with the most basic rule: don’t dirty the prefix. Layer the context, make serialization deterministic, turn history into an append-only log, and bring hit rate into monitoring. Once these four things are done, cache hits rise naturally and cost and latency drop together. Get cache hits right first, then talk about a smarter Agent.