Building a Better Agent Harness: Get Cache Hits Right First
This article explains why prompt cache hit rate is the first engineering priority for an AI agent harness, the execution framework that carries model calls. It covers how prefix-based caching works, how to layer context into stable and volatile parts, how to keep prompts and tool schemas deterministic across turns and parallel sub-agents, which metrics to collect, common pitfalls, and a practical implementation checklist for lowering cost and latency.
Building a Better Agent Harness: Get Cache Hits Right First
Why Cache Hits Come First
The harness — the execution framework that carries model calls — has moved from a fringe concept to a core engineering object that decides whether an agent succeeds. The reason is not mysterious: every agent inference is not an isolated request but a continuous stream of calls carrying a large amount of repeated context. When the framework reliably reuses those repeated parts, the cost per task can drop by an order of magnitude, and response latency converges as well.
The most direct business reason is one sentence: save money. A representative observation from public industry discussion reported a cumulative cache hit rate of 99.93% when running a certain model on a certain execution framework: roughly 947 million hit input tokens were billed at about $2.65, while the same tokens at the miss price would have cost about $132.62 — a difference of roughly 50x. This is a public observation from a specific scenario; billing rules and hit conditions differ across vendors and cannot be generalized into a universal benefit. But the underlying pattern is universal: in long-context, multi-turn tool-calling workloads, repeated computation on the input side usually dominates cost, and that overhead can be removed architecturally.
So for an excellent harness, the first priority is not fancy planning ability but treating context reusability as a first-class design concern.
First, Clarify the Concept: What Is Actually Being Hit
Most inference services apply a prefix-reuse strategy to input tokens: when the beginning of a new request matches already-cached content exactly, that prefix does not need to be recomputed and is billed at the hit price. Three engineering constraints follow:
- Hits are prefix-based; once a difference appears at any position, everything after it degrades to a miss.
- Hits depend on content identity, not semantic similarity; rewriting, reordering, and timestamps all break them.
- Hits usually have a lifetime, governed by server-side cache capacity and retention policy, and need re-warming after a long idle period.
Understanding these three points explains a lot of cases where “the context did not change, but the hit rate is still low.”
Layer the Context: Separate Stable from Volatile Completely
The core technique for improving hit rate is layering. Divide context into four layers and keep the order fixed:
- Global layer: system instructions, output specifications, safety policies, tool inventory, and JSON Schema definitions.
- Domain layer: project structure notes, coding conventions, glossary, long-term knowledge.
- Session layer: user goals, confirmed constraints, summaries of intermediate conclusions.
- Incremental layer: the most recent turns, tool return results, temporary observations.
The key principle: the more stable the content, the earlier it goes; the more volatile, the later. A schematic structure:
[Global layer: stable, managed by version number][Domain layer: evolves with the repository, low-frequency updates][Session layer: medium-frequency updates, append rather than rewrite][Incremental layer: high-frequency changes, length controlled]
A common counter-example is putting the current time, a random request ID, or a retry counter at the top of the system instructions. Such fields change every turn and permanently prevent everything after them from hitting, at a very high cost. If they must be carried, push them to the end of the incremental layer, or render them client-side with placeholders.
Stability Discipline for Prompts and Tool Descriptions
- Versioning: the global and domain layers carry explicit version numbers and are replaced wholesale on change, not tweaked in place.
- Fixed ordering: sort tool lists, examples, and enum items by a stable rule; never use random iteration order over a collection.
- No meaningless jitter: do not inject random numbers, UUIDs, or the current millisecond timestamp into a stable prefix.
- Batch changes: merge multiple small edits into a single version upgrade to reduce cache rebuilds.
- Trim redundancy: repeated phrasing wastes budget and adds inconsistency risk; consolidate it into a single authoritative passage.
Tool definitions are especially easy to overlook. Many frameworks generate tool descriptions dynamically before every call, with field order determined by hash traversal results, so the prefix differs every turn. Fixing the serialization of tool schemas is often the single change that improves hit rate the most.
Reuse Strategies for Multi-Turn and Multi-Agent Scenarios
Multi-turn conversations should keep an append-only, never-rewrite history strategy. When history must be compressed, use a structured summary written into the session layer instead of rewriting the whole history text; once a summary is generated, keep it byte-for-byte identical in later turns.
Parallel sub-agents should share the same global and domain layers and diverge only in the incremental layer. That way multiple branches reuse the same prefix instead of each rebuilding it. For repository information or retrieval results that are read frequently, normalize first (remove whitespace differences, unify line endings, fix ordering) before concatenating into the context, avoiding false misses caused by “same content, different bytes.”
Metrics: No Measurement, No Optimization
You must be able to observe before optimizing. Collect at least these metrics:
- Hit rate: hit input tokens / total input tokens.
- Effective prefix length: deviation of the stable layers’ actual byte count from the expected value.
- Miss attribution distribution: content change, idle expiration, over-length truncation, ordering jitter.
- Cost per task and P95 latency, to verify that optimization did not come at the expense of quality.
A schematic statistics implementation:
class CacheStats:def __init__(self):self.hit = 0self.miss = 0def record(self, usage):self.hit += getattr(usage, "cached_tokens", 0)self.miss += usage.prompt_tokens - getattr(usage, "cached_tokens", 0)@propertydef hit_rate(self):total = self.hit + self.missreturn self.hit / total if total else 0.0
Note that different services name the hit fields differently and count them differently; rely on the usage information actually returned and do not assume a universal field exists.
Common Pitfalls
- Pitfall 1: assuming semantic similarity is enough to hit. In reality it is byte-by-byte prefix matching.
- Pitfall 2: putting dynamic content at the beginning, which invalidates the entire block.
- Pitfall 3: frequently fine-tuning prompts, causing repeated cache rebuilds.
- Pitfall 4: watching only hit rate without monitoring task success rate and latency, ending up “cheaper but dumber.”
- Pitfall 5: assuming the cache lasts forever and ignoring idle expiration; long tasks need one warm-up call first.
Implementation Checklist
- Draw a context layering diagram and annotate each layer’s update frequency.
- Freeze the serialization order of tool schemas and examples.
- Push timestamps, random values, and retry information to the end or remove them.
- Maintain history in append-only fashion; compress via structured summaries.
- Wire up dashboards for hit rate, miss attribution, and cost.
- Build a regression evaluation: after each prompt or tool description change, watch both hit rate and task success rate.
- Add warm-up and keep-alive strategies for long-idle scenarios.
Conclusion
Cache hits are not an exclusive capability of any particular model but an engineering discipline at the harness level. Separate stable from volatile, batch changes, and complete the measurement, and the cost curve will naturally trend down. Order matters: get hits solid first, then talk about planning, reflection, and multi-agent collaboration — only then do the gains actually show up on the bill. To carry this capability in the cloud, you can combine general-purpose components such as container platforms, logging services, and monitoring and alerting to build an observable, regression-testable loop of continuous optimization.
