Building a Better Agent Harness: Start by Getting Cache Hits Right
This article explains why prompt caching is the first optimization target for a mature agent harness. It breaks down how a request moves through prefill and decode, how KV Cache reuse works on the provider side, and why a stable token-by-token prefix determines the hit rate. It also presents an illustrative cost model showing the leverage of higher hit rates, five engineering practices for improving them, and common misconceptions to avoid.
1. The Problem: Repeated Computation Inflates Agent Costs
A common shorthand in the industry describes an agent system as: Agent = Model + Harness. The model handles reasoning and generation, while the harness (the runtime framework) assembles the system prompt, tool definitions, project notes, conversation history, and user input into a single request the model can process, and manages the multi-turn loop, tool calls, and result回填.
As agents take on longer tasks, the genuinely new information in a single session is often a small fraction of the total input, while most of it is recurring shared content. If that content is recomputed from scratch every time, compute and cost are amplified for no reason. A mature harness therefore has to get cache hits right first.
When a business leader evaluates whether to invest in this optimization, the most direct answer is also the simplest: it saves money. With the same model and the same task, improving only how requests are organized can compress the compute cost of repeated input by an order of magnitude.
2. How It Works: What Happens During a Request
Processing a request in a large model can be roughly divided into two phases.
The first phase is prefill. The model reads the system prompt, tool definitions, project notes, conversation history, and the new question in turn, computing the intermediate state of each token across the attention layers. This phase scales with input length and is usually the main cost driver in long-context scenarios.
The second phase is decode. After understanding the context, the model generates the answer token by token. This phase scales with output length and is constrained by single-generation speed.
In the attention mechanism of each Transformer layer, tokens that have already been read form Key and Value vectors. These computed and stored intermediate states are the KV Cache. It is neither the previous answer nor readable text; it is closer to the “computational notes” the model leaves behind after reading the material: if a later request has an identical opening, those notes can in principle be reused directly, and only the new content needs to be computed.
It is worth stressing that KV Cache reuse happens on the provider side, and the caller cannot read or modify it directly. What engineering can do is increase the likelihood that reuse is possible.
3. The Key Concept: Why the Prefix Determines the Hit Rate
Requests issued by an agent are usually concatenated in this order:
[system prompt][tool definitions][project notes][conversation history][new message this turn]<---------- reusable shared prefix ----------><-- new suffix -->
The prefix is a continuous stretch of content that is completely identical from the very first token. It is not keyword matching, nor is it “semantically similar”: the content forms a shared prefix only when two requests match token by token from the beginning to the same position. Once a difference appears at any position, everything after it usually has to be recomputed along a new path.
For example:
Turn N: A + B + CTurn N+1: A + B + C + D → A, B, C are reusable; only D is computedIf B changes: A + B' + C + D → everything from B' onward must be recomputed
This leads to a core conclusion: prompt caching is first a game of “matching answers from the start.” The more stable the opening, the longer the reusable prefix; the earlier a change appears, the more content has to be recomputed afterward.
4. The Cost Model: The Leverage Effect of the Hit Rate
Providers price cached and uncached input differently, but the general pattern is that the unit cost of the hit portion is significantly lower than that of the miss portion. This creates a nonlinear leverage effect: a few percentage points of improvement in the hit rate can cut the bill several times over.
An illustrative model makes this clear (the numbers are for explanation only and do not represent any specific pricing):
Let the miss unit price be P and the hit unit price be P/50Total input tokens: 1,000,000, hit rate hCost = 1,000,000 × [h × P/50 + (1-h) × P]h = 0% → 1,000,000 Ph = 90% → 118,000 Ph = 99% → 21,800 P
Going from 90% to 99% cuts cost by roughly another 80%. This is exactly why long-session agents are worth investing engineering resources in: the longer the session and the more turns, the more pronounced the compounding effect.
5. Engineering Practice: How to Systematically Improve the Hit Rate
5.1 Keep the Prefix Stable: Push Volatile Content to the End
Put low-churn content such as the system prompt, tool schemas, and project notes at the front, and high-churn content such as timestamps, random IDs, and this turn’s retrieval results at the end. Any dynamic variable injected into the middle invalidates everything after it.
5.2 Context Governance: Control “Meaningless Change”
- Deduplicate tool definitions and fix their ordering, so re-serialization each turn does not cause order drift;
- Maintain history messages in append-only fashion, avoiding in-place rewrites or summary replacement of existing content;
- In retrieval-augmented scenarios, deduplicate and trim before concatenation to reduce wasted tokens.
5.3 Sessions and Routing: Send the Same Prefix Down the Same Path
In multi-tenant or split-line scenarios, requests that share the same system prefix should follow a consistent model and configuration path, so that model version, temperature, and system version do not drift mid-session.
5.4 Observability: Measure First, Then Optimize
The harness should log input tokens, cached tokens, uncached tokens, and cumulative hit rate for every turn, feeding a trend dashboard and alerts. Without measurement, optimization is guesswork.
metrics:input_tokens_totalcached_tokens_totalcache_hit_ratio = cached / inputprefix_stability = shared prefix length with previous turn / input length
5.5 Fallback: A Hit Is Not a Prerequisite for Correctness
Caching affects only performance and cost, not semantics. Any optimization that depends on caching must guarantee that the output remains correct even at a 0% hit rate. Never treat “cache is available” as a precondition for business logic.
6. Common Misconceptions
- Misconception 1: thinking that the answer is cached. What is actually cached is the attention intermediate state, which has nothing to do with the output.
- Misconception 2: thinking that semantic equivalence is enough for reuse. It must match token by token.
- Misconception 3: optimizing only on the model side. The way the harness organizes requests often has a bigger impact.
- Misconception 4: chasing 100% hits at the expense of quality. Stability should be bounded by not harming task quality.
7. Conclusion
In an agent system, the model sets the ceiling on capability, while the harness determines whether that capability can be delivered efficiently, reliably, and economically. The cache hit rate is an excellent entry point: it connects cost, latency, and engineering discipline at once. Get the prefix stable, keep context governance clean, and make the metrics transparent, and large-scale agent deployment finally has a reliable foundation.
