A Good Agent Harness Starts with Solid Cache Hit Rates

    This article explains why prefix cache hit rate deserves to be treated as a core engineering metric for LLM agents. It breaks down prefill and decode, defines the prefix as the only strict criterion for cache reuse, and shows how the agent harness—through context ordering, tool serialization, history trimming, and session management—ultimately determines whether a prefix stays stable. You will find practical techniques such as layered context design, append-only history, canonical serialization, controlled invalidation boundaries, and observability, along with common anti-patterns and a deployment checklist.

    1. Why Cache Hit Rate Deserves to Be Its Own Engineering Metric

    In large language model inference, a single request can be roughly split into two stages.

    The first stage is prefill. The model reads the system prompt, tool definitions, project notes, conversation history, and the new user input of the current turn in sequence, computing intermediate states for every token across the attention layers. This stage determines time to first token and is the most compute-intensive part in long-context scenarios.

    The second stage is decode. After understanding the context, the model generates the answer token by token. This stage is more affected by GPU memory bandwidth and batching strategy, while the compute per step remains relatively manageable.

    In every attention layer of a Transformer, tokens that have already been read form Key and Value tensors. Saving these intermediate states and reusing them directly in later requests is what we call the KV Cache.

    One point deserves emphasis: the KV Cache is neither the text of the model’s previous answer nor anything that can be opened and read. It is closer to the “computational notes” the model leaves behind after reading the material, and it is only valid for a specific model and a specific context prefix.

    From this follows a simple conclusion: if there is a large amount of exactly identical opening content across round after round of agent requests, the prefill result of that opening can in theory be reused repeatedly instead of recomputed every time. That is where the value of cache hits comes from.

    Cost-sensitive teams should pay particular attention to it. When the cache hit rate is high enough, the input billing for the hit portion is usually significantly lower than for the miss portion, and the overall cost can differ by an order of magnitude; even under self-hosted inference or flat-rate plans, a higher hit rate translates directly into higher throughput and shorter queue times. So when asked “why study cache hits,” the answer can be very direct: because it saves money and saves time.

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

    To talk about hit rate, you must first define the prefix.

    A request sent by an agent to the model is 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 the segment that is continuously and completely identical starting from the very first token. It is not keyword matching, nor is it “semantically close enough.” The criterion is extremely strict—if two requests are identical from the beginning through token 50,000, those 50,000 tokens form the shared prefix; once token 50,001 differs, everything after it usually has to be recomputed along a new path.

    A few examples:

    • If the previous request was A + B + C and this turn is A + B + C + D, then as long as A + B + C is unchanged byte for byte, the cache up to C can be reused and only the new D needs to be computed.
    • 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 need to be recomputed.

    Prompt caching is therefore essentially a game of “checking the answer from the top”: the more stable the opening, the longer the reusable prefix; the earlier a change appears, the more content must be recomputed. In engineering terms it can be summarized in one sentence—push volatile content as far to the back as possible.

    3. Why the Harness Decides the Hit Rate

    You can choose the model, and you can also choose the harness that carries it (the execution framework responsible for assembling context, dispatching tools, and managing sessions). In agent scenarios, the harness has evolved from an early “invocation wrapper” into a critical layer that affects whether tasks succeed, and cache hit rate is one hard dimension for measuring its quality.

    The reason is that the final shape of the request content is almost entirely determined by the harness:

    1. The concatenation order is decided by the harness. Putting timestamps, random IDs, or retrieval results at the very front directly destroys prefix stability.
    2. The serialization of tool definitions is decided by the harness. Field order, spaces, line breaks, and whether optional parameters are expanded—any instability in any of these causes token-level differences.
    3. The history trimming strategy is decided by the harness. Sliding windows, summary compression, and dropping by turn all change the prefix boundary.
    4. The way sessions and concurrency are organized is decided by the harness. When multiple sessions share the same mutable global state, the hit rate is continuously dragged down.

    In other words, with the same model and the same business, switching to a different harness can produce a completely different hit rate and a completely different bill. This is also why selection should include cache friendliness as an evaluation item rather than looking only at benchmark scores.

    4. Engineering Practices for Improving Hit Rate

    4.1 Layer the Context: Stable Zones First, Volatile Zones Last

    The recommended layering order is:

    1. Layer 1: globally stable system constraints (almost never change)
    2. Layer 2: tool and interface definitions (low-frequency changes, require canonical serialization)
    3. Layer 3: project notes and long-term knowledge (replaced as a whole by version, not rewritten each time)
    4. Layer 4: conversation history (append only, never modified)
    5. Layer 5: new input this turn, timestamps, random identifiers, retrieval snippets

    The key principle: anything that changes every time must not appear in the prefix.

    4.2 Append Only, Never Modify in Place

    Conversation history should stay append-only. When early content needs correcting, prefer appending a correction note at the end rather than going back to rewrite the message from turn 3—the latter invalidates everything from turn 3 onward.

    4.3 Canonical Serialization

    Use stable serialization for tool definitions and structured configuration: fixed key order, fixed indentation, unstable whitespace removed, and avoid serializing dictionary iteration order, sets, or hash structures directly into the prompt. An illustrative approach:

    1. import json
    2. def stable_dump(obj) -> str:
    3. # Sort keys + compact separators, so the same semantics always produce exactly the same text
    4. return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)

    4.4 Control the Minimum Reuse Granularity and Invalidation Boundary

    Split long documents into stable blocks and replace them as a whole instead of rewriting parts locally; write the version number inside the block so old blocks expire naturally and new blocks hit independently, avoiding “change one sentence, invalidate the whole document.”

    4.5 Turn Hit Rate into a Regression-able Metric with Observability

    On the harness side, record for each request the number of input tokens, the number of hit tokens, the hit rate, time to first token, and the number of failed retries, and aggregate by session, tool version, and prompt template. Illustrative calculation:

    1. hit_rate = cached_input_tokens / max(total_input_tokens, 1)
    2. # A sudden drop in hit rate usually means the prefix has been polluted: first check tool definitions and where timestamps are injected

    With logging services and monitoring alerts in place, you can see the hit rate curve at the same moment a template change ships, turning “cache friendly” into a release standard that can be regression-tested and gated.

    5. Common Anti-Patterns

    • Injecting the current time, a request ID, or a random number at the start of the system prompt.
    • Regenerating tool definitions every turn with unstable field order.
    • Concatenating retrieval results at the very front, so the prefix differs every turn.
    • Replacing history with a semantic summary that is regenerated every turn.
    • Multiple tenants or sessions sharing one mutable global context.
    • Choosing a model only by benchmark scores while ignoring the harness’s ability to organize context.

    6. Deployment Checklist

    1. Draw a diagram of the request assembly order, marking which parts are stable zones and which are volatile zones.
    2. Compare two consecutive runs with the same input to confirm the shared prefix length matches expectations.
    3. Check whether tool definition serialization is stable and whether it is under version control.
    4. Confirm history is append-only and corrections are done by appending at the end.
    5. Set up dashboards and alerts for hit rate, time to first token, and cost per task.
    6. Write “cache friendliness” into the harness selection and template review process.

    Get prefix stability right and cache hits follow naturally; once hits go up, improvements in cost and latency become measurable and sustainable. It is a foundational piece of engineering with high priority that is too often deferred to “optimize later.”