Good Harness Design: Fix Cache Hits First
This article explains why prefix cache hit rate is the first-priority design metric for an LLM harness, the prefix-matching constraints behind it, and a cache-friendly architecture with observability, anti-patterns, and a four-step rollout. It covers context layering (L0–L3), freezing and versioning prompts and tool definitions, pushing volatile content to the tail or out of band, append-only conversation history, RAG caching tactics, and the cost and TTFT gains that follow.
Good Harness Design: Fix Cache Hits First
1. A Cost Pattern Worth Breaking Down
A widely circulated set of figures from the industry is representative: a coding tool serving a large model reported a cumulative prefix cache hit rate of 99.93%. Under public pricing, roughly 947 million cached input tokens cost about $2.65, while the same tokens priced as uncached input would cost about $132.62 — almost exactly a 50x difference.
The value of these numbers is not the dollar amounts but the structural fact they expose: in long-context, multi-turn workloads, the main variable on the input side is not “how many tokens were used” but “how many tokens went through the cache.” When the hit rate moves from 90% to somewhere around 99.9%, input cost drops by an order of magnitude. This also explains why mature harnesses — the execution frameworks that carry model calls — treat cache hits as the first priority, instead of starting with model selection, concurrency scheduling, or prompt tricks.
Note that this article discusses no specific product or vendor; it only covers transferable engineering methods and general principles.
2. Why Cache Hits Are the First-Order Problem for a Harness
2.1 Cost Structure Determines the Optimization Order
Input-side inference for large models usually distinguishes “input that hits the cache” from “input that misses,” and the unit prices differ significantly. Multi-turn chat, codebase Q&A, and long agent chains all share one trait: every request carries a large prefix that is almost identical to the previous turn (system instructions, tool descriptions, message history, file contents already read).
If that prefix is recomputed every time, cost grows linearly or even super-linearly with the number of turns; if it can be reused reliably, the marginal cost approaches zero. So the optimization order should be: first make sure the reusable part is reused, then optimize the part that cannot be reused.
2.2 Hit Rate Is a Design Metric, Not a Luck Metric
Many teams treat cache hits as an incidental runtime outcome. In practice, the hit rate is almost entirely determined by how requests are constructed. With the same model and the same workload, hit rates across different harnesses can differ by tens of percentage points. The difference comes down to three things:
- whether the prefix is byte-for-byte stable;
- whether the stable prefix is placed at the very front;
- whether the changing part is isolated at the tail and kept as short as possible.
2.3 High Hit Rates Also Pay Off in Latency
Cache hits save time as well as money. Cached portions skip repeated prefill computation, so time to first token (TTFT) drops noticeably, and the difference is especially visible in long-context scenarios. Cache optimization is therefore a dual lever for both cost reduction and speed.
3. The Underlying Constraint: Prefix-Matching Semantics
To design for a high hit rate, you first have to understand the general constraint: prefix cache reuse is typically decided by the longest common prefix starting from the beginning. Once content at some position changes, nothing after it can be reused — even if the content later returns to its original form.
Three hard rules follow:
- Position-sensitive: identical content at different positions cannot be reused across them.
- One change spoils everything: any modification anywhere in the prefix (timestamps, random IDs, whitespace, line breaks, JSON field order) invalidates everything after it.
- Longer is more valuable: content closer to the front is reused across more turns, so it yields more.
These three rules are the theoretical basis for all the engineering practices below.
4. A Cache-Friendly Harness Architecture
4.1 Context Layering: Sort Content by Rate of Change
A recommended approach is to split the request context into four layers and concatenate them strictly in this order:
[L0 very stable] Role definition, safety policy, output spec[L1 stable] Tool/function signatures and descriptions, domain knowledge, long-term rules[L2 semi-stable] Conversation history, confirmed file contents, interim conclusions[L3 volatile] Current user input, live retrieval snippets, timestamps, random identifiers
The key principle: the lower the rate of change, the earlier the position; the higher the rate of change, the later the position. Any practice that puts volatile content in front destroys the entire cache.
4.2 Freezing Prompts and Tool Definitions
- Once tool descriptions ship, avoid changing wording or field order;
- When you need to canary different wording, keep multiple complete prefixes side by side rather than doing local substitution inside one prefix;
- Version your prefixes: treat L0/L1 as immutable assets, and make changes through version numbers rather than in-place edits.
4.3 Pushing Volatile Content to the Tail and Minimizing It
Timestamps, request IDs, user nicknames, random sampling parameters and the like should all go at the end of the request; better still, keep them out of the context entirely and pass them through a side channel. Illustrative refactor:
# Bad: volatile content pollutes the prefixmessages = [{"role": "system", "content": f"Current time {now()}, request {uuid4()}\nYou are a coding assistant..."},{"role": "user", "content": question},]# Good: stable prefix first, volatile info at the tail or out of bandmessages = [{"role": "system", "content": SYSTEM_PROMPT_V3}, # frozen, versioned{"role": "system", "content": TOOL_SPEC_V3}, # frozen, versioned*history, # append-only growth{"role": "user", "content": question},]meta = {"trace_id": uuid4(), "ts": now()} # side channel, not in context
4.4 Append-Only Maintenance of Conversation History
In multi-turn scenarios, keep the history append-only, never rewritten. Common cache-breaking behaviors include summarizing and rewriting past messages, deleting intermediate turns, reordering, and re-formatting tool results a second time. If history must be compressed, freeze the compressed result as a new stable layer and keep it unchanged in later turns, instead of regenerating a summary every turn.
4.5 Caching Strategy for Retrieval-Augmented Scenarios
RAG is the easiest place to punch through the cache, because retrieved snippets change every turn. Practical options:
- Separate the “fixed knowledge block” from the “dynamic retrieval block”: the former goes to L1, the latter to L3;
- Apply stable serialization to retrieval results (fixed field order, fixed sort rules, no random IDs);
- Add a local cache for frequently repeated queries to reduce repeated injection;
- Cap the size of the dynamic block so long-tail snippets do not eat the budget.
5. Observability: No Measurement, No Hit Rate
Cache optimization has to be measurable. A harness should collect at least these metrics:
- cached input tokens, uncached input tokens, and hit rate per request;
- hit rate distribution by business scenario / tenant / model;
- prefix invalidation event counts with the invalidation position identified (which layer starts to mismatch);
- number of cache blocks, reuse-count distribution, eviction counts;
- a combined dashboard of per-request cost and TTFT.
Illustrative instrumentation:
def record(usage):hit = getattr(usage, "cached_input_tokens", 0)miss = usage.input_tokens - hittotal = max(usage.input_tokens, 1)metrics.gauge("cache.hit_ratio", hit / total)metrics.counter("cache.miss_tokens", miss)metrics.counter("cache.hit_tokens", hit)
When the hit rate drops unexpectedly, check three things first: whether the prefix was polluted by dynamic fields, whether serialization is unstable, and whether the context was reordered by accident.
6. Common Anti-Patterns
- Embedding the current time, a random number, or a session ID in the system prompt;
- Regenerating a history summary every turn and replacing the original history with it;
- Tweaking tool definitions frequently across iterations without version isolation;
- Using a serialization method that does not guarantee ordering to emit structured context;
- Concatenating a large dynamic retrieval block after the system instructions and before the user input;
- Looking only at total token counts without the cached/uncached split, which leads to optimizing in the wrong direction;
- Multiple tenants sharing one prefix that contains tenant identifiers, causing them to invalidate each other.
7. Rollout Path: Four Steps
- Measure first: build the cached/uncached split and invalidation localization, and establish a baseline.
- Layer the structure: complete the L0–L3 refactor, freeze L0/L1, and version them.
- Clean up volatile content: move timestamps, random identifiers, and tenant information out of the prefix, and push them to the tail or a side channel uniformly.
- Govern continuously: make hit rate part of release gates and capacity planning, set threshold alerts, and prevent regressions across version iterations.
8. Closing
Once the main tension on the input side shifts from “total tokens” to “cache reuse efficiency,” harness engineering quality translates directly into the bill and into response speed. Rather than chasing more elaborate scheduling strategies, do the simplest thing to the extreme first: keep stable content stable, keep it at the front, and keep it reusable. Once cache hits are solid, model selection, context compression, and concurrency orchestration will actually start to compound.
