Learning path: AI System Design: Reliable, Fast and Affordable LLM Apps · Step 5 of 15
Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
A support bot's cache can hit 97% of requests and still answer only 52% correctly. Four cache layers, the key each one needs, how a document delete has to travel through all of them, and a 200-request simulation that puts hit rate next to correct answers.
What you will learn
- Name the four places an AI request can be cached: prompt prefix, embedding, retrieval and exact response
- Build each cache key from everything that could change the result: company, access, index version, model and prompt version
- Follow one deleted document through every cache layer
- Report hit rate next to correct answers, because a high hit rate alone can hide leaks and stale answers
Before you start
- The RAG Pipeline Explained
- LLM Tokens, Context Windows and Cost
"Just add a cache" sounds like the easy interview answer. But a cache can look great on a dashboard and still hand out wrong answers. Here's the question you'll get: design the cache layers for a support bot, and show how a document deletion moves through every layer. We'll answer it in four steps: the layers, the keys, the delete, and how to measure it. Every number below comes from a small simulation with a fake model, not from a real provider.
The stapler on your desk
The store room has plenty of staplers, but it's a long walk every time. That walk is your model call. So you keep one on your desk, and now it's right there. That's a cache.
Then the store room recalls that stapler, and nobody tells your desk. Your copy just carries on. That's a stale entry. And if another company shares the desk, they'll pick up your things too. That's a leak. A copy close by is fast, and it has to know two things: whose it is, and when it goes out of date.
Three wrong answers out of four
Start with the simplest cache: a plain response cache that only looks at the question. Two companies, Acme and Globex, share it. Acme's refund policy is 30 days, Globex's is 14.
SIMULATED: fake model, 2 tenants, seed 7
-- naive cache
acme_first: Answer: Refunds within 30 days.
globex_second: Answer: Refunds within 30 days.
acme_after_update: Answer: Refunds within 30 days.
acme_after_delete: Answer: Refunds within 30 days.
llm_calls: 1
Acme asks first and gets 30 days, which is right. Globex asks the same thing and also gets 30 days: that's Acme's policy, a leak. Acme changes its policy to 45 days and still gets 30: stale. Acme deletes the document and still gets 30. That's one model call and three wrong answers out of four, and nothing looked slow.
Four layers
An AI request has four places you can cache. This part is a description of the idea; the simulation only exercises the last one, the response cache.
- Prompt prefix. Some model providers can reuse the work on the start of a prompt, so the stable part goes first.
- Embedding. The same text with the same embedding model gives the same vector, so you don't compute it twice.
- Retrieval. For this question, the documents that came back.
- Exact response. Same question, same context, same answer. It saves a whole model call.
What goes in each key
The key is the label an entry gets stored under. The rule is simple: anything that could change the result goes in the key.
| Layer | Key contains |
|---|---|
| Prompt prefix | Model + the stable part of the prompt (the provider usually handles this, so keep private text out of a shared prefix) |
| Embedding | Embedding model + text |
| Retrieval | Company + the person's access scope + index version + question |
| Response | Everything above + model + prompt version |
Now Acme and Globex can't share an entry, and when a version changes, the old entry simply can't be found any more.
How a delete travels
Follow one deleted document. This walk through the layers is a picture of the idea; only the four answers at the end come from the run.
Here are the same four questions with the better, scoped key:
-- scoped cache
acme_first: Answer: Refunds within 30 days.
globex_second: Answer: Refunds within 14 days.
dropped: 2
acme_after_update: Answer: Refunds within 45 days.
acme_after_delete: I could not find that.
llm_calls: 3
Acme gets 30, Globex gets 14, the update gives 45, and after the delete the bot says it can't find it. That took three model calls instead of one, and every answer was right.
The number that fools you
Now the full comparison: 200 simulated requests and three caches. This is a small simulation, not a benchmark.
-- 200 simulated requests
naive no-call 97% correct 52% leaked 81 stale 15 llm 6
ttl no-call 74% correct 68% leaked 63 stale 0 llm 51
scoped no-call 93% correct 100% leaked 0 stale 0 llm 14
- Plain cache: 97% of requests made no model call. That's the dashboard number. Only 52% were correct; 81 leaked and 15 were stale.
- Add a time limit (TTL), the usual first answer: no-call drops to 74%, correct only reaches 68%, and 63 still leak. Stale went to zero here, but a time limit can't stop a leak.
- Better key: 93% no model call, 100% correct, nothing leaked, nothing stale. That's 14 model calls against 6, and that's the price of being right.
Quote the habit, not the numbers: hit rate goes next to correct answers. A high hit rate says the cache answered, not that it was right. The same idea appears in a recommendations service in Serving With a Cache and a Popular Fallback.
The follow-ups
- Time limit or events? Events for updates and deletes, so the change moves right away. Keep a time limit as the backstop for an event that gets lost.
- How do you test for hits across companies? Ask the same question as two companies, and count any answer that came from the other one. That count must stay at zero.
- How do you know the hits are right? Sample some hits, answer them again without the cache, and compare.
A simple rubric, as a teaching guide:
| Level | What the answer has |
|---|---|
| Weak | Names a cache and quotes the hit rate |
| Good | The layers, a time limit, and the company in the key |
| Strong | Versions in the key, a delete followed through every layer, correct answers measured beside the hit rate, and what's still not solved |
When the cache matches questions by meaning instead of exact text, a new failure appears. That's the next article: Semantic Caching and False Hits.
Recap
| Idea | What to remember |
|---|---|
| Four layers | Prefix, embedding, retrieval, response; the closer to the answer, the more it saves and the more it can get wrong |
| Keys | Anything that changes the result goes in the key |
| Deletes | A delete has to reach every layer, removed, not hidden |
| Measure | Hit rate next to correct answers (simulated: 97% hits, 52% correct) |
Try it yourself
Pick one cached answer in an app you know, and say out loud what happens to it when its source document is deleted. Which layers still hold a copy?
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
When the main model goes down, the backup has to be allowed to take the data, able to read the whole request and tested before the bad day. A simulated four-model chain for an EU customer: a 6,000-token request lands on mid-eu, flagged degraded; a 10,000-token request is served by nobody, on purpose.
Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
A bulk upload buries the chat. In a small simulation, one shared queue grows to 199 waiting and the middle chat answer takes 80.2 s. A bound plus a chat lane brings it to 0.35 s while 178 bulk jobs are told to retry in 10 s, and cancelling abandoned calls saves 21,000 wasted tokens.
Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
Six GPU replicas, two at 95% and four at 30%: round robin counts requests, and requests aren't equal. In a small simulation, least outstanding requests cuts p95 from 6.52 s to 3.05 s, prefix affinity lifts cache hits to 95% but pushes p95 to 11.45 s, a real health check takes errors from 48 to 2, and draining cuts 0 answers instead of 4.
A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
A queue doesn't lose a document, but it can hand one out twice. In a small simulation, a worker crash makes document two go from 3 to 6 chunks and the index holds 11 when the documents hold 8. An idempotent consumer brings it back to 8 with the same two deliveries, and a limit of three tries moves a poison file to a dead letter queue.