Good Harness Design: Get Cache Hits Right First

    This article explains why input cache hit rate is a decisive cost factor for AI agent workloads and why it is primarily determined by the execution framework, commonly called the Harness, rather than by model capability alone. It covers why agent workloads naturally suffer from low cache reuse, the first principle of prefix matching and the longest stable prefix, and six key Harness practices: byte-level deterministic prompt templates, versioned tool definitions, append-only session state, controlled context compression with a frozen summary layer, deterministic retrieval ordering, and cache isolation with concurrency-aware scheduling. It also outlines the observability metrics needed to verify cache optimization, a list of common anti-patterns, and a four-stage adoption roadmap for teams running agents over the long term.

    1. Starting With a Telling Cost Gap

    A set of figures circulating in the industry recently sparked considerable discussion. When running a large-parameter model under a certain AI coding execution framework, the cumulative input cache hit rate reached 99.93%. Using publicly available pricing as a rough estimate, roughly 947 million input tokens served from cache cost about $2.65, while the same tokens billed as cache misses would cost about $132.62 — almost exactly a 50x difference.

    The value of these numbers is not the dollar amounts themselves, but the fact they expose an often-overlooked reality: in agent workloads, the cost structure on the input side depends heavily on reuse rate, and reuse rate is determined mainly by how the execution framework (commonly called the Harness) organizes context, not by model capability alone.

    A note on scope: cache pricing rules, hit-determination granularity, and invalidation policies differ across vendors. This article does not discuss the billing details of any specific product; it focuses only on general engineering principles.

    2. Why Agent Workloads Have Naturally Low Cache Hit Rates

    Traditional single-turn question answering has short inputs with concentrated changes, so caching is easy to get right. Agent workloads have three characteristics that make them inherently cache-unfriendly:

    1. Continuously growing context: system prompts, tool definitions, historical trajectories, and retrieved snippets keep stacking up, pushing input length from a few thousand tokens to hundreds of thousands.
    2. Easily polluted prefixes: timestamps, request IDs, randomly ordered candidate sets, and dynamically assembled debug information — if any of these appear near the front, everything after them is invalidated.
    3. Concurrent branching: parallel subtasks and multi-candidate sampling constantly switch contexts, and without isolation the cache gets repeatedly flushed.

    Once you understand these three points, it becomes clear why “getting cache hits right first” is a prerequisite for execution framework design, not a patch applied after launch.

    3. The First Principle of Cache Hits: The Longest Stable Prefix

    Input caching in mainstream inference services generally uses prefix matching semantics: comparison proceeds segment by segment from the beginning and stops at the first difference, with everything after that point treated as a miss. This yields one core design rule:

    The earlier content sits in the context, the more stable it must be; the more volatile the content, the later it must sit.

    This means context assembly order is not a matter of style but of cost. A recommended assembly order:

    1. [highly stable] model and decoding parameter notes, safety policy, fixed system instructions
    2. [stable] tool/function definitions (fixed order, fixed field order)
    3. [semi-stable] project-level long-term knowledge, coding conventions, repository structure summary
    4. [volatile] current task description, retrieved snippets for this turn
    5. [most volatile] live timestamps, random sampling results, debug markers

    As long as volatile fields are consistently pushed to the tail, the prefix remains reusable even if the tail changes every time.

    4. Six Key Practices at the Harness Level

    4.1 Byte-Level Determinism in Prompt Templates

    Hit determination is usually based on the serialized byte sequence. Therefore JSON key order, array order, whitespace and line breaks, floating-point precision, and enum order should all be fixed. In practice, avoid serializing unordered collections directly, and sort the tool list by name before concatenation.

    4.2 Version Control for Tool and Function Definitions

    Tool definitions are often the largest part of the context yet the least likely to change. Treating them as “configuration assets” under version control, and bumping the whole version on change rather than making local tweaks, can significantly improve reuse across sessions.

    4.3 Append-Only Session State

    Treat conversation history as an append-only log: new information is attached as new blocks at the tail, and rewriting existing history blocks is forbidden. When an earlier conclusion needs correcting, append a correction note instead of rewriting what came before.

    1. def append_turn(ctx, role, payload):
    2. # Append only; never modify the existing prefix
    3. ctx.blocks.append({"role": role, "payload": payload, "seq": ctx.next_seq()})
    4. return render(ctx) # the rendered prefix stays stable

    4.4 Bounding Context Compression and Summarization

    Long sessions must be compressed, but compression rewrites the prefix. The compromise is a “stable summary layer”: once a summary is generated it is frozen, and only incremental summaries are appended after it, avoiding a full re-summarization every turn that would shift the entire prefix.

    4.5 Deterministic Ordering of Retrieved Snippets

    Retrieval results should be sorted by a fixed rule (such as relevance score plus document ID) and truncated to a fixed budget. Do not introduce randomness or differences based on concurrent completion order, otherwise the same retrieval will produce a different prefix.

    4.6 Cache Isolation and Concurrency Scheduling

    When multiple tenants and tasks share a runtime, maintain a separate context namespace for each task, and where possible schedule consecutive requests from the same session to the same inference instance to reduce repeated warm-up across instances.

    5. Observability: No Measurement, No Optimization

    Cache optimization must be verifiable. It is recommended to instrument the following metrics in the execution framework:

    • Request level: total input tokens, cached input tokens, hit rate, and the starting offset of the first miss region;
    • Session level: cumulative hit rate, number of prefix drift events, and average stable prefix length;
    • Change level: hit rate comparison before and after each template or tool definition release.

    The “starting offset of the first miss region” is the most diagnostic: it points directly to which segment broke the prefix. If the offset always appears at the same position, the problem can essentially be pinned to the template fragment at that position.

    1. metrics: hit_ratio=0.9993 first_miss_offset=41230 drift_count=0

    6. Common Anti-Patterns

    • Injecting the current time or a random greeting at the start of the system prompt;
    • Regenerating tool definitions on every request with unstable ordering;
    • Concatenating context directly from hash table iteration results;
    • Repeatedly “rewriting history + re-summarizing” within a session;
    • Counting only total tokens without distinguishing hits from misses;
    • Treating caching as a backend capability while the framework imposes no constraints.

    Stage one: make it measurable — add instrumentation for hit rate and first-miss offset to establish a baseline. Stage two: stabilize the prefix — fix template order, tool definition ordering, and retrieval ordering to eliminate randomness. Stage three: control drift — introduce append-only history and a frozen summary layer to control long-session cost. Stage four: make it regression-proof — include hit rate in pre-release automated regression gates so later iterations cannot quietly degrade it.

    8. Conclusion

    Cache hit rate is not an occasional windfall on the model side; it is a direct reflection of execution framework engineering quality. Get these four things solid — stable prefixes, deterministic rendering, append-only state, and observable metrics — and the cost curve shifts from linear growth to something close to controllable. Otherwise, even the strongest model capability will be consumed by repeatedly recomputed input costs. For teams planning to run agents over the long term, building the Harness first and optimizing model calls second is the more pragmatic order.