Good Harness Design: Get Prompt Cache Hits Right First
This article explains why prompt caching is a foundational part of good AI agent harness design, using a real cost contrast where a roughly 50x difference came from eliminating repeated computation rather than cheaper models. It defines what prompt caching actually reuses, identifies five common cache killers at the harness layer, and lays out practical patterns for a cache-friendly design: layered context, append-only prompts, normalized tool schemas, externalized session state, and cache lifecycle tuning. It also covers how to measure prefix hit rate, prefix stability, and prefix version distribution, along with common misconceptions and boundaries around tenant isolation and provider differences. Readers will learn how to prioritize prefix stability before adding retrieval, memory, or multi-agent orchestration.
1. Start With a Cost Contrast
A widely discussed pattern in the industry is what happens when a certain class of high-throughput inference workload runs on an agent framework and the cumulative prompt cache hit rate is pushed close to 99.93%. Under the pricing model that was public at the time, roughly 947 million cached input tokens cost about $2.65; if those same tokens had been billed at the uncached rate, the cost would have been about $132.62. The two numbers differ by roughly 50x.
That gap should make developers pause on three points:
- The main source of the cost difference is not that the model itself became cheaper, but that repeated computation was eliminated.
- Once the hit rate is high enough, the billing structure shifts from “growing linearly with each conversation turn” to “close to a one-time prefix cost plus a small increment.”
- This benefit is not exclusive to any single framework; it is the natural result of prompt caching operating under the right engineering constraints.
So when we ask what a good harness should look like, the most practical starting point is not stacking on more plugins. It is getting the basics of cache hits right first.
2. First, Clarify What Prompt Caching Actually Caches
The prompt caching implemented across the industry rests on a simple idea: when the input prefix of a request is identical to that of a prior request, the inference service can reuse the internal state already computed for that prefix and only compute the new portion. This yields two kinds of benefits:
- Compute reuse: it skips repeated prefix computation and reduces time to first token.
- Billing discount: the cached portion is typically billed at a price significantly lower than uncached input.
The key point is that hit detection usually depends on an exact, token-by-token prefix match. This means a change in any single character can turn everything after it into a cache miss. Many teams see hit rates stuck at 30%–60% for a long time, not because the model does not support caching, but because the harness is unintentionally rewriting the prefix on every turn.
The detection logic can be abstracted schematically as:
If the longest common prefix length between the current input and a cached prefix = LThen the first L tokens hit, the rest missHit rate = hit tokens / total input tokens
From this we can derive an engineering rule of thumb: the upper bound of the cache hit rate is determined by prefix stability; the lower bound is determined by request frequency and lifecycle.
3. Five Common “Cache Killers” at the Harness Layer
3.1 Injecting Timestamps and Random Values Into the Prefix
Putting the current time, a random request ID, or a random greeting at the start of the system prompt makes the prefix different on every turn. The fix is straightforward: move all volatile values to the tail of the prompt or into the user message.
3.2 Dynamically Assembled System Prompts
Generating the system prompt dynamically based on user tier, region, or experiment group creates multiple coexisting prefixes. If the number of groups is manageable, this may be acceptable; if the combinations of grouping dimensions explode, the hit rate collapses quickly. The recommendation is to fix the stable parts and push the variable parts down into structured variables.
3.3 Unstable Tool Description Ordering
When the tool list comes from dictionary iteration, set deduplication, or concurrent assembly, the order can vary between processes. Tool schemas and description text must be serialized and sorted into a fixed order, for example by sorting on tool name before concatenation.
3.4 Lossless Rewriting of Historical Messages
Reprocessing historical messages with “compression, correction, formatting, or sensitive-word replacement” changes the prefix content. The correct approach is to append to historical messages only, never modify them; when a summary is truly needed, add it as an explicit new message rather than writing it back over old messages.
3.5 Coupling Session State With the Prompt
Writing mutable business state (cart, inventory, progress) into the system prompt makes the prefix change frequently with business activity. State should be externalized as tool return values or a structured data block placed at the tail of the conversation.
4. A Practical Cache-Friendly Harness Design
4.1 Layer the Context: Stable / Semi-Stable / Volatile
Arrange the input from highest to lowest stability:
[Stable layer] Role definition, output spec, safety policy, tool schema (sorted by name)[Semi-stable layer] Domain knowledge, long-term memory summary (low-frequency updates)[Volatile layer] Current user input, real-time retrieval results, business state snapshot
The benefit is that even if the volatile layer changes every turn, the stable layer still hits consistently, and the stable layer usually makes up the bulk of a long context.
4.2 Enforce an “Append-Only” Constraint on Prompts
The harness should enforce a rule: messages already written to the session cannot be changed, deleted, or reordered. All new information enters by appending. In engineering terms, you can add a read-only check at the session storage layer and reject any update operation outright.
4.3 Normalize Tools and Schemas
def render_tools(tools):# Fix the order to avoid prefix changes caused by concurrency or dict orderingreturn "\n".join(t.to_prompt() for t in sorted(tools, key=lambda x: x.name))
At the same time, tool description text should be placed under version control, and any change should be treated as a prefix version upgrade rather than a casual edit.
4.4 Externalize Session State
Put volatile state into a structured data block placed at the tail:
<state>{"cart_items": 3, "coupon": null, "step": 2}</state>
State updates happen through tool calls, while the prompt itself stays stable.
4.5 Cache Lifecycle and a Frequency Floor
Cache entries usually have a time-to-live window and need a certain reuse frequency to be retained. For low-frequency sessions, merge requests and reduce fragmented calls; for high-frequency sessions, fix the entry prefix and avoid multiple entry points each maintaining their own prefix.
5. How to Measure It: Build a Reproducible Hit-Rate Baseline
No measurement, no optimization. It is worth building three metrics into the harness:
- Prefix hit rate: hit input tokens / total input tokens.
- Prefix stability: the longest common prefix ratio between two adjacent requests.
- Prefix version distribution: the occurrence count and token share of each prefix version.
A minimal offline check script might look like this:
def prefix_hit_rate(prev_tokens, cur_tokens):n = 0for a, b in zip(prev_tokens, cur_tokens):if a != b:breakn += 1return n / max(1, len(cur_tokens))
During a canary rollout, use “prefix stability” as a release gate: block the launch if it falls below the threshold. This is more effective than reviewing the bill after the fact.
6. Common Misconceptions and Boundaries
- Misconception 1: assuming a higher hit rate is always better and pursuing it without limit. In reality, over-fixing the prefix sacrifices personalization, so you need to balance hit rate against output quality.
- Misconception 2: treating the cache as a cross-tenant sharing mechanism. Cache reuse must strictly respect tenant isolation and data boundaries, and isolation must not be broken in the name of optimization.
- Misconception 3: ignoring provider differences. Different inference services differ in cache granularity, TTL windows, and billing models, so the engineering implementation should stay configurable and avoid tight coupling to a single implementation.
- Boundary note: for billing and caching rules, defer to the official documentation of the service you use; this article makes no specific numerical commitments.
7. Conclusion: Get the Basics Right and the Gains Follow
Back to the opening cost contrast: the 50x gap did not come from a complex trick, but from the plain constraint of “keep the prefix unchanged” being strictly enforced. For harness designers, the priority should be: first fix the prefix structure, then introduce retrieval and memory, and only then consider multi-agent orchestration. Reversing that order usually trades higher complexity for a lower hit rate.
When a team turns cache hits into a foundational capability that is measurable, gateable, and regression-testable, long-session cost, time to first token, and capacity planning all fall into a controllable range. That is the real meaning of “a good harness gets cache hits right first.”
