Improving Prompt Cache Hit Rates in AI Coding Harnesses
This article explains how AI coding harnesses can reduce inference costs by designing long, stable, byte-consistent prompt prefixes for prompt caching. It covers why cache hit rate is a cost lever, common causes of cache misses, practical harness-side design principles such as stable system prefixes, deterministic context assembly, layered cache keys, variable-tail control, and session reuse. It also outlines metrics for evaluating impact and boundary conditions around TTL, privacy, billing data, and cache invalidation.
In AI coding and multi-turn agent tasks, model input is often dominated by a long prefix made up of the system prompt, repository summary, current file, and tool trace. These prefixes are highly similar across consecutive requests in the same session and often across the same repository. Prompt caching exploits this pattern: the server reuses key-value pairs already computed for a prefix and charges the full input only for the uncached portion. The primary engineering goal for a harness is therefore not to pile on more context, but to make the cacheable prefix long and stable enough that the vast majority of tokens fall on the cache-hit path.
Why cache hit rate is a cost lever
Large-model input pricing usually distinguishes between cache hits and cache misses. The unit price for cached tokens is far lower than for uncached tokens, sometimes by orders of magnitude. In long sessions and agent tasks with many tool calls, a single request can involve hundreds of thousands of tokens. Most of that volume is repeated system instructions, directory trees, already-read files, and historical tool output. If this content is treated as new input every time, cost grows linearly. If the prefix is byte-identical and falls within the cache window, cost largely covers only the increment.
In engineering terms, pursuing a hit rate above 99% is about removing repeated computation from the bill.
Common causes of cache misses
- Prefix jitter. Timestamps, random IDs, session sequence numbers, and dynamically inserted “current time” values break byte-level consistency.
- Context reordering. The same set of files is sorted by hash or access time, so adjacent requests have different prefixes.
- Mutable metadata embedded in tool results. Absolute paths, machine names, and process IDs leak into output.
- Premature truncation or sliding windows. Cutting a stable prefix to save length causes all subsequent requests to miss.
- Improper cache-key strategy for multi-tenant or concurrent sessions. This can cause cache pollution or prevent reuse.
Practical design principles for a harness
Stable system prefix
Write role definitions, safety constraints, and repository-level conventions as fixed text. Do not concatenate dates or version numbers at runtime. When dynamic information is needed, place it in a variable segment at the end of the request so that all bytes before that segment remain identical.
Deterministic context assembly
Sort file lists and symbol indexes lexicographically by path. Normalize file contents by standardizing line endings and removing trailing whitespace. Clean tool returns structurally first: strip host-specific fields and retain only task-relevant text. This allows the common prefix across adjacent requests to cover most of the tool history.
Layered cache keys
Separate the system layer, repository layer, and session layer. The system layer almost never invalidates. The repository layer can be reused for a long time as long as the index has not changed. The session layer should only append increments. The harness should explicitly track the cached prefix length and perform prefix alignment on the client side to avoid meaningless small differences.
Control the variable tail
Place the current user instruction and the latest tool result at the end. Merge consecutive tool calls where possible to reduce the number of intermediate-state requests. For read-only exploration tools, results can be cached locally and submitted again as part of the stable prefix.
Session and reuse strategy
For consecutive tasks in the same repository, reuse the same session ID and prefix template where possible. Across sessions, use a repository snapshot hash as the cache namespace to prevent different repositories from interfering with each other. If concurrent requests share a prefix, serialize the initial fill and then parallelize subsequent hits to prevent cache stampede.
Evaluating impact without tying to a specific model
Focus on three metrics: the share of tokens that hit the cache, the absolute number of uncached tokens, and the total input cost per task. In coding-agent scenarios with highly repetitive context, when the hit rate approaches its upper bound, cost is often only a small fraction—sometimes one-tenth or less—of treating everything as uncached. This is not model magic; it is the result of the harness engineering the cacheable prefix.
Boundary conditions in practice
Caches have capacity and TTL limits, so an excessively long prefix may be evicted. Keys and private content should not enter a shared cache. Billing and hit statistics should be based on the usage fields returned by the provider; client-side estimates are for reference only. When a repository undergoes a large-scale refactor, proactively invalidate the repository-layer cache to avoid incorrectly reusing a stale index.
Conclusion
A good harness gets cache hits right first. That means turning the unchanged parts into a long, stable prefix, compressing the changing parts into the shortest possible tail, and using deterministic assembly to guarantee byte-level consistency. This approach is model-agnostic and applies to any inference service that supports prompt caching. By normalizing session structure, ordering rules, and tool output once, developers can realize sustained cost advantages across many subsequent requests while maintaining task quality.
