Good Harness Design: Get Prefix Cache Hits Right First

    This article explains why input cost in LLM applications is driven less by how many tokens you read than by how often repeated prefixes fail to be reused. It covers how prefix caching decides hits, six common patterns that break hit rates, a four-layer Harness design approach (context tiering, session affinity, externalized state with retrieval, and observability), a cost model that converts hit rate into savings, and a pre-launch checklist. Readers will learn how to structure prompts and routing so stable prefixes are reused reliably.

    1. A Cost Pattern That Keeps Getting Confirmed

    Public discussion in the industry has surfaced one set of figures: a coding tool driving a high-throughput model reached a cumulative prompt cache hit rate of 99.93%. That corresponds to roughly 947 million cached input tokens, which at the published pricing of the time came to about $2.65, versus about $132.62 if every token had been billed at the uncached rate — almost exactly a 50x difference.

    The value of these numbers is not the dollar amounts. It is the structural fact they expose: the bulk of input cost is not “how much you read” but “how many times you re-read the same content without reusing it.” The price gap between cached and uncached input is typically an order of magnitude, so the first optimization target for a Harness (the runtime framework that carries model calls) is not a shorter prompt, but making identical prefixes reliably reusable.

    Note that the figures above come from public discussion. Ratios will differ across models and pricing rules, so treat them as motivation for the methodology rather than a performance commitment you can apply directly.

    2. How Prefix Cache Hits Are Actually Decided

    Prefix caching in mainstream inference services can be abstracted as follows: take the token sequence as input, compute hashes segment by segment from the beginning, find the longest common prefix against already-cached content, bill the matched portion at the cached rate and the rest at the uncached rate.

    Three hard constraints follow:

    1. The prefix must match token for token. One extra space, one newline, or one timestamp is enough: everything from the divergence point onward degrades to uncached.
    2. Matching is prefix-based, not set-based. Put stable content at the end and it cannot be reused, even if the content is identical.
    3. Caches have a lifetime. Capacity eviction, TTL expiry, and routing to a different instance all cause misses, so the hit rate is a probability, not a guarantee.

    Illustrative pseudocode for how a Harness should assemble a request:

    1. def build_request(system_spec, repo_index, turn_history, user_msg):
    2. # Segment A: highly stable, globally shared, placed first
    3. seg_a = system_spec.render() # tool definitions, output spec, safety policy
    4. # Segment B: stable within the session, changes per branch
    5. seg_b = repo_index.render() # repo structure summary, dependency list
    6. # Segment C: rolling window, keep only the last N turns
    7. seg_c = render_recent(turn_history, N=6)
    8. return seg_a + seg_b + seg_c + user_msg # volatile content always goes last

    3. Six Common Patterns That Destroy Hit Rates

    • Writing timestamps, random IDs, or request sequence numbers into the system prompt. This is the most frequent self-inflicted wound.
    • Reordering tool definitions every turn. Unstable serialization is equivalent to swapping the prefix every turn.
    • Trimming history from the head. Once the head changes, the entire prefix is invalidated; use a tail-based rolling window instead.
    • Mixing two template versions in the same session. A template version switch breaks prefix continuity.
    • Injecting the full text of large files repeatedly. This lengthens the uncached tail and accelerates cache eviction.
    • Load balancing across replicas or instances with no session affinity. Requests get scattered across nodes, and the hit rate drops roughly linearly with the number of replicas.

    4. A Four-Layer Design Method for Harnesses

    Layer 1: Context tiering and stability classification. Split context explicitly into a globally constant layer / session-stable layer / rolling-window layer / one-shot input layer, and ensure serialization within each layer is byte-stable at build time (fixed key order, fixed indentation, no auto-formatting injection).

    Layer 2: Session affinity and routing consistency. Keep the same session on the same inference instance where possible. If a container platform hosts the inference service, configure consistent routing based on a session identifier, and make replica scaling as smooth as possible to avoid mass connection rebuilds.

    Layer 3: Externalized state and on-demand retrieval. Strip volatile state out of the prompt and place it in object storage or a cache service, retrieving only the fragments the current turn actually needs. This reduces both the uncached tail length and overall token consumption.

    Layer 4: A closed observability loop. No measurement, no optimization. At minimum, collect hit rate, cached/uncached token distribution, prefix length distribution, eviction counts, and cost per session. A dashboard can be built on metrics like these:

    1. cache_hit_ratio = cached_tokens / prompt_tokens
    2. prefix_stability = common prefix length between two adjacent turns / previous turn prompt length
    3. cost_per_turn = cached*c_price + uncached*u_price + output*o_price
    4. eviction_rate = evicted prefixes / written prefixes

    prefix_stability is the most diagnostic of these: it surfaces template jitter before the bill gets worse.

    5. Cost Modeling: Turning Hit Rate Into Money

    Let the prompt size per turn be P, the hit rate be h, and the ratio of cached to uncached price be k (commonly on the order of 1:10 to 1:50 in the industry). Input cost savings relative to an all-uncached baseline is roughly h * (1 - k). Moving h from 0.9 to 0.99 at k=0.02 cuts input cost by about another 9x.

    In practice, build a sensitivity table with hit rate on the horizontal axis (0.80/0.90/0.95/0.99) and average daily prompt token volume on the vertical axis, outputting a monthly input cost range. That tells you whether the optimization effort is worth it.

    6. Pre-Launch Checklist

    • Any timestamps, random numbers, or auto-incrementing sequence numbers left in the system prompt?
    • Are tool and function definitions stably sorted and version-locked?
    • Is history trimmed only from the tail?
    • Is session-affinity routing in place, and is the hit rate controllable when replica count changes?
    • Are logging and monitoring/alerting wired up, with alerts when the hit rate falls below a threshold?
    • Have oversized contexts been switched to retrieval-based injection?
    • Has a “prefix stability” regression test been run in a canary environment?

    7. Closing Thoughts

    A high hit rate is not a privilege of a particular model; it is a by-product of Harness engineering quality. Do the four things well — context tiering, serialization stability, session affinity, and observability — and the hit rate will converge to a high level on its own. Otherwise, even the cheapest per-token model price gets cancelled out by repeatedly uncached prefixes. If you need to host inference services plus the accompanying observability capabilities, general-purpose offerings such as Baidu AI Cloud’s container platform, object storage, logging service, and monitoring/alerting can be used as a foundation, which puts the optimization focus back where it belongs: on the Harness design itself.