Good Harness Design: Get Prompt Caching Right First
This article explains why prompt cache hit rate, not model price, is the dominant driver of input-side cost in AI agent applications. It covers how prefix caching works, the engineering constraints it imposes, and why the harness (the agent's orchestration layer) is the first line of responsibility for cache reuse. You will learn a four-layer context design that separates stable content from volatile content, deterministic tool and schema governance, session orchestration aligned with cache TTL windows, the metrics worth instrumenting, common anti-patterns with fixes, and a practical launch checklist.
1. Starting With a Cost Contrast
A set of figures circulating in the technical community illustrates the point well: an AI coding tool running a general-purpose large model reported a cumulative prompt cache hit rate of 99.93%. Under published pricing, roughly 947 million cached input tokens cost about $2.65; the same tokens at non-cached rates would cost about $132.62 — almost exactly a 50x difference.
The real value of these numbers is not that things got “50x cheaper.” It is that they expose a frequently overlooked engineering fact: in agentic applications, the dominant variable on the input side is not the model’s unit price but the cache hit rate. Model capability, context length, and tool count are hard to change significantly in the short term, but the cache hit rate is a metric determined entirely by the caller’s architecture. In other words, more than half of the bill is in the hands of the harness itself.
This article discusses no specific product. Instead, it abstracts the issue into a general technical question: how do you design a harness so that prompt caches are reused as much as possible?
2. How Prompt Caching Generally Works
Mainstream large model services commonly offer “prefix caching,” whose matching logic can be abstracted as follows:
- The prefix of the request input sequence is used as the key, compared segment by segment starting from the first position of the token sequence;
- The hit length is the longest common prefix; once a difference appears at any position, everything after it counts as a miss;
- The hit portion is billed at a price significantly lower than normal input, while the missed portion is billed at the normal rate;
- Cache entries have a time-to-live (TTL), usually on the order of minutes, and expire after being idle.
From this, three hard engineering constraints follow:
- The prefix must be byte-for-byte stable. Timestamps, random IDs, request sequence numbers, usernames, floating-point formatting differences — any single fluctuation invalidates the entire cache from that position onward.
- Stability takes priority over “importance.” Putting volatile content at the front, even if it is only a few dozen tokens, invalidates tens of thousands of tokens of cache that follow.
- The hit window is time-sensitive. Sending a request after a long idle period is effectively a cold start.
Once you understand these three points, it becomes clear why “getting cache hits right first” is a prerequisite of harness design rather than an afterthought optimization.
3. Why the Harness Is the First Owner of the Hit Rate
A typical agent main loop reassembles the context every turn: system instructions, tool definitions, long-term memory, retrieved snippets, message history, and the current observation. If the assembly logic is “regenerate the string every turn,” the hit rate will inevitably collapse.
Common unfriendly patterns include:
- Embedding dynamic fields such as the current time, session ID, or remaining budget in the system prompt;
- Tool descriptions generated automatically via code reflection, with field order unstable due to hash traversal;
- Retrieval results (RAG snippets) inserted before the message history, shifting the entire prefix each turn;
- Message history “summarized and compressed” and written back each turn, rewriting the already-cached historical prefix;
- Retries and fallbacks that change the prompt wording, causing the prefix to fork.
Each of these looks small on its own, but together they can push the hit rate from 90% down below 30%. The core design goal of the harness should therefore be explicit: make the longest common prefix of each turn’s request as long as possible.
4. Layering the Context: Fully Separating Stable From Volatile
A recommended approach is to divide the context into four layers, strictly ordered by decreasing stability:
[L1 Constant layer] System role, safety policy, output spec, examples (versioned, changed with releases)[L2 Tool layer] Tool names, parameter schemas, invocation constraints (fixed ordering, frozen descriptions)[L3 Session layer] User goal, confirmed constraints, structured summary of completed steps[L4 Volatile layer] Current observation, tool returns, timestamps, retrieved snippets, temporary drafts
Key engineering rules:
- L1 and L2 are frozen once shipped; changes go through version numbers, with no in-place editing;
- L3 uses append-only updates: only new structured entries may be added at the end, with no rewriting, reordering, or compressing of existing content;
- L4 always goes last, with controlled length;
- When long-term memory is needed, use “retrieved results as L4 snippets” instead of “rewriting history,” to avoid breaking the prefix.
A sketch of append-only session history:
def build_prompt(session, observation):parts = [SYSTEM_PROMPT_V3, # L1: constant, switched by versionTOOL_BLOCK_V7, # L2: frozen tool descriptionssession.append_only_log, # L3: append only, never rewrittenrender(observation), # L4: added this turn]return "\n".join(parts)
5. Deterministic Governance of Tools and Schemas
The more tools there are, the more easily the tool layer becomes a cache killer. Recommended practices:
- Serialize tools after sorting by name in lexicographic order; never rely on the traversal order of dicts or sets;
- Put description text under version control, generated and hash-verified at build time, with no dynamic content concatenated at runtime;
- Use stable serialization for parameter schemas (sorted keys, no default-value drift);
- Apply “full replacement plus version number” for tool set changes, rather than dynamically adding or removing tools based on usage;
- If the tool count really is large, use tiered loading: core resident tools in L2, long-tail tools injected at L4 via retrieval.
An example of build-time freezing:
import json, hashlibdef freeze_tools(tools):ordered = sorted(tools, key=lambda t: t["name"])blob = json.dumps(ordered, sort_keys=True, ensure_ascii=False)digest = hashlib.sha256(blob.encode()).hexdigest()[:8]return blob, f"TOOL_BLOCK_V{digest}"
If the build-time hash does not change, the runtime prefix does not change.
6. Session Orchestration Aligned With the Cache Window
The hit rate depends not only on content but also on timing:
- Keep it warm: maintain a request cadence within the TTL window to avoid cold starts after long idle periods; for interactive scenarios, a keep-alive strategy can be configured.
- Batch and merge: combine multiple small requests into one larger request to reduce prefix rebuilds.
- Share prefixes across parallel branches: multi-branch tasks should share the same L1/L2 prefix and fork only at L4, rather than each branch building its own system prompt.
- Do not rewrite on retry: a failed retry must reuse exactly the same input, adjusting only sampling parameters — never “try a different phrasing.”
- Defer summarization: when history must be compressed, append the summary as a new L3 entry and leave the original history untouched, or start a new session segment entirely.
7. Measurement: No Metrics, No Optimization
Optimizing the cache requires observability. It is recommended to instrument the harness to collect the following fields (using only generic billing/usage semantics, with no vendor-proprietary interfaces):
{"session_id": "s-1024","turn": 17,"input_tokens": 42130,"cached_input_tokens": 42088,"cache_hit_ratio": 0.999,"prefix_version": "SYS_V3|TOOL_V7","idle_ms": 8200}
Core metric definitions:
- Hit rate = cached input tokens / total input tokens;
- Prefix fingerprint: a hash over L1+L2, used to confirm whether the version has drifted;
- Idle duration: pinpoints gaps caused by TTL expiry;
- Fork rate: measures where the longest common prefix of each turn decays relative to the previous turn.
With the fork position, you can precisely determine whether the cause is system prompt jitter, a change in tool ordering, or an incorrect insertion position for retrieved snippets.
8. Common Anti-Patterns and Their Fixes
| Anti-pattern | Consequence | Fix |
|---|---|---|
| Current time in the system prompt | Prefix fails at the very first position | Move the time into L4 |
| Rewriting the history summary every turn | Entire historical prefix invalidated | Switch to append-only summary entries |
| Retrieved snippets inserted before history | Everything shifts | Put retrieval results at the end |
| Dynamically concatenated tool descriptions | Tool layer jitter | Freeze at build time plus version number |
| Changing wording on retry | Prefix forks | Reuse the input exactly |
| Continuing after a long idle period | Cache expired | Keep-alive or merge requests |
9. Implementation Checklist
- Are L1/L2 versioned and frozen at build time?
- Is session history strictly append-only and never rewritten?
- Are all volatile fields at the end of the context?
- Is tool serialization sorted with stable key order?
- Are cached tokens, prefix fingerprint, and idle duration being collected?
- Do parallel branches share the same prefix?
- Does the retry path guarantee byte-identical input?
- Are keep-alive or request-merging strategies configured within the cache window?
10. Conclusion
A 99.93% hit rate is not a proprietary feature of some model; it is a direct reflection of harness engineering quality. Once input-side cost is compressed by one to two orders of magnitude, teams can reinvest the budget into longer contexts, more thorough reasoning, and more complex tool orchestration — that is the real payoff of “getting cache hits right first.” Order matters: make the prefix stable first, then talk about model selection and capability expansion.
