AI Agent Framework Optimization: Get Prompt Cache Hits Right First
Prompt cache hits can substantially reduce the cost and latency of AI agent workloads. This article explains how reusable prefixes work, which context-building patterns undermine caching, and how layered, append-only prompts, stable serialization, and regression testing make cache efficiency a repeatable engineering practice.
1. Start with Cache Hits: A High-Return Optimization
Why spend engineering effort improving prompt cache hit rates? The simplest answer is that caching saves money—and often makes responses faster.
An anonymized, publicly shared implementation illustrates the potential. An agent runtime calling a large language model service achieved a cumulative input-token cache hit rate of 99.93%. Under the publicly listed pricing at the time, approximately 947 million cached input tokens cost about $2.65. If those same tokens had been billed at the uncached rate, they would have cost approximately $132.62—a roughly 50-fold difference.
The example highlights a structural feature of agent workloads: input tokens often greatly outnumber output tokens, and much of the input consists of repeated shared prefixes. Multi-turn tool calls, lengthy project instructions, and substantial tool definitions are submitted again on every turn. Without reuse, their cost accumulates approximately linearly with the number of interaction rounds.
Cache hits offer two benefits:
- Lower cost: Cached input tokens typically have a substantially lower price than uncached tokens. A high hit rate can fundamentally change the composition of the bill.
- Lower latency: Reusing a cached prefix avoids recomputing its attention states in full. Time to first token often falls, making interactions feel more responsive.
For an effective agent framework, or harness, reliable prompt caching should come before elaborate planning features.
2. Request Structure: A Reusable Prefix and a New Suffix
A model request can be roughly divided into two parts:
[System prompt][Tool definitions][Project instructions][Conversation history][New messages]<----------------------- Reusable prefix ---------------------------------><-- New suffix -->
- Reusable prefix: The system prompt, tool and interface definitions, project-level instructions, and conversation history through the previous turn. Much of this content remains stable within a session, and some may also be shared across sessions.
- New suffix: The current user input, newly returned tool results, and any newly added reasoning or decision content.
Prefix caching generally works by matching the input token sequence against a previously processed prefix. The server reuses computed intermediate states for the matching portion and processes the new suffix.
Three engineering constraints matter:
- Order matters. Matching proceeds token by token from the beginning of the sequence. Keep the prefix text identical, including whitespace and line breaks.
- Changes have a cascading effect. A difference anywhere in the prefix can make the content from that point onward ineligible for reuse.
- Caches have a finite lifetime. Idle periods, concurrent scheduling, or backend instance changes may invalidate an established prefix.
These constraints lead to a simple principle: make the reusable prefix as long and stable as possible, and establish it early.
3. Common Patterns That Break Cache Hits
Poor cache hit rates often come from how a framework assembles prompts rather than from the model itself. Common anti-patterns include:
- Putting volatile content first. Timestamps, request IDs, random values, or user time zones at the beginning of the system prompt change the prefix on every request.
- Inserting dynamic reminders into earlier history. Adding messages such as “the working directory has changed” or “N commands have been executed” in the middle of the conversation disrupts reuse of everything that follows.
- Unstable tool-definition order. Tool lists assembled by iterating over hash tables or sets may change order. Randomly generated identifiers inside tool schemas create similar problems.
- Inconsistent serialization. JSON key order, floating-point formatting, or Unicode normalization may vary between turns.
- Rewriting history instead of appending to it. Summarization, trimming, and corrective edits alter the existing prefix. Summarization is still useful, but the result should establish a new stable layer, rather than patching the old prefix in place.
- Nondeterministic ordering of parallel tool results. Appending results in completion order causes their sequence to vary.
- Inlining large, changing objects. Full file contents, logs, and retrieval results increase both token volume and the amount of content that can change.
4. Build Context in Layers: Treat Prompts as Versioned Artifacts
Divide context into three explicit layers and follow an append-only approach:
| Layer | Content | Stability | Update policy |
|---|---|---|---|
| L0: Static | Role instructions, output requirements, safety constraints | Stable across sessions | Update with a version release |
| L1: Session | Tool definitions, project instructions, repository conventions | Stable within a session | Establish at session initialization |
| L2: Turns | User inputs, tool results, new decisions | Grows each turn | Append only; do not rewrite |
The following pseudocode illustrates the structure:
class ContextBuilder:def __init__(self):self.l0 = [] # Static layer: reused across sessionsself.l1 = [] # Session layer: reused within a sessionself.l2 = [] # Turn layer: append new content onlydef set_session(self, tools, project_notes):# Use stable sorting to prevent order changesself.l1 = [render_tools(sorted(tools, key=lambda t: t.name)),normalize(project_notes), # Standardize whitespace and line breaks]def append_turn(self, user_msg, tool_results):# Order parallel results by invocation, not completionordered = [r for _, r in sorted(tool_results, key=lambda x: x[0])]self.l2.append(render_user(user_msg))self.l2.extend(render_tool_result(r) for r in ordered)def render(self):# Fixed order: static -> session -> turns; volatile state stays at the endreturn self.l0 + self.l1 + self.l2
Apply three supporting rules:
- Keep volatile information at the end. Timestamps, counters, and working-directory changes belong at the end of L2, never in L0 or L1.
- Reference large objects instead of embedding them. Store files, logs, and retrieval results externally, such as in object storage. Keep stable references and summaries in the history, and retrieve the underlying content when needed.
- Version every L0 or L1 change. Treat modifications to either layer as a new version. Rebuild the prefix rather than patching it in place, then warm the rebuilt prefix to reduce uncached work for the first requests.
5. Measure Cache Hits as a Regression Metric
Cache efficiency needs to be measurable. At a minimum, collect:
- Overall cache hit rate: Cached input tokens divided by total input tokens.
- Hit rate by call category: Break results down by the main agent loop, subtasks, and summarization tasks to identify sources of poor reuse.
- Invalidation events: Record where prefix fingerprints change and why. These are direct clues for troubleshooting.
- Cost correlation: Calculate cached and uncached token charges separately, then relate those costs to business metrics.
- Latency correlation: Track time to first token alongside total input size.
Collect these fields through a centralized logging service and configure alerts when cache hit rates fall below a chosen threshold.
Add a prefix-stability regression test to CI as well: render the same session context twice and verify that L0 and L1 remain identical.
assert render(ctx).l0_l1_hash == previous_l0_l1_hash
6. Conclusion
Prompt cache efficiency is largely a context-assembly problem. Layer the context, move volatile information to the end, replace large embedded objects with references, and version changes to stable layers. These practices help keep cache hit rates high and consistent.
Combined with measurement and regression testing, caching becomes a sustainable engineering capability rather than a one-off tuning exercise. Get this foundation right before investing heavily in planning, memory, or multi-agent coordination: it can offer a much stronger return on engineering effort.
