Good Harness Design: Make Cache Hits Your First Priority
As AI agents move from demos to production, runaway token bills often become the first real obstacle. This article explains why prefix cache hit rate is the primary cost lever for long-context, multi-turn agent workloads, using a simple cost model to show how a 50x price gap emerges as the reusable prefix approaches 100%. It then presents a four-layer Harness design—request construction, context governance, observability, and routing/capacity—along with common anti-patterns and a four-week rollout roadmap centered on cache hit rate as the acceptance metric.
When agents move from demos to production, the first problem teams hit is often not that the model is not smart enough, but that the bill grows too fast. A representative observation from the industry: when running a general-purpose large model on the execution framework of an AI coding tool, the cumulative cache hit rate reached 99.93%. The 947 million input tokens that were cache hits cost about $2.65; if those same tokens had been billed at the non-cached price, the cost would have been about $132.62—exactly a 50x difference. The number is not mysterious. It reflects a simple engineering rule: in long-context, multi-turn agent workloads, the dominant cost variable is not the unit price, but the proportion of repeated computation. This article sets aside specific product details, abstracts the problem into “good Harness design starts with solid cache hits,” and offers practical design methods.
1. Why Cache Hits Are the First Lever for Agent Cost
Large model inference can be roughly split into two phases: prefill of the input tokens and token-by-token autoregressive decoding. During prefill, the model computes and writes the attention key-value cache (KV Cache) for every token, with compute cost roughly linear in input length. During decode, it reuses that cache to generate output token by token. The core idea of prefix caching is that if two requests share an identical prefix token sequence, the key-value cache for that prefix can be reused directly, with no need to prefill it again.
Agent workloads fit this mechanism closely. Within the same session, the system prompt, tool definitions, long-term memory, and code repository context usually stay unchanged; only the most recent user inputs and tool returns change. This means a well-designed execution framework can naturally place most of the input on the “reusable prefix.” Conversely, if the framework applies seemingly harmless “optimizations” to the context before each turn—reordering the tool list, dynamically rewriting the system prompt, inserting timestamps, truncating and appending summaries—the prefix is repeatedly broken and the hit rate drops off a cliff.
So cache hits are not a money-saving trick; they are an architectural constraint. They require treating context stability as a first-class concern, on par with functional correctness.
2. The Math Intuition Behind Hit Rate: Where the 50x Gap Comes From
Suppose the reusable prefix accounts for a fraction p of a workload and the non-cached part accounts for 1-p. If cached tokens are priced at 1/50 of the non-cached price, the total relative cost is roughly:
cost ≈ p * (1/50) + (1 - p) * 1
When p = 0.9, cost ≈ 0.118; when p = 0.99, cost ≈ 0.0298; when p = 0.9993, cost ≈ 0.02. Raising the hit rate from 90% to above 99% cuts cost by another order of magnitude. The 50x gap in the original observation is essentially the limiting behavior as p approaches 1.
This model also explains why occasional context jitter is so expensive: a single prefix invalidation forces all subsequent turns to re-prefill from the break point, so the loss accumulates rather than being one-off.
3. A Four-Layer Design for the Harness
3.1 Request Layer: Make the Prefix an Immutable Contract
Split the request into a “stable segment” and an “incremental segment,” and guarantee byte-level consistency of the stable segment:
def build_request(system_block, tool_specs, history, new_input):# Stable segment: serialization must be byte-for-byte reproduciblestable = stable_json({"system": system_block, # no timestamps or random IDs"tools": sorted_tools(tool_specs) # fixed order; never reorder dynamically by hit rate})delta = stable_json({"history": history, "input": new_input})return stable + delta
Key points: keep tool definitions in a fixed order; move dynamic information in the system prompt (time, session ID) into the incremental segment; avoid embedding hashes, random numbers, or environment probe results in the stable segment.
3.2 Context Governance: Control the Decay of the “Cacheable Surface”
In long sessions, history keeps growing. If you use a sliding window or summary compression, make sure compression happens only at stable-segment boundaries and that the compressed result, once fixed, never changes again. A recommended approach is layered memory: keep recent in-session dialogue verbatim; solidify older content as structured summaries; place cross-session knowledge in external retrieval and inject it into the incremental segment on demand. This controls length without breaking the prefix.
3.3 Observability Layer: Treat Hit Rate as a Core Metric
No measurement, no optimization. At minimum, collect per-turn total input tokens, cached token count, hit rate, recompute volume caused by prefix invalidation, and cache write count. Example instrumentation:
metrics.record({"input_tokens": usage.input_tokens,"cached_tokens": usage.cached_input_tokens,"hit_ratio": usage.cached_input_tokens / max(1, usage.input_tokens),"prefix_invalidations": counter.inc(),})
When the hit rate drops unexpectedly, check three things first: whether the stable segment was rewritten, whether the tool list was reordered, and whether the session was routed to an instance that does not share the cache.
3.4 Routing and Capacity Layer: Send the Same Prefix to the Same Place
Prefix caches are usually bound to a specific inference instance. If load balancing scatters consecutive requests of the same session across different instances, the cache effectively does not exist. In practice, use session affinity or consistent routing based on prefix hashes to direct requests with the same prefix to the same instance; also reserve enough GPU memory for the cache and set an eviction policy to avoid frequent churn. If you run inference services on a container platform, include the affinity policy and scaling policy in configuration management.
4. Common Anti-Patterns
- Inserting the current time, request ID, or random sampling markers into the stable segment;
- Dynamically reordering tool definitions by “most recently used” each turn;
- Incrementally rewriting history (re-summarizing all history every turn);
- Multiple tenants sharing one prompt template but each injecting a different prefix;
- Completely random load balancing with no session affinity;
- Monitoring only latency and error rate, not the cached token ratio.
5. Rollout Roadmap
Week one: add instrumentation and obtain a baseline hit rate and recompute volume. Week two: freeze the stable segment and fix the placement of dynamic fields, which usually delivers the largest improvement. Week three: introduce layered memory and external retrieval to control context growth. Week four: adjust routing affinity and cache capacity to eliminate cross-instance jitter. Use hit rate as the acceptance metric at each step, and watch output quality and latency alongside it, so that saving money does not come at the expense of results.
6. Conclusion
A 99.93% hit rate is not magic; it is the inevitable result of stacking four things: a stable prefix, controlled context, observability, and affinity routing. For teams, before rushing to switch models or push down unit prices, making the Harness’s cache hits solid is often the step with the highest return on investment. If you run on general-purpose infrastructure such as Baidu AI Cloud, with container platforms, logging services, and monitoring and alerting capabilities, and put these metrics on a regular dashboard, the cost curve is usually flatter than expected.
