Module 8 · 4 lessons
Caching for AI features
Three ways to reuse work: exact, prefix and meaning-based caches, and the risk of serving the wrong answer.
Before you start
From this track: Modules 0 to 7. Each module uses only ideas from the ones before it.
Builds on: Caching strategies, Cache eviction and stampedes
Already know these? Start with the first lesson below.
1. Exact-match caches
The picture
Same prompt, same answer
An exact-match cache answers a repeated prompt from storage, but only when every character is the same.
Scene 1 of 4 · The first request
The first "What are your opening hours?" misses the cache, so the model answers and the answer is stored.
- Help page — healthy
- Your backend — healthy
- Answer cache — healthy — 1 answer stored
- Language model — healthy
| Prompt | Cache |
|---|---|
| What are your opening hours? (highlighted) | miss: the model answers, the answer is stored |
- Requests today
- 1
- Model calls
- 1
- The first request. The first "What are your opening hours?" misses the cache, so the model answers and the answer is stored.
- The same again. The other 4,999 identical requests that day come straight from the cache, with no model call.
- One word more. Adding one word, "today", makes a different prompt, so it misses and calls the model.
- Refresh with a TTL. Each answer expires 24 hours after it was stored; the next request after that gets a fresh one.
- Now you try. The cache holds the answer to "What are your opening hours?". Send a new prompt. For example: Cache miss: the backend calls the model. The meaning is the same, but the characters differ, and an exact cache compares characters only.
Scene 1 of 4: The first request. The first "What are your opening hours?" misses the cache, so the model answers and the answer is stored.
Key points
- The cache key is the whole prompt, character for character.
- A repeat answers from storage, with no model call.
- One extra word, a capital letter or a date makes a new prompt.
- A TTL makes old answers expire, so they refresh.
The simplest (A small, fast store that keeps copies of popular data, so most reads skip the slower database.) stores each (Everything sent to a language model in one request: instructions, context and the question.) and its answer. If exactly the same prompt arrives again, the answer comes from the cache, with no model call.
It cannot match the wrong question, since the prompt must be identical. It can still serve an old answer, so each entry needs a time limit. Hits are also rarer than you might hope: one extra word or a changed date makes a new prompt.
In system design: Use an exact cache for repeated, fixed prompts, such as a daily summary, and give each entry a (How long a cached copy is kept before it is thrown away.) so it refreshes.
Where it goes wrong
- A cached answer outlives the facts behind it unless each entry has a TTL or is cleared when the facts change.
- Personal details in the prompt make every key different, so the cache rarely hits, and it stores personal data too.
In an interview
- Say which prompts repeat exactly, what the cache key is, and how long each entry lives.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsCaching strategiesAmazon ElastiCache documentationGeneral caching rules that apply here: cache-aside and a TTL to limit stale answers.
- Official docsPrompt cachingAnthropic docs (one provider)A different cache that reuses work on a shared prompt start. Compare it with caching whole answers.
2. Reusing a shared prompt start
The picture
Read the shared start once
A prefix cache keeps the saved work for a prompt's fixed start, so prefill reads only the new part at the end.
Scene 1 of 4 · The same long start
Every request starts with the same 3,000 tokens of instructions, then a 50-token question.
- Prefill time
- not shown yet
- Input cost (example prices)
- not shown yet
- The same long start. Every request starts with the same 3,000 tokens of instructions, then a 50-token question.
- No prefix cache. Without a prefix cache, prefill reads all 3,050 tokens every time, about 122 ms at the lab's rate.
- Reuse the start. A prefix cache keeps the saved work for the start, so prefill reads only 50 new tokens.
- Often cheaper too. If cached input costs 10% of the price, input drops from $0.00915 to $0.00105 a request.
- Now you try. Lay out the prompt, and see how much of it the cache can reuse. For example: 0 tokens reused, 3,060 read fresh: about 122 ms of prefill. Something that changes sits at the top, so nothing after it can be reused.
Scene 1 of 4: The same long start. Every request starts with the same 3,000 tokens of instructions, then a 50-token question.
Key points
- Most prompts start with the same long instructions.
- A prefix cache keeps the saved work for that shared start.
- Prefill then reads only the new tokens at the end.
- Anything that changes must come last, or nothing after it can be reused.
Many prompts start with the same long instructions and differ only at the end, in the user's question.
A (A cache that keeps a model's saved work for the shared start of many prompts, so only the new part has to be read.) keeps the model's saved work for that shared start, its (The memory where a model keeps its work on every token so far, so each new token does not redo it. It grows by one token per step.) (see How a model writes). Then (The first stage of an answer, where the model reads the whole prompt in one go and saves its work for later steps.) only has to read the new part.
This saves time, and often money, since many providers charge less for input (A piece of text that a language model reads or writes, often part of a word. Prices and limits are counted in tokens.) read from such a cache. The start must match exactly, and the saved work expires, often after a few minutes.
In system design: Put the fixed parts of a prompt first and the changing parts last, so the shared start stays identical and can be reused.
Where it goes wrong
- A changing detail near the top of the prompt, such as today's date, stops reuse for everything after it.
- The saved start expires after a few minutes, so rare traffic gains little. Some providers also charge extra to store it.
In an interview
- Explain why fixed instructions go first and changing parts last, and what that saves in time and cost.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (3)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsPrompt cachingAnthropic docs (one provider)How a cached prompt start is priced, how long it lasts, and what must match exactly.
- Official docsAutomatic Prefix CachingvLLM documentationHow an open-source server reuses the KV cache of a shared prompt start.
- Research paperSGLang: Efficient Execution of Structured Language Model Programs (2023)Zheng et al., NeurIPS 2024RadixAttention: a tree of cached prompt starts shared across requests.
3. Caching by meaning
The picture
3 of 12 new questions reuse a cached answer, saving 3 model calls. 2 of those get the wrong answer. 6 could safely have reused one but did not.
- Reused, right answerNew: “How can I reset my password?”Cached: “How do I reset my password?” · similarity 0.97
- Reused, wrong answerNew: “Is shipping free to the US?”Cached: “Is shipping free to the UK?” · similarity 0.96
- Reused, wrong answerNew: “What time do you open on Sunday?”Cached: “What time do you open on Monday?” · similarity 0.95
- Asks the modelNew: “How do I change my password?”Cached: “How do I reset my password?” · similarity 0.93
- Asks the modelNew: “How do I pause my subscription?”Cached: “How do I cancel my subscription?” · similarity 0.92
- Asks the modelNew: “Where is my parcel?”Cached: “Where is my order?” · similarity 0.91
- Asks the modelNew: “How can I reach customer support?”Cached: “How do I contact support?” · similarity 0.90
- Asks the modelNew: “How do I change my billing address?”Cached: “How do I change my delivery address?” · similarity 0.89
- Asks the modelNew: “Can I buy a gift card?”Cached: “Do you sell gift cards?” · similarity 0.88
- Asks the modelNew: “Can I get my money back?”Cached: “What is your refund policy?” · similarity 0.86
- Asks the modelNew: “How do I delete my last order?”Cached: “How do I delete my account?” · similarity 0.84
- Asks the modelNew: “Can I pay by card?”Cached: “Which payment methods do you take?” · similarity 0.80
What this simplifies. The questions and their similarity scores are made up to show the idea. Real scores come from comparing embeddings. The right threshold depends on the model and the kind of question, so teams test it on real traffic.
A (A cache that reuses an answer when a new question is close in meaning to one already answered, not only when it is identical.) compares the (A list of numbers that stands for the meaning of a piece of text. Texts with similar meanings get similar lists.) of a new question with the questions it has already answered. It reuses an answer when the two are close enough.
How close counts as close enough is a threshold you choose. A lower threshold reuses more answers and saves more model calls.
But close in meaning is not the same as the same answer. "Is shipping free to the UK?" and "Is shipping free to the US?" look almost identical.
In system design: Start with a high threshold and check samples of reused answers. Avoid caching by meaning where a wrong answer is costly.
Where it goes wrong
- Two questions that look alike can need different answers, such as the UK and the US. A loose threshold serves the wrong one.
- An answer about one user's account must never be reused for another. Keep such questions out, or add the user to the key.
In an interview
- Say how you set the threshold, and how you would check samples of reused answers.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Official docsGPTCacheZilliz on GitHubAn open-source semantic cache: embed the question, find a close one, reuse its answer.
- Official docsEmbeddingsGoogle Machine Learning Crash CourseWhy close vectors mean similar text, and why “close” needs a threshold.
4. When caching goes wrong
The picture
The right answer for the wrong person
A shared cache keyed only on the question can hand one customer's answer to another, and any cached fact can go stale.
Scene 1 of 4 · Customer A asks
user:42 asks "Where is my order?", and the model answers that order 1187 is out for delivery.
- user:42 — healthy — order 1187
- user:77 — healthy
- Your backend — healthy
- Shared cache — healthy — stores order 1187
- Language model — healthy
| Customer | Cache key | Gets | Check |
|---|---|---|---|
| user:42 (highlighted) | "Where is my order?" | order 1187 | their own |
- Customer A asks. user:42 asks "Where is my order?", and the model answers that order 1187 is out for delivery.
- Customer B asks. user:77 sends the same words, and a cache keyed on the question alone returns user:42's order.
- User in the key. With the user in the key, user:77 misses the cache and gets order 2240, their own.
- Facts change too. A cached price or policy goes stale when it changes, so each entry needs a TTL or a clear.
- Now you try. Choose the cache key for "Where is my order?", and see what user:77 gets. For example: user:77 gets order 1187, which belongs to user:42; the two requests make 1 model call. The key holds only the words, so user:77 gets the answer stored for user:42: wrong, and a privacy leak.
Scene 1 of 4: Customer A asks. user:42 asks "Where is my order?", and the model answers that order 1187 is out for delivery.
Key points
- The same words can need a different answer for each user.
- Put the user in the key, or keep the question out of the cache.
- Cached facts go stale when a price or policy changes.
- Give entries a TTL, or clear them when the facts change.
A cached answer goes stale when the facts behind it change, such as a price or a policy. So entries need a TTL, or must be cleared when the facts change.
A cache shared between users must never mix up personal data: one customer's order status is not an answer for another.
Keep personal or account questions out of shared caches, or include the user in the cache key as well as the question.
In system design: Decide for each feature what may be cached, for how long and for whom, before turning a cache on.
Where it goes wrong
- A price change leaves cached answers wrong until they expire. Clear the related entries when the facts change.
- One bad answer stored in a shared cache is served to everyone who asks. Check answers before you store them.
In an interview
- For each cached feature, say what may be cached, for whom, and for how long.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Engineering guideOWASP Top 10 for LLM Applications: LLM02 Sensitive Information DisclosureOWASP GenAI Security ProjectHow a shared cache can show one user’s private data to another.
- Official docsCaching strategiesAmazon ElastiCache documentationUsing a TTL and clearing entries so cached answers do not go stale.