Protecting the Request Prefix: Engineering Practices for Agent Cache Hit Rates
This article explains how prefix caching works in LLM-based agents, why a cache hit depends on each request matching byte for byte at the start, and which common changes break the prefix. It also covers practical ways to keep prefixes stable and how to use the cache hit rate to check whether a runtime is behaving consistently.
In an agent system, a single task usually goes through several rounds of model calls. The input for each round includes system instructions, tool definitions, project rules, and conversation history. Most of this content is identical to the previous round. Server-side prefix caching can reuse the intermediate states already computed for this shared part, which lowers latency and cost. The benefit does not appear automatically, though. It depends on how the runtime assembles each request. This article covers how prefix caching works, the common ways it gets broken, and how to protect it.
1. What Gets Cached: From Result Reuse to Prefix Reuse
Traditional caching stores key-value pairs. Developers design the keys explicitly, so the conditions for a hit are clear. Prefix caching for large language models works on a different object. When the service processes an input, it computes intermediate attention states for every token. These are commonly called the KV cache. When the beginning of a new request matches the beginning of an earlier request, the computed states can be reused directly. Only the tokens from the first mismatched position onward need to be recomputed.
A cache hit therefore depends on token order. The cache measures the longest common prefix, counted from the start of the request. The test is whether the serialized token sequence matches position by position. Semantic similarity does not matter. Two texts with the same meaning but different wording, whitespace, or order will not hit the cache.
This property leads to the core engineering principle: the runtime must keep the beginning of every request stable at the byte level.
2. Why Prefixes Break
Prefixes usually break for small, mundane reasons. They generally fall into the following categories.
- Position changes: The order of the tool list changes, or a rule is inserted earlier in the prompt.
- Dynamic content at the front: The current time, random IDs, or request numbers are written at the start of the system prompt, so they differ on every call.
- Rewritten history: Old messages are edited to compress them or fix formatting, which changes their text or whitespace.
- Unstable serialization: The same object produces JSON keys in a different order at different times.
- Configuration drift: Different processes or versions load templates that differ slightly.
These changes are nearly invisible, but each one breaks the cache at its first difference. The earlier the difference occurs, the more computation is wasted.
3. A Typical Agent Flow
Consider a common workflow. In the first round, the model reads the project rules and tool descriptions, then decides to call a search tool. The runtime runs the search, appends the results to the end of the message list, and sends the second round of requests.
Ideally, the first half of the second request matches the first round exactly. It adds only the tool call and the tool result. The prefix cache can cover most of the input, so this round needs to compute only the few hundred new tokens.
Now suppose the runtime reorders the tools in the second round, or inserts the current time into the system prompt. The cache then breaks at the earliest difference. The large block of content after that point must be recomputed in full, even though it has not changed. This problem grows in long, multi-round, multi-tool tasks, because each additional round increases the amount of content that may be recomputed.
4. Engineering Practices for Keeping the Prefix Stable
4.1 Layer Content by Change Frequency
Sort request content by how stable it is. Place the most stable content first, including base instructions and tool definitions. Next come project-level rules, then session-level history. Put the new messages from the current round and any dynamic information last. The more often content changes, the later it should appear. This limits how much of the prefix a change can invalidate.
4.2 Use Deterministic Serialization
Output tool definitions and parameter schemas with a fixed sorting rule. Do not rely on the insertion order or traversal order of dictionaries.
import jsondef serialize_tools(tools: list[dict]) -> str:# Sort by name and fix the key output order so the same set of tools# always produces the same byte sequenceordered = sorted(tools, key=lambda t: t["name"])return json.dumps(ordered, ensure_ascii=False, sort_keys=True)
4.3 Move Dynamic Information to the End
Put timestamps, request IDs, and similar values at the end of the current round’s messages, not in the system prompt. Even if this information changes every round, it then affects only the content added in that round.
from datetime import datetime, timezonedef build_messages(prefix: list[dict], history: list[dict], user_input: str) -> list[dict]:now = datetime.now(timezone.utc).isoformat()# Append dynamic info to the latest user message so the prefix and# history stay unchangedlatest = {"role": "user", "content": f"{user_input}\n[Current time {now}]"}return prefix + history + [latest]
4.4 Append to History, Never Rewrite It
Treat messages already written to a session as immutable. When the context needs compressing, generate a new summary message and place it after the history. State which earlier content it replaces. Compression changes the prefix, so run it once when the context exceeds a set threshold, not on every round.
4.5 Keep Runtime Configuration Fixed Within a Session
Keep the template version, tool set, and model parameters unchanged for the duration of a session. If a change is unavoidable, treat it as the creation of a new prefix. Record the reason in the logs so you can later analyze how the hit rate changed.
5. Using the Cache Hit Rate as a Runtime Health Check
The cache hit rate is more than a number on a cost report. It can also show whether the runtime is stable. For each request, record three values: the total number of prefix tokens, the number of cached tokens, and the position where the cache miss begins.
The hit rate is calculated as follows:
Hit rate = cached input tokens / total input tokens
When the hit rate suddenly drops, compare the serialized outputs of the two most recent requests and find the first position where they differ. The function below locates the first differing character between two strings.
def first_diff(a: str, b: str) -> int:for i, (x, y) in enumerate(zip(a, b)):if x != y:return ireturn min(len(a), len(b))
Once you find the difference, trace it back to the code that assembles the request. The cause is usually tool sorting, timestamp injection, or history rewriting.
6. Balancing Cost and Engineering Effort
Many providers charge different unit prices for cached and uncached input, and the gap can be large. Check the provider’s published pricing for current rates. When estimating costs, consider two factors. The first is whether the prefix stays stable within a session. The second is how much new content each round adds. The first factor determines how much you save, and the second determines the baseline size of the recomputed input.
Conclusion
The benefits of prefix caching come from disciplined runtime engineering. Keep stable content first, put changing content last, treat history as read-only, and monitor hit rates over time. Following these steps keeps the repeated computation in each agent step as small as possible.
