Good Harness Design: Maximize Cache Hits First
This article explains why prompt cache hit rate is the dominant factor in LLM application cost, and how Harness design determines it. It covers how prefix-based caching works, five common practices that silently break cache reuse, and engineering techniques such as layered prompt architecture, serialization normalization, append-only session history, concurrency isolation, and observability. It also debunks four common misconceptions, recommends an optimization order, and provides a practical checklist for teams building AI coding assistants and agents.
1. A Cost Fact That Keeps Getting Reconfirmed
In LLM-powered coding tools, code assistants, and automated agents, one pattern keeps recurring: once session context is reused consistently, the cumulative cache hit rate can reach extremely high levels, and actual input-side spending ends up orders of magnitude below what a “bill everything as a cache miss” assumption would predict. A widely discussed public data point: a long-running session reached a cumulative cache hit rate of 99.93%, with roughly 947 million input tokens served from cache at a cost of about $2.65 at the then-public pricing. Had all of those tokens been billed as misses, the cost would have been about $132.62 — exactly 50x higher.
What makes these numbers interesting is not “50x cheaper.” It is the billing structure they expose: in mainstream LLM pricing models, input tokens are split into two tiers — cached input and uncached input — and the cached tier is significantly cheaper (commonly around one tenth of the uncached price, though the exact ratio varies by vendor and model). In other words, cost is driven less by how many tokens you send and more by how many of those tokens can be reused.
The engineering conclusion follows directly: at a stage where model capability and context length are converging, the quality of the Harness — the runtime framework that assembles prompts, manages context, and orchestrates tool calls — directly determines the order of magnitude of your bill. Get cache hits right first. Only then consider switching models, compressing context, or adding routing. The order of returns should not be reversed.
2. Why Cache Hits Fail: Build the Right Invalidation Model
To improve the hit rate, you first need to understand when a hit is possible. The widely accepted precondition for reuse is: the prefix must be byte-for-byte identical. The cache is keyed on a contiguous prefix starting from the beginning of the prompt. Only when that prefix matches exactly will a hit occur; the moment any byte changes anywhere in the prefix, everything after that point degrades to a miss.
The following illustrative pseudocode captures this prefix sensitivity:
prompt = system_block + tool_schema_block + long_term_memory + session_history + current_query# Hit detection is approximately: find the longest common prefix with prior requestshit_tokens = longest_common_prefix_len(prompt, cached_prompts)miss_tokens = len(prompt) - hit_tokens
This explains the most common forms of self-inflicted damage in practice:
- Timestamps and random values placed at the front. Injecting the current time, a random request ID, or a trace ID at the top of the system block makes the prefix different on every turn, so all the stable content that follows becomes unreusable.
- Unstable tool definition ordering. When tool schemas come from hash tables, set iteration, or unsorted registration results, the serialization order drifts across processes and the prefix breaks very early.
- Dynamic content embedded in the stable region. Concatenating a user nickname, tenant ID, or environment variable into the middle of the system prompt is like planting a time bomb inside a stable prefix.
- Session history rewritten in place. Summarization, error correction backfills, and reordering of history messages all change the prefix bytes.
- Multiple concurrent branches sharing one session identifier. Concurrent branches overwrite each other’s context, repeatedly invalidating the cache key.
3. Harness-Side Engineering Practices: Make Stability a Structural Constraint
3.1 Layered Prompt Architecture: Stable Layers First, Volatile Layers Last
Split the prompt explicitly into four layers and strictly guarantee their order and byte stability:
[L1 ultra-stable] Role definition, output specification, safety boundaries (version-controlled; changes go through a release process)[L2 stable] Tool/function schemas (serialized after sorting, with an explicit schema version number)[L3 semi-stable] Long-term memory, retrieved project knowledge base results (emitted in a fixed sort order)[L4 volatile] Current session history, this turn's user input, timestamps, etc.
The key constraint: no volatile information may cross ahead of L3 into an earlier position. Teams can encode this as a CI check — for example, snapshot tests on prompt templates that assert the first N tokens are identical across builds.
3.2 Serialization Normalization: Turn “Looks the Same” into “Is Byte-Identical”
The same semantic structure can serialize to different bytes under different implementations. Engineering needs to pin down: JSON key order, whitespace and indentation, Unicode normalization form, floating-point precision, and array order. It is worth computing a stable hash for each prompt layer and writing it to logs, so that when a hash drifts you can pinpoint the exact layer instead of vaguely observing that “the hit rate dropped.”
3.3 Append-Only Session History Management
Treat history as an append-only log rather than a freely editable string. When context compression is needed, use a “frozen prefix + tail window” strategy: the frozen portion is never modified, and compression happens only inside the tail window, which confines the invalidation to the last small segment.
# Bad: full rewrite, entire prefix invalidatedhistory = summarize(history) + new_turn# Good: frozen prefix, only the tail rollsfrozen_prefix = history[:k] # never changes once fixedtail_window = compact(history[k:]) # compression affects only the tailprompt = base + frozen_prefix + tail_window + new_turn
3.4 Concurrency and Multi-Tenant Isolation
Different sessions and different tenants must use mutually isolated context namespaces so that branches do not pollute each other. If parallel subtasks share the same long context, ensure their prefixes are fully identical and carry only their own task descriptions in the tail. This way the long prefix is reused without branches breaking each other.
3.5 Bring Hit Rate into Observability
No measurement, no optimization. At minimum, collect in your logging service and monitoring/alerting system: cached and uncached input tokens per request, cumulative hit rate, prefix hash, the layer where invalidation occurred, and cache expiry wait time. Dashboards grouped by model, scenario, and template version can quickly answer whether a drop was caused by a template change or by a shift in traffic composition.
4. Common Misconceptions and the Order of Returns
- Misconception 1: Save money by compressing prompts. Compression changes prefix bytes; if it happens in the stable region, it destroys hits instead. The gain from compression is far smaller than the gain from keeping the prefix stable.
- Misconception 2: Frequently switching models or parameters. Different models and parameter configurations usually map to different reuse domains, so frequent switching invalidates existing reuse assets.
- Misconception 3: Focusing only on output tokens. Output tokens usually cost more per token but remain a controlled share; repeated input of long context is the main cost source.
- Misconception 4: Treating hit rate as a model capability. It is primarily a result of the Harness and calling conventions — an engineering-controllable factor.
The recommended optimization order: first fix the layering and serialization conventions → then add hit-rate observability → then restructure session history to be append-only → and only last consider context compression, retrieval pruning, and model routing.
5. Implementation Checklist
- Is the prompt layered, with all volatile content placed at the end?
- Are tool schemas serialized after sorting and carrying a version number?
- Have timestamps and request IDs been removed from the stable prefix?
- Is history append-only, with compression limited to the tail window?
- Is a stable hash computed for each layer and written to logs?
- Are hit-rate dashboards and alert thresholds in place per scenario?
- Do template changes go through a release process with prefix snapshot tests?
6. Conclusion
A high hit rate is not luck; it is the result of treating prefix stability as a first-class engineering constraint. When a Harness gets these four things solid — layered structure, normalized serialization, append-only history, and observability — repeated context turns from a cost into a reusable asset, and the billing structure changes with it. In a stage where model capabilities are converging, this kind of deterministic return is worth prioritizing over any single-point trick.
