Sub topic 13
Stable prefixes and prompt caching
This chapter explains why the order and stability of your agent's context affect cost and speed. It assumes you have read the earlier chapters on what fills the context and on compaction. You should also be comfortable with the command line and basic Python.
What prompt caching is
Every time a coding agent takes a step, the whole context is sent to the model again. That includes the system prompt, tool definitions, project instructions, and every earlier message and tool result. In a long session the same thousands of tokens are sent dozens of times.
Prompt caching lets the provider reuse work it already did on the beginning of that input. The provider stores the processed form of a prompt prefix. If your next request starts with the same prefix, it skips that work and processes only the new part. The benefits are:
- Lower latency, because less input is processed from scratch.
- Lower cost on providers that charge less for cached input tokens.
- Often higher throughput under rate limits, depending on the provider.
Caching changes cost and speed. It does not change how much fits in the context window. A cached token still occupies a slot in the window, so everything in the earlier chapters about trimming and compacting still applies.
How the cache matches: exact prefixes
A cache hit requires the new request to begin with exactly the same content as an earlier request. The match is by position from the start. If one token differs, the cache can reuse only what came before that token. Everything after it must be processed again, even if it is identical to the earlier request.
Most agent requests are assembled in this order:
- Tool definitions.
- System prompt and persistent project instructions.
- Conversation history, oldest message first.
- The newest message or tool result.
The layers at the top change rarely. The layers at the bottom change on every step. That order suits caching, because the stable material comes first and the new material is appended at the end.
What breaks a prefix
Anything that changes content early in the request invalidates the cache from that point on. Common causes in agent sessions:
- A timestamp or session ID at the top of the system prompt. It changes on every request, so the cache never matches past it.
- Editing the instruction file mid-session. If the agent reloads it and the text changes, the prefix changes from that point.
- Adding or removing a tool, or changing a tool's description. Tool definitions usually come first, so a change there can invalidate almost everything.
- Switching models. Caches are generally tied to a specific model.
- Rewriting earlier history. Compaction replaces old messages with a summary. The new prefix differs from the old one, so the next request starts with a cache miss.
- Reordering content. The same text in a different order is a different prefix. This includes nondeterministic ordering, such as listing files from an unsorted set.
- Waiting too long. Cached prefixes expire. Lifetimes are short and vary by provider and configuration, often in the range of minutes. A long pause can mean the next request is a miss even if nothing changed. Check your provider's documentation for the current lifetime.
The details differ between providers. Some cache automatically, some ask you to mark cache breakpoints, and some require a minimum prefix length before caching applies. Treat the rules in this chapter as general principles and confirm the specifics for your tool.
Seeing the effect in code
The script below simulates a prefix cache at the level of whole segments. Real caches work on tokens or blocks, but the matching rule is the same. It compares two consecutive requests and counts how many leading segments are identical.
def cached_segments(previous, current):
"""Count leading segments that match exactly."""
count = 0
for old, new in zip(previous, current):
if old != new:
break
count += 1
return count
def build(system, tools, history):
return [system, *tools, *history]
tools = ["tool:read_file", "tool:run_tests"]
history = ["user: fix parser", "assistant: reading config.py"]
new_result = ["tool: config.py contents"]
# Case 1: a stable system prompt, new content appended at the end.
stable = "system: follow AGENTS.md"
first = build(stable, tools, history)
second = build(stable, tools, history + new_result)
print("stable prompt:", cached_segments(first, second), "of", len(first), "segments reused")
# Case 2: a clock embedded in the system prompt changes the first segment.
clock_a = "system: follow AGENTS.md. Time 13:45:02"
clock_b = "system: follow AGENTS.md. Time 13:45:40"
first = build(clock_a, tools, history)
second = build(clock_b, tools, history + new_result)
print("clock in prompt:", cached_segments(first, second), "of", len(first), "segments reused")Running it prints:
stable prompt: 5 of 5 segments reused
clock in prompt: 0 of 5 segments reusedIn the second case, one changed character in the first segment makes every later segment a miss. The later segments are identical, but the cache cannot use them because the prefix before them differs.
Design rules for stable prefixes
Put stable content first and volatile content last. If the agent needs the current date or branch name, give it in the newest message or fetch it with a tool call. Do not put it in the system prompt. A tool result lands at the end of the history, where a change costs nothing.
Keep persistent instructions fixed during a session. The earlier chapter on persistent instructions recommended short, stable files. Caching gives a second reason. Each edit to the instruction file mid-session forces reprocessing of the history that follows it. Make edits between sessions, or accept the one-time cost when the change is worth it.
Keep the tool set constant. Choose the tools a session needs at the start. Toggling tools on and off during a session invalidates the prefix each time. If a tool is rarely used, leaving it enabled is often cheaper than repeated cache misses. Weigh this against the context space its definition takes.
Append, don't rewrite. A conversation that only grows at the end keeps its prefix. Operations that rewrite the middle break it. Compaction is the main example, and it is still worth doing. See the next section.
Make output deterministic where it enters the context. If a tool lists files, sort the list. If a script prints a map of the repository, make it print in the same order every time. This matters most for material that is re-sent as part of a fixed prefix, such as a generated repository summary placed in the instructions.
Keep sessions warm when it matters. If the cache lifetime is short, a quick follow-up reuses the prefix. Coming back after a long break often means paying for the full prefix again. This is rarely a reason to change how you work, but it explains why the first request after a pause can feel slower and cost more.
Caching and compaction pull in different directions
Compaction shrinks the context, which lowers cost on every later request. It also rewrites the history, so the next request after compaction is a cache miss on the rewritten part. The cost of that miss is paid once.
A rough way to decide:
| Situation | Better choice |
|---|---|
| Context is small and the session is going well | Keep going. A compaction would break a useful cached prefix for little gain. |
| Context is large, and many more steps remain | Compact. A one-time miss is cheaper than carrying a large history through many steps. |
| Quality is degrading (repeated mistakes, forgotten decisions) | Compact or start fresh. Correctness outweighs cache savings. |
| A few steps remain before the task ends | Finish, then start a new session for the next task. |
Quality comes first. A cache hit on a context that confuses the agent saves money but wastes your time.
The same logic applies to handoffs. A fresh session starts with an empty cache for its history, but if it begins with the same tools, system prompt, and instruction file, that stable part of the prefix can still be cached from earlier sessions while the provider keeps it.
Common mistakes
- Putting
Current time:or a random request ID at the start of the system prompt. - Generating a repository summary with an unstable order and inserting it into the instructions.
- Changing the model partway through a session without expecting a cold start.
- Assuming that caching removes the need to manage context. It reduces the price of repeated tokens. It does not reduce what the model must attend to, and it does not prevent degradation.
- Assuming a cache hit guarantees any specific discount. Pricing and behavior depend on the provider, so check your usage reports to see how many cached tokens each request used.
Checking whether it works
If your tool or provider reports cached tokens per request, use that number. After the first request of a session, most input tokens should be reported as cached, apart from the newest step. If the cached count stays near zero, look for a changing element near the top of the request: a timestamp, a rewritten instruction file, or a changing tool list.
Exercise
A team's agent session shows almost no cached tokens on any request, even though the conversation only grows by appending messages. The system prompt begins with the line "Session started: <current time to the second>". Explain why the cache is missing and give one fix.
Show answer
The timestamp is in the first segment of the request, and its value changes on every request. Caches match only an exact prefix from the start, so the mismatch at the very beginning means nothing after it can be reused. The fix is to remove the timestamp from the system prompt. If the agent needs the time, let it call a tool or include the time in the newest message, which sits at the end of the request where a change does not affect the cached prefix.
Exercise
Your session has 80% of the window used and about twenty steps of work remain. You know compaction will cause one cache miss on the history. Should you compact? Give your reasoning.
Show answer
Yes, compact. The miss happens once, while a large history would be re-sent and attended to on each of the remaining twenty steps. A smaller context lowers the cost and latency of those steps and reduces the risk of degradation. After compacting, keep the system prompt, tools, and instructions unchanged so that the next requests can cache the new, shorter prefix.