Good Harness Design: Maximize Cache Hits First

    This article explains why input cache hit rate is the first-order cost variable in long-context, multi-turn AI agent workloads, and how to design the Harness—the context assembly and scheduling layer around model calls—to maximize it. It covers the asymmetry of cached versus uncached input pricing, six common root causes of low hit rates, a four-layer context design (L0–L3) with append-only and stable-serialization rules, scheduling actions such as request batching, cache keep-alive, session affinity routing, and summarization, plus the metrics needed to verify optimization. A four-stage rollout plan and common pitfalls are included.

    1. Starting from a Cost Observation

    In agentic applications, input-side spending usually dominates the total cost structure. One reported result from running a high-throughput model in an AI coding tool: a cumulative cache hit rate of 99.93%. Under the pricing published at the time, roughly 947 million cached input tokens cost about $2.65, while the same tokens at the uncached rate would have cost about $132.62—almost exactly a 50x difference.

    The number itself is not mysterious. It exposes a long-underestimated engineering fact: in long-context, multi-turn agent workloads, the first-order cost variable is not “how expensive the model is” but “whether the context can be reused.” For the same task, a well-designed Harness (the context assembly and scheduling layer that carries model calls) and a poorly designed one can differ by one to two orders of magnitude on the bill.

    This article discusses no specific product or vendor. Instead, it abstracts the phenomenon into a reusable engineering methodology: the first step of a good Harness is not fancier planning capability, but maxing out cache hits.

    2. Why Cache Hit Rate Becomes a First-Order Cost Variable

    2.1 The Pricing Asymmetry on the Input Side

    Most mainstream LLM services use three-part pricing: cached input / uncached input / output. Cached input typically costs only a fraction to one-tenth of uncached input. This means:

    • Uncached tokens are “full-price goods”; cached tokens are “discounted goods.”
    • When the context reaches hundreds of thousands of tokens and every turn re-carries the system prompt, tool definitions, and history, the uncached portion is billed at full price repeatedly.
    • Output tokens cannot be cached, so nearly all optimization headroom sits in the input prefix.

    2.2 Agent Workloads Are Naturally “Highly Repetitive in the Prefix”

    A typical agent loop looks like this:

    1. system prompt + tool schema + long-term memory
    2. + message history (m1..mn)
    3. + current observation
    4. -> model inference -> tool call -> new observation -> request again

    On every request, almost everything before the tail is repeated verbatim; only a new observation and reasoning result are appended at the end. This “append-only, rarely modified” access pattern is the ideal input for prefix caching. In other words, agent workloads have inherently high caching potential. If the hit rate stays low, it is usually a Harness implementation problem, not a workload problem.

    3. Six Root Causes of Low Hit Rates

    3.1 The Prefix Is Polluted by Timestamps or Random Values

    The most common killer is injecting the current time, a random request ID, or a randomly ordered candidate list into the system prompt or tool descriptions. A single changed character invalidates the entire prefix cache.

    3.2 Unstable Context Ordering

    Placing volatile content (the user’s latest input, retrieval results) before stable content (system rules, tool definitions) makes the prefix different on every request. The correct order is: the more stable, the earlier.

    3.3 Frequently Changing Tool Definitions and Parameter Descriptions

    The JSON serialization order of tool schemas, optional-field pruning strategies, and adding or removing tools dynamically per scenario all change the prefix bytes.

    3.4 Cache Lifetime Mismatched with Request Intervals

    Caches usually have a time-to-live window. If tool execution takes long or a human confirmation waits a while, the cache may already have expired, and the next turn becomes a full uncached miss.

    3.5 Multiple Sessions or Tenants Sharing the Same Prefix

    Contexts from different users, repositories, or permission scopes are concatenated into one prefix, so cache keys cannot be shared and the hit rate is diluted.

    3.6 No Metrics, No Attribution

    Without tiered hit-rate and token attribution reports, teams can only reverse-engineer from the bill, and optimization becomes guesswork.

    4. A Practical Layered Caching Design

    Split the context explicitly into four layers, each with its own stability level and caching strategy:

    Layer Content Stability Strategy
    L0 Global Safety policies, output specs, general tool descriptions Very high Shared across all tenants, version-controlled
    L1 Session Task goals, constraints, long-term memory summaries High Reused within a session; reused across sessions by summary
    L2 Trajectory Historical reasoning and tool call records Medium Append-only, no write-back modification
    L3 Transient Current observation, retrieval snippets, temporary variables Low Placed at the end, allowed to change

    The accompanying hard rules:

    1. Append-only, no modification: once L0–L2 are generated they are frozen; all new information is appended at the end.
    2. Volatile content goes last: time, random numbers, and retrieval results may appear only in L3.
    3. Stable serialization: tool definitions use a fixed field order and fixed sorting rules.
    4. Prefix fingerprint checks: compute a hash per layer and compare before each request; alert as soon as a fingerprint changes.

    Illustrative implementation:

    1. import hashlib, json, time
    2. class PrefixBuilder:
    3. def __init__(self):
    4. self.l0, self.l1, self.l2 = [], [], []
    5. self.fingerprints = {}
    6. def _fp(self, parts):
    7. raw = json.dumps(parts, ensure_ascii=False, sort_keys=True)
    8. return hashlib.sha256(raw.encode()).hexdigest()[:16]
    9. def build(self, transient):
    10. stable = self.l0 + self.l1 + self.l2
    11. fp = self._fp(stable)
    12. if fp != self.fingerprints.get("stable"):
    13. # The stable prefix was modified, the cache will be invalidated as a whole, locate it immediately
    14. self.fingerprints["stable"] = fp
    15. self.on_prefix_drift(fp)
    16. return stable + transient # volatile content always goes last
    17. def on_prefix_drift(self, fp):
    18. # Hook into the logging service and monitoring alerts, output the drift source
    19. log_event("prefix_drift", fp, time.time())

    5. Four Key Actions at the Scheduling Layer

    5.1 Request Batching and Coalescing

    Merge parallel tool call results into a single append, reducing the number of request turns and therefore the chances of the prefix being recomputed.

    5.2 Cache Keep-Warm for Long Tasks

    For tools expected to run long, use “short polling + heartbeat requests” to keep the cache alive, or split the long task into multiple short segments and issue the next request immediately after each segment ends.

    5.3 Session Affinity Routing

    Under multi-instance deployment, route the same session to the same instance consistently so the cache does not land on another node. This can be implemented with the session persistence capability of the container platform or hash-based routing at the gateway layer.

    5.4 Context Compression and Summarization

    When the trajectory grows too long, summarize and compress L2 and re-freeze it into a new stable prefix. Note that the compression action itself causes one cache invalidation, so run it in batches and at low frequency.

    6. Metrics: Making Optimization Verifiable

    No metrics, no optimization. Collect at least the following and wire them into your logging service and monitoring alerts:

    • Cumulative hit rate = cached input tokens / total input tokens;
    • Prefix drift count: how often stable-layer fingerprints change; the ideal value is close to 0;
    • Cache expiration rate: the share of misses caused by intervals that are too long;
    • Per-task input cost: attributed per task rather than only looking at the total bill;
    • Time to first token (TTFT): higher hit rates usually come with lower TTFT, serving as cross-validation.

    A simple attribution dashboard logic:

    1. Total input cost = cached tokens × cached price + uncached tokens × uncached price
    2. Optimization goal = minimize uncached tokens while task success rate does not drop

    7. Common Pitfalls

    1. Assuming “more context is always better”: redundant content both raises uncached cost and dilutes attention, so subtract.
    2. Treating the cache as a correctness dependency: caching is only a performance and cost optimization; business correctness must be guaranteed by external state and validation.
    3. Only tuning prompts, not the Harness: no matter how good the prompt is, if the order is wrong and the timestamp is still there, the hit rate will not go up.
    4. Ignoring multi-tenant isolation: shared prefixes must align with permission boundaries, otherwise you introduce data cross-use risk.
    5. One big-bang rewrite: first use fingerprints and reports to locate a single drift source, then fix items one by one and verify by regression.

    8. A Suggested Rollout Path

    • Phase 1 (1–2 days): wire up hit-rate and drift metrics, remove pollution sources such as timestamps and random values;
    • Phase 2 (3–5 days): re-layer the context, freeze L0/L1, fix tool definition serialization;
    • Phase 3 (1 week): add session affinity routing, long-task keep-warm, and summarization compression;
    • Phase 4 (ongoing): do per-task cost attribution and regression, and make hit rate part of the release gate.

    9. Conclusion

    A 99.93% hit rate and an roughly 50x cost gap are not a victory of model capability but a victory of engineering discipline. Put stable content first and freeze it, put volatile content last, factor cache lifetime into scheduling, and make hit rate an observable metric—do these four things and cache hits will be “maxed out” naturally. As agent workloads become mainstream, Harness maturity is becoming the dividing line between a team’s cost and user experience.