Building a Better Agent Harness: Start with Solid Cache Hits

    This article explains why prompt caching, not model selection, is the first lever for controlling Agent costs. It covers how prefill and decode work, why the reusable prefix is matched byte by byte, and four Harness practices that protect cache hits: stabilizing the prefix, append-only conversation management, fixed tool sets and ordering, and observability. It also shows how to model cost across cached and uncached tokens, lists common mistakes, and provides a practical implementation checklist.

    1. It Starts with a Bill

    One easily overlooked fact in Agent engineering is that every model request re-reads the system prompt, tool definitions, project notes, and conversation history. This content is often highly repetitive across consecutive turns, yet it may trigger a full attention computation each time. When call volume scales to hundreds of millions of tokens, the repeated computation adds latency and a cost gap that can be measured.

    There has been public discussion in the industry about an AI coding tool that reached a cumulative cache hit rate above 99.9% during continuous operation. Billing for the cached portion was nearly fifty times lower than for a complete miss. The number matters not because it comes from a specific product, but because it reveals a general rule: cost optimization for Agents happens first at the cache hit layer, not at the model selection layer.

    If you roughly split an Agent into “model + harness,” the model sets the ceiling on capability, while the harness determines how efficiently that capability is invoked. The same model can cost an order of magnitude more or less depending on how requests are organized.

    2. What Happens Inside a Request

    Understanding cache hits requires understanding the two phases of inference.

    Prefill: The model reads all input tokens in parallel, including system instructions, tool schemas, project context, prior messages, and the current question, and computes the attention state for each token at every layer. This phase is compute-intensive and highly sensitive to whether the input has changed.

    Decode: The model generates output token by token based on the established context. This phase is sequential and mainly constrained by memory bandwidth.

    In each attention layer of a Transformer, tokens that have already been read produce corresponding Key and Value vectors. Saving and reusing these intermediate states is what we call the KV Cache.

    It is worth stressing that the KV Cache is not the text of the previous answer, nor is it anything you can open and read. It is closer to the “computational notes” the model leaves behind after reading the material. Once those notes are invalidated, the material has to be read again.

    3. The Prefix: The Only Yardstick for a Hit

    Agent requests are usually assembled in this order:

    1. [system prompt][tool definitions][project notes][conversation history][new message this turn]
    2. <---------- reusable shared prefix ----------><-- new suffix -->

    The prefix is a contiguous stretch of content that is completely identical starting from the first token. It is not keyword matching, and it is not “semantically similar”: only when two requests are byte-for-byte identical from the beginning through the Nth token do those N tokens form a shared prefix. Once the (N+1)th token differs, everything after it generally has to be recomputed along a new path.

    For example:

    1. Turn 1: A + B + C
    2. Turn 2: A + B + C + D → reuse A, B, C; compute only D
    3. If one tool definition in B changes:
    4. Turn 2: A + B' + C + D → recompute everything from B' onward

    The conclusion is straightforward: the earlier a change appears, the shorter the reusable prefix and the larger the recomputation. This is why “getting cache hits right” is essentially a game of matching from the beginning of the answer.

    4. Four Levers at the Harness Level

    4.1 Stabilize the Prefix

    Keep the system prompt, tool definitions, and project notes at the very front of the request and keep them byte-for-byte stable. Avoid splicing timestamps, random IDs, session summaries, or dynamic counters into the prefix.

    4.2 Append-Only Conversation Management

    Append to the tail of the conversation history; do not rewrite the middle. When earlier content needs correcting, prefer appending a correction at the end rather than going back to edit history.

    4.3 Fixed Tool Set and Ordering

    Adding or removing tools, renaming them, changing descriptions, or changing parameter schemas will all break the prefix. Version the tool set and keep the same order within a session.

    4.4 Observability

    Cache hits are not magic; they should be measured. Log total input tokens, cached tokens, hit rate, and new suffix length for each turn, build a trend dashboard, and combine it with logging services and monitoring alerts to detect anomalies.

    Illustrative calculation logic:

    1. hit_rate = cached_input_tokens / total_input_tokens
    2. # A sudden drop in hit rate usually means the prefix was polluted; check dynamic fields and tool changes first

    5. How to Estimate Cost Correctly

    Take one public discussion as an example: about 947 million cached input tokens cost roughly $2.65 at the cached rate; charged entirely at the uncached rate, it would be about $132.62. This comparison is a reminder that cost evaluation must separate the cached and uncached curves rather than looking only at total tokens.

    In engineering, you can build a simple model:

    1. cost per request ≈ cached tokens × cached price + uncached tokens × uncached price + output tokens × output price

    The optimization goal is therefore clear: without changing task outcomes, make “uncached tokens” contain as little as possible beyond what is genuinely new this turn.

    6. Common Mistakes

    • Putting dynamic content first: Placing the time, username, or a random request ID at the front invalidates the entire prefix.
    • Chasing semantic reuse: Caching matches on the token prefix; semantically similar but literally different text will not hit.
    • Rewriting history frequently: A mid-stream edit means recomputing everything from the edit point onward.
    • Looking only at unit price, not hit rate: There is limited room to negotiate unit price, while improving hit rate often yields more.

    7. Implementation Checklist

    1. Fix the order: system prompt, tool definitions, project notes, history, new message.
    2. Zero dynamic fields in the prefix; always place dynamic information at the end.
    3. Append to history only, never rewrite; add corrections at the tail.
    4. Version the tool set and keep it consistent within a session.
    5. Build a monitoring dashboard for hit rate, uncached tokens, and cost per request.
    6. Use A/B testing to verify the impact of changes on hit rate and task success rate.

    8. Closing Thoughts

    An Agent’s competitiveness comes not only from model capability but also from the quality of the harness’s context organization. Stabilize the prefix, make conversations append-only, bring tool definitions under control, and measure the hit rate, and cache hits will turn from an occasional gain into a structural advantage. Saving money is only the result; the real capability is delivering the same outcome with less repeated computation, reliably.