Sub topic 13
Structuring prompts for caching
This chapter assumes you can call a language model through an API, know what a system prompt is, and can read short Python. It covers how to order a prompt so a provider can reuse work from earlier calls.
Why caching matters for context
An agent or chat application sends a long prompt on every call. Most of that prompt is the same each time: the system rules, the tool descriptions, and often a block of reference material. The model has to process all of it again on every call unless the provider remembers earlier work.
Prompt caching is a provider feature that stores the processed form of the beginning of a prompt, so a later call that starts with the same text can skip that work. The effect depends on the provider. It usually lowers the price of the cached part of the input, and it often lowers the time before the first output token appears.
Caching does not change what the model sees. The output should be the same with or without it. It changes cost and speed only. This makes it a good last step in context engineering: you first decide what belongs in the context, and then you arrange it so the stable part can be reused.
How prefix caching works
Most providers cache a prefix. A prefix is the first N tokens of a prompt. The cache can be reused only if the new prompt begins with exactly the same tokens as an earlier one, up to some boundary.
Two consequences follow from this.
- The match is exact. A changed word, a different space, or a reordered tool list produces different tokens and ends the match at that point.
- Everything after the first difference is processed again, even if it is identical to the earlier prompt.
So the order of your prompt decides how much can be cached. Content that never changes belongs at the start. Content that changes on every call belongs at the end.
Ordering from stable to variable
Sort your prompt sections by how often they change. A typical order is:
- System rules. They change only when you release a new version of the application.
- Tool descriptions. They change when you add or remove a tool.
- Reference documents. They change per task, or per user.
- Conversation history. It grows with each turn.
- The current question. It is different on every call.
The helper below builds a prompt in this order. It puts the two stable sections first and the three changing sections last.
def assemble_prompt(system_rules, tool_descriptions, reference_docs, recent_history, question):
# Stable content first, so a provider's prefix cache can reuse it across calls.
# Content that changes on every call goes last.
stable = [system_rules, tool_descriptions]
variable = [reference_docs, recent_history, question]
return "\n\n".join(stable + variable)If a developer builds the prompt the other way, with the question first, no two calls share a prefix, and the cache never helps.
Ordering and the earlier chapter on placement
An earlier chapter discussed where to place instructions and evidence so the model uses them well. Caching adds a second constraint. Sometimes the best place for an instruction, such as a reminder right before the question, is not the best place for caching. In practice the two goals mostly agree, because the stable system rules go first for both reasons. Where they conflict, keep the stable block first and put short reminders in the variable tail. The tail is small, so repeating a line there costs little.
What breaks a prefix
Cache misses usually come from small, accidental changes near the top of the prompt. These are the most common ones.
| Cause | Example | Fix |
|---|---|---|
| Timestamp in the system prompt | "Current time: 06:04:20" | Move the time into the variable tail, or round it to the day |
| Per-user data early in the prompt | "The user's name is Ana" in the first line | Place user details after the shared block |
| Unstable tool order | Tools listed from a set or dictionary with no fixed order | Sort tools by name before sending |
| Random IDs | A request ID inside the system prompt | Send IDs in headers or after the prefix |
| Edited history | Rewriting or removing an older message | Append new messages. Do not change old ones |
| Changed tool list mid-session | Adding a tool in turn 5 | Keep the tool set fixed per session |
The last two rows deserve attention because they conflict with other techniques in this tutorial.
Compaction and history trimming
Trimming or compacting history changes the middle of the prompt. Every change invalidates the cache from that point onward. This does not make compaction a bad idea. It means you should compact in batches, not on every turn.
Consider a session that drops the oldest message on every call. Each call rewrites the history section, so the history is never cached. If the session instead lets history grow for 20 turns and then compacts once, 19 of 20 calls can reuse the cached history, and only the compaction call pays the full price.
def compact(history, keep_last, summarize):
# history is a list of message strings, oldest first.
# summarize is a function that takes a list of messages and returns a short string.
split = max(0, len(history) - keep_last)
older, recent = history[:split], history[split:]
if not older:
return history
summary = summarize(older)
return ["Summary of earlier conversation: " + summary] + recentA simple policy is to call compact only when the token count passes a threshold, such as 80 percent of your budget, and not on every turn.
Cache lifetime and minimum size
Providers set rules that you should look up for the one you use. The details differ and change over time, but these properties are common.
- Minimum length. Very short prefixes may not be cached at all. A prompt with a two-line system message gains nothing.
- Time to live. A cache entry expires after a period of no use, often measured in minutes. A burst of calls benefits. One call per hour may not.
- Refresh on use. In many systems each cache hit extends the entry's life.
- Explicit or automatic. Some providers cache automatically when prefixes match. Others require you to mark a cache boundary in the request.
- Different prices. Writing to the cache can cost more than a normal call, while reading from it costs less. A prefix used only once may cost you more than not caching.
Because of these rules, caching pays off when many calls share a long prefix within a short time. It pays off less for rare, one-off calls.
Estimating the saving
You can estimate the benefit before you build anything. Suppose a prompt has a 6,000-token stable prefix and a 1,000-token variable tail. Without caching, each call processes 7,000 input tokens. With a cache hit, 6,000 of those tokens are read at the cheaper rate, and 1,000 are processed normally.
The share of input that can be cached is the stable prefix divided by the total prompt:
6,000 / 7,000 ≈ 86 percent
If cached tokens cost a fraction of normal ones, the saving on input cost is close to that share times the discount. Long agent sessions are the best case, because the history grows and the stable prefix stays the same. In that case, each new call adds only a small tail to a large cached block.
Interaction with budgeting
Caching does not enlarge the context window. A cached token still counts against the window, and it still competes with the output reserve and everything else in the budget. Caching lowers the price of tokens. It does not make them free in terms of space.
This matters for selection decisions. Do not keep a document in the prefix just because it is cheap to cache. An irrelevant cached document still distracts the model, as the chapter on context failures described. Select first, then order for caching.
A practical checklist
- Put system rules and tool descriptions first, in a fixed order.
- Keep anything that varies per call, such as time, user, and question, after the shared block.
- Append to history. Avoid editing earlier messages.
- Compact in batches when a threshold is reached.
- Keep the tool set stable for the length of a session.
- Log cache read and write token counts, and track the hit rate.
- Compare answer quality with and without your reordering, using the fixed test set from the evaluation chapter. Reordering can change output quality even though caching alone does not.
Common errors
- Putting the date at the top. The most frequent cause of misses. A date that changes daily limits the cache to one day. A timestamp that changes each second removes the cache entirely.
- Building the tools list from an unordered collection. Python dictionaries keep insertion order, but a list built from a
setdoes not have a stable order across runs. - Reusing a cached block across different users when it contains private data. Keep private material out of any block that is shared.
- Caching too little. A prefix below the provider's minimum is never stored, so you pay for the setup and get no reuse.
- Optimizing before measuring. If your calls are rare, a cache entry expires before the next call and the work is wasted.
Exercise
A support agent builds its prompt as: a line with the current timestamp, the system rules (3,000 tokens), the tool descriptions (2,000 tokens), the conversation history, and then the user's question. The provider reports zero cached tokens on every call. What is the likely cause, and how would you change the order?
Show answer
The timestamp on the first line changes on every call, so the prefix differs from the first token and nothing after it can match. Move the timestamp out of the prefix and into the variable tail, next to the question. The order becomes: system rules, tool descriptions, history, then timestamp and question. The 5,000-token stable block can then be cached.
Exercise
A session drops the oldest message from history on every turn to stay under budget. Calls are made every few seconds and the history is long. Why is caching poor here, and what change keeps the budget while improving cache reuse?
Show answer
Dropping the oldest message changes the start of the history section on every call, so the history never matches an earlier prefix. Let history grow by appending, and compact it only when it passes a threshold, for example 80 percent of the budget. Between compactions, the prefix including the history stays identical, so most calls get cache hits.