Building Efficient AI Agent Frameworks: Prioritize Cache Hits
Efficient AI agent execution relies heavily on effective caching. This article explains how to optimize LLM agent frameworks by understanding prefill, decode, and KV cache mechanisms. It details strategies for organizing requests, managing context, and measuring performance metrics to reduce costs and latency while maintaining task quality and security.
1. Why Agent Frameworks Should Prioritize Caching
An agent execution framework is responsible for orchestrating model calls, managing conversation state, executing tools, and feeding tool results back to the model. A seemingly simple development task can go through multiple cycles of “analyze problem - call tool - read result - continue reasoning.”
These calls typically contain a large amount of repetitive content: system instructions remain largely unchanged, tool descriptions appear repeatedly, project briefs persist, and historical messages accumulate. If every request recalculates the entire input from scratch, the framework repeatedly pays compute and time costs for content it has already processed.
Therefore, cache hits are not an isolated performance toggle, but a critical indicator of the framework’s design quality. Request stability, state traceability, and message consistency all determine whether context can be reused.
However, cache optimization should not be simplistically understood as “the higher the hit rate, the better.” The true goal is:
Reducing repetitive input computation and improving the cost and response time of effective tasks, without lowering task quality or security requirements.
If you continuously carry useless history just to boost the hit rate, the input size may keep expanding. Even if the unit price of the cached portion is lower, the total cost, context consumption, and the model’s attention burden may still increase.
2. Understanding Prefill, Decode, and KV Cache
1. Prefill: Processing Existing Context
Upon receiving a request, the model must process system instructions, tool definitions, historical messages, and the current input. This phase is typically called prefill.
In common autoregressive attention models, each layer computes corresponding representations based on the input, including the keys and values required for subsequent attention calculations. A long context means more input to process, which usually translates to higher prefill overhead.
Thus, even if two requests ultimately generate very short responses, as long as the input is sufficiently long, repetitive prefilling can become a significant cost source.
2. Decode: Generating New Content Step-by-Step
After processing the input, the model typically generates new tokens one by one. This phase is called decoding.
During decoding, the model can utilize previously saved keys and values, avoiding the need to reprocess the entire history for every new token generated. This saved intermediate state is the Key-Value Cache, often referred to as the KV Cache.
It is crucial to emphasize: The KV Cache stores computation states, not the text of previous responses, nor a business knowledge base.
A cache hit does not mean the model will directly return a previous answer. The model still needs to compute and generate output based on the newly added input.
3. Intra-Request Caching vs. Cross-Request Reuse
When understanding caching, two levels should be distinguished:
- Intra-request state reuse: Reusing processed historical states within the same generation process.
- Cross-request prefix reuse: When a subsequent request shares the same beginning as an existing cache, the inference service may reuse that computation state.
Cross-request reuse depends on server-side implementation. Cache granularity, retention time, routing methods, model configurations, and isolation policies can all affect actual hits. Therefore, a client observing that two requests share the same prefix does not guarantee a server-side hit.
3. Prefix Matching: The Fundamental Rule of Cache Optimization
Most prefix caching mechanisms focus on: How much content remains consistently identical from the beginning of the request.
Assume a request is structured as:
[System Instructions][Tool Definitions][Project Background][Historical Messages][Current New Message]
If the previous request was:
A + B + C
And the next request is:
A + B + C + D
Then the existing A + B + C might be reused, and only the new part D needs to be processed.
However, if the second request becomes:
A + B' + C + D
Even if C is completely unchanged, under common exact prefix reuse mechanisms, you cannot simply skip the altered part and continue using the original state. This is because subsequent states depend on preceding context; if earlier content changes, subsequent computation results may also change.
This forms a key engineering principle:
Place long-term stable content at the beginning, and high-frequency variable content at the end.
Here, “consistency” usually refers to the consistency of the token sequence and related configurations actually processed by the server, not semantic consistency. Two prompts expressing the same meaning do not necessarily share a cache. Variations in whitespace, field order, text formatting, or message structure can also cause input discrepancies.
4. Request Organization: Eliminating Meaningless Variations
1. Keep System Instructions Stable Without Sacrificing Instruction Hierarchy
System instructions rarely change and are suitable as part of a stable prefix. Role descriptions, behavioral boundaries, and output specifications should use unified templates, with changes controlled via version management.
Avoid arbitrarily inserting frequently changing elements like timestamps, random IDs, or running statuses at the beginning of fixed templates. Once these change, they truncate the reusable prefix.
However, when adjusting positions, the instruction hierarchy must be respected. You should not downgrade content with security constraints to ordinary context just for the sake of caching. Optimization should occur under the premise that semantics and permission boundaries remain unchanged.
2. Make Tool Definitions Stable and Appropriate
Tool names, descriptions, parameter structures, and ordering are all part of request stability. The execution framework should avoid randomly sorting tools each turn or repeatedly rewriting descriptions when functionality hasn’t changed.
Tool definitions can be organized into version-controlled fixed templates to reduce discrepancies caused by dynamic concatenation.
That said, stable does not mean infinitely expanding. Keeping all tools in the context at all times may increase input length and affect the model’s accuracy in selecting the right tool. A more reasonable strategy is to determine the required tool set based on the task and keep it stable within the task phase; consciously adjust it only when capability requirements change.
3. Standardize Project Background and Retrieved Materials
Project briefs are usually stable, while retrieval results, file fragments, and execution feedback may change every turn. These two should be managed separately:
- Place stable project background relatively early;
- Place current retrieval materials in the dynamic context area;
- Use deterministic sorting rules for multiple fragments;
- Avoid reordering or reformatting when content hasn’t changed;
- Remove meaningless time fields and temporary display information.
This not only improves reusability but also makes it easier for developers to determine “which content change caused the cache to drop.”
4. Use Deterministic Serialization for Historical Messages
Historical messages should not be re-polished, have punctuation automatically replaced, or have field output orders changed each turn. For structured tool results, stable serialization rules should be established.
For example, for the same data object, if the field output order differs each time, the text prefix may change. Engineering-wise, you can fix field order, numerical format, line break rules, and how empty fields are handled.
However, standardization can only eliminate meaningless discrepancies, not erase real business differences. For instance, code indentation, path casing, and precise values may have actual semantic meaning and should not be arbitrarily rewritten.
5. Context Management: Balancing Append, Trimming, and Compression
1. Prioritize Appending, Do Not Rewrite History Unnecessarily
If a task is ongoing, appending new messages is usually more beneficial for prefix reuse than rebuilding the entire history.
The framework can treat message history as an ordered log: existing records remain unchanged, and new records are appended to the tail. This approach is not only cache-friendly but also facilitates replay, auditing, and fault localization.
However, when history contains errors, expired states, or sensitive data, it should still be processed promptly; you should not keep unsuitable content for the model just to maintain a high hit rate.
2. Context Compression Causes a Structural Break
Long tasks often require compressing early history into a summary. After compression, the request structure changes, and cache hits may temporarily drop.
This is not an optimization failure, but a cost trade-off: compression sacrifices some reusable history, but it may significantly reduce the input size for subsequent turns.
A more prudent approach is to set clear compression trigger conditions, such as the context nearing capacity limits, noticeable increase in historical noise, or the task entering a new phase. After generating the summary, keep it stable for several subsequent turns to avoid summarizing from scratch every turn.
Summaries should prioritize retaining goals, constraints, confirmed facts, key decisions, and pending items, rather than mechanically compressing all dialogue.
3. File Changes Must Be Reflected Promptly
In AI coding scenarios, code files are constantly modified. You cannot continue feeding the model outdated code just to preserve the cache.
You can separate stable project overviews from frequently changing file content; when the task allows, provide necessary change fragments rather than repeatedly sending all files. However, whether to use diff content should be combined with the model’s understanding of the current code state; you should not omit critical context under the guise of saving input.
6. Validating ROI with Metrics Beyond a Single Percentage
Cache hit rate is usually calculated based on input tokens:
Cache hit rate = Cached input tokens / Total input tokens
If the service bills cached and uncached inputs separately, a simplified cost model can be written as:
Input cost = Cached input volume × Cached unit price+ Uncached input volume × Uncached unit price
Compared to billing everything as uncached, the theoretical input savings are:
Input savings = Cached input volume × (Uncached unit price - Cached unit price)
These formulas only describe the input portion and do not directly represent the total bill. Output fees, cache write or storage fees, tool execution fees, and other service costs must be considered separately according to actual billing rules.
It is recommended to track the following metrics simultaneously:
| Metric | Primary Use |
|---|---|
| Weighted input token hit rate | Determine if repetitive input is effectively reused |
| Total cost per effective task | Determine if business benefits are real |
| Time to first token (TTFT) | Observe the impact of prefill optimization on wait time |
| Full task duration | Determine if end-to-end experience is improved |
| Average input length and growth trend | Identify history bloat |
| Task success rate and retries | Prevent optimization from harming correctness |
When evaluating, distinguish between cold and hot caches, and record factors such as cache expiration, concurrency, service routing, and model configuration changes. A high hit rate may simply come from heavily repetitive long contexts, so different solutions should not be compared directly without considering the workload.
7. Building an Observable Cache Optimization Loop
In practice, you can record summary fingerprints for each logical region per request:
System instruction region: Version and content fingerprintTool definition region: Version and content fingerprintProject background region: Content fingerprintHistorical message region: Count and content fingerprintDynamic input region: Length and change type
These fingerprints are used to determine if content has changed; they do not represent the actual cache key on the server side, nor can they be used to directly infer actual hits.
When the hit rate drops, you can troubleshoot in the following order:
- Has the model or a configuration affecting computation changed?
- Has a fixed template been updated?
- Has the tool set or its ordering changed?
- Has a dynamic field been inserted into the project background?
- Has the history been compressed, trimmed, or re-serialized?
- Has the cache expired, or was the request routed to a different cache resource?
Logs should prioritize saving necessary statistical information and controlled fingerprints, rather than indiscriminately recording full prompts. Sensitive content like code, credentials, and customer data should be subject to access control, desensitization, and retention period management.
8. Security and Correctness as Prerequisites for Cache Reuse
Cross-request caching requires clear tenant, permission, and data isolation boundaries. Even if two users submit identical content, you cannot assume they can share all cache states. Whether sharing is possible should be determined by the service architecture and security policies.
For retrieved materials and tool outputs, it must be clear that they are external data and should not allow embedded instructions to override system rules. Stable caching reduces repetitive computation but does not eliminate risks like prompt injection, data staleness, or tool result errors.
The framework should also avoid mixing session identifiers, access credentials, and sensitive business content into broadly reusable public templates. Cache-related logs, diagnostic interfaces, and monitoring data must also be incorporated into security management.
9. Implementation Sequence: Stabilize, Measure, Refine
An actionable transformation sequence is:
- Establish a baseline: Record current input length, hit rate, cost, latency, and task quality.
- Stabilize request structure: Fix templates, tool order, and serialization rules; remove unnecessary dynamic fields.
- Split context regions: Clarify which content is long-term stable and which changes every turn.
- Govern history growth: Set up phased compression and trimming mechanisms, balancing prefix reuse and input size.
- Conduct A/B testing: Compare cold/hot cache performance and end-to-end ROI under the same task set.
- Continuously monitor for regressions: Re-evaluate effects after template updates, tool expansions, or model configuration changes.
A good agent execution framework doesn’t simply stuff more content into the context; it ensures every piece of content has a clear position, lifecycle, and change rules.
The value of a cache hit ultimately lies in reducing meaningless recomputation. Only by combining stable prefixes, context governance, billing analysis, and quality assessment can you truly transform “higher hit rates” into “cheaper effective tasks, faster responses, and more reliable operations.”
