Sub topic 9
Reuse stable prompt prefixes with provider caching
This chapter assumes you can call an LLM API, know what system messages and tokens are, and have read the earlier chapters on token pricing, latency anatomy, and measurement. Here you will learn what provider prompt caching does, how to lay out prompts so it works, and how to check that it is working.
What provider prompt caching is
When a model receives a prompt, it first runs a prefill step over every input token. Prefill builds internal state (the attention key and value tensors) for each token. If two requests start with the same tokens, that state is identical for the shared part. Provider prompt caching stores the state for a prefix so a later request can skip recomputing it.
You get two benefits when a request hits the cache:
- Lower input cost. Providers typically bill cached input tokens at a discount. Some also charge a premium to write a cache entry. The size of both varies by provider and model, so read your provider's current pricing page.
- Lower time to first token. Prefill is the main part of time to first token for long prompts. Skipping most of it shortens the wait before the first output token.
Caching does not change the output tokens, the decoding speed, or the answer. It is a billing and speed feature, not a quality feature. A cached request should produce the same kind of answer as an uncached one.
This is different from the exact-match response cache covered in a later chapter. A response cache returns a stored answer and skips the model entirely. A prompt cache still runs the model, still generates a fresh answer, and only saves the work on the shared prefix.
How prefix matching works
Caches match on a prefix, meaning the beginning of the prompt, token for token. The first token that differs ends the match. Everything after that point is processed normally.
This leads to the main design rule: put content that stays the same at the start of the prompt, and content that changes at the end.
A layout that caches well:
- System instructions
- Tool or function definitions
- Fixed few-shot examples or reference documents
- Per-request retrieved context
- The user's question
A layout that caches badly puts a timestamp, a user name, or a request ID in the first line. That one changing token makes every prompt differ from the very start, so no prefix is ever shared.
Common ways to break the prefix
These mistakes are the usual reasons a cache never hits:
- Dynamic values early in the prompt. Current date, session ID, user name, or A/B flags placed in the system message. Move them to the end, or drop precision you do not need (a date instead of a full timestamp).
- Unstable serialization. Tool definitions or JSON examples built from a Python dict with changing key order produce different text each run. Serialize with a fixed order.
- Reordered content. Retrieved documents placed before a fixed instruction block, or few-shot examples shuffled per request.
- Editing the shared prefix. Any edit to the system prompt invalidates existing entries. Expect a burst of cache misses after each prompt deploy.
- Changing the model or request settings that the provider includes in the cache key. Entries are generally tied to a specific model. Some providers also key on tool definitions or other parameters.
Provider differences you must check
Providers implement caching in different ways. Before you rely on it, look up these points in the current documentation:
| Question | Why it matters |
|---|---|
| Is caching automatic or do you mark cache breakpoints? | Automatic systems need only a good layout. Explicit systems need request changes. |
| What is the minimum prefix length? | Short prompts may be below the threshold and never cache. |
| How long does an entry live? | Typical lifetimes are minutes, and a hit usually refreshes the timer. Sparse traffic can let entries expire. |
| Is there a write premium? | A premium means a prefix that is used only once costs more than no caching. |
| How is the discount reported? | You need a usage field in the response to verify hits. |
Treat any specific number you read in a blog post as stale until you confirm it on the provider's page.
When caching pays off
Caching helps when many requests share a long prefix and arrive close together in time. Good fits:
- A chatbot with a long system prompt and tool list, called on every turn
- A document question-answering app where many questions are asked about one large document
- An agent loop that resends a growing conversation, where each step shares everything before the newest message
- A batch job that applies the same long instructions to thousands of items
It helps little when prompts are short, when every prompt starts differently, or when traffic is so sparse that entries expire between calls.
You can estimate the saving with the same cost arithmetic from the pricing chapter. The sketch below compares a request stream with and without cache hits, using placeholder prices.
# Placeholder prices in USD per million input tokens. Replace with your provider's current prices.
PRICE_INPUT = 1.00
PRICE_CACHED_INPUT = 0.10 # discounted rate for cache reads
PRICE_CACHE_WRITE = 1.25 # some providers charge extra to write an entry
def input_cost(prefix_tokens, suffix_tokens, requests, hit_rate):
"""Estimated input cost for a stream of requests sharing one prefix.
hit_rate is the fraction of requests that read the prefix from cache.
The remaining requests pay the write price (or the normal price if
your provider has no write premium).
"""
hits = requests * hit_rate
misses = requests - hits
prefix_cost = (
hits * prefix_tokens * PRICE_CACHED_INPUT
+ misses * prefix_tokens * PRICE_CACHE_WRITE
)
suffix_cost = requests * suffix_tokens * PRICE_INPUT
return (prefix_cost + suffix_cost) / 1_000_000
baseline = input_cost(6000, 400, 10_000, hit_rate=0.0)
cached = input_cost(6000, 400, 10_000, hit_rate=0.9)
print(f"no hits: ${baseline:.2f} 90% hits: ${cached:.2f}")With the placeholder prices, a 6,000-token prefix and a 90% hit rate cut input cost sharply. With a hit rate near zero, the write premium makes caching cost more than not caching. That is why the hit rate is the number to watch.
Verify hits from the usage data
Never assume the cache is working. Most providers return token counts in the response that split cached from uncached input. The field names differ by provider, so the helper below takes the counts as arguments and you map your provider's fields onto them.
def cache_report(usages):
"""Summarize cache effectiveness from a list of (cached_tokens, total_input_tokens) pairs."""
cached = sum(c for c, _ in usages)
total = sum(t for _, t in usages)
hit_requests = sum(1 for c, _ in usages if c > 0)
return {
"token_hit_rate": cached / total if total else 0.0,
"request_hit_rate": hit_requests / len(usages) if usages else 0.0,
}
# Example data: the first call writes the cache, later calls read it.
print(cache_report([(0, 6400), (6000, 6400), (6000, 6420), (6000, 6395)]))Log both rates. The token hit rate tells you how much money you save. The request hit rate tells you whether the prefix is being matched at all. A low token hit rate with a high request hit rate means only a small part of each prompt is shared, so move more stable content to the front.
Also compare time to first token for hit and miss requests, using the timing wrapper from the measurement chapter. A real hit should show lower time to first token on long prompts. If cost drops but latency does not, the bottleneck may be queueing or decoding rather than prefill.
Working with the cache in practice
Follow this order when you add caching:
- Take a baseline of cost and time to first token.
- Restructure the prompt so stable content comes first.
- Enable caching in the way your provider requires.
- Send a repeated request twice and confirm the second shows cached tokens in the usage data.
- Run your evaluation set to confirm quality is unchanged.
- Watch hit rate in production and alert if it drops.
For intermittent traffic, consider whether your entry lifetime fits your request spacing. If requests come every ten minutes and entries last five, you pay write costs on nearly every call. Either accept it, batch requests closer together, or turn caching off for that route.
Cached prefixes also interact with other levers. Trimming the prompt still helps, but trimming the stable prefix shortens the part that is already discounted, so favor trimming the changing suffix first. Retrieval budgeting matters more, because retrieved context sits after the prefix at full price.
Exercise
Your support bot sends a 5,000-token system prompt with every request. The first line is "Current time: <full timestamp to the second>". Usage data shows a cached-token count of 0 on every call, even though traffic is steady. What is the cause, and what two changes would you make?
Show answer
The timestamp changes on every request, so the first tokens differ and no prefix match is possible. Move the timestamp (or a coarser date) to the end of the prompt, after the stable instructions, and keep the rest of the system prompt byte-for-byte identical, including fixed ordering of tool definitions. Then send the same request twice and confirm the second call reports cached tokens.
Exercise
A nightly job sends one request per hour, each with the same 8,000-token prefix. The provider's cache entries last about five minutes and charge a write premium. Does caching help? What would you check or change?
Show answer
Probably not. Each request arrives after the entry has expired, so every call pays the write premium and none reads from the cache, which costs more than no caching. Check the provider's actual entry lifetime and the hit rate in the usage data. Options: disable caching for this route, or group the work so many requests run within one entry lifetime.