Learning path: AI System Design: Reliable, Fast and Affordable LLM Apps · Step 6 of 15
Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
A semantic cache answers a question that sounds like an old one with the old answer. On 32 synthetic questions, "monthly plans" matched "annual plans" at 0.91, right and wrong scores overlapped, and the only threshold with zero false hits answered nothing on fresh questions.
What you will learn
- Explain how a semantic cache decides a hit: one similarity score against one threshold
- Read a threshold sweep in hits, false hits and misses, and see why the safest threshold answered nothing
- Show why right and wrong matches can have overlapping scores
- Put scope and age before similarity, and keep actions and personal answers out of the cache
Before you start
- Caching for AI Apps
- Word Embeddings and Cosine Similarity
A semantic cache gives a question that sounds like an old one the old answer. The interview question: product wants a semantic cache to cut LLM spend by 40%. Design it, and stop it giving a confidently wrong answer. The 40% is the interviewer's ask, not a result. Most people say "use a high threshold" and move on, so let's test that. Everything here comes from a small experiment: synthetic questions, fixed answers, the small embedding model all-MiniLM-L6-v2, and a simulated clock. The result isn't neat, and that's exactly why it's worth seeing.
A receptionist answering from memory
Picture a gym receptionist. Someone asks, "What's the refund window on annual plans?" She looks it up, says 30 days, and remembers it. The next person asks, "Refund period for a yearly plan?" Different words, same meaning, so she answers from memory. Correct, and fast.
Then someone asks about monthly plans. It sounds nearly the same, so she says 30 days again, and nobody notices. Or take an example that isn't from our experiment: "cancel my order" and "don't cancel my order". Nearly the same words, opposite meanings. A semantic cache matches on how close a question sounds, and close isn't the same as correct.
One score, one line
The question goes into an embedding model and comes out as a vector (see Word Embeddings and Cosine Similarity). The cache compares it with every stored question and keeps the closest, which gives one score. At or above the threshold, you return the stored answer and skip the model. Below it, the question takes the normal path. The whole decision is one number against one line.
With 8 stored synthetic questions, these were the closest wrong matches:
closest wrong questions (score):
0.91 What is the refund window for monthly plans?
0.91 What is the refund window for quarterly plan
0.88 How do I disable two-factor login?
0.87 How do I import invoices from a PDF?
Monthly plans scores 0.91 against the annual question, so the cache hands back 30 days, fast and wrong. Disable two-factor login scores 0.88 against enable. Import invoices scores 0.87 against export. The score says the questions are close. It can't say they need the same answer.
Try every threshold
So let's tune it. Sixteen practice questions: 8 rewordings, where a hit is right, and 8 look-alikes, where a hit is wrong. Seven thresholds:
model all-MiniLM-L6-v2, 8 stored, 16 dev, 16 test
dev sweep: thr hits false missed
0.60 8 6 0
0.70 6 4 2
0.75 5 4 3
0.80 3 3 5
0.85 2 3 6
0.90 0 1 8
0.95 0 0 8
picked 0.95: lowest, 0 false hits on dev
test at 0.95: 0/8 hits, 0 false, 8 missed
At 0.6 we catch all eight rewordings and also give six wrong answers. At 0.85 there are more wrong hits than right ones. Only 0.95 has zero false hits, so a careful rule picks it. Then on 16 fresh questions: 0 of 8 right, 0 wrong, 8 missed. That zero looks perfect, and it's only there because the cache never answered anything.
The scores overlap
Why? Put every score on one line.
On the practice set, the highest wrong score (0.91) sits above the highest right score (0.89). So a line that lets the right matches through lets wrong ones through too. On the fresh set it overlaps again. On both sets, every threshold we tried that gave right answers gave wrong ones too. To be fair, that's 32 synthetic questions and one small model, so it isn't a law. But here the threshold couldn't carry the job alone.
Scope comes first
Now the part a threshold can't touch. One question, asked six ways, with the threshold at 0.7 (a setting for the experiment, not a recommendation) and a simulated clock:
policy at 0.7 (simulated clock):
same tenant hit
other tenant empty
other tenant, no scope hit
new model empty
new prompt empty
after ttl stale
Another company gets nothing, because its entries were filtered out before any score was computed. Switch that filter off, and the other company gets a hit: one company reading another company's answer, and the score can't warn you. Change the model or the prompt version and the cache is empty, so old answers don't come back. Move the clock past the time limit and the entry is stale.
The exact-key version of this idea, with deletes and versions, is in Caching for AI Apps.
What you never cache
Some questions shouldn't reach the gate at all. These are design ideas, not things the experiment tested:
- Actions. "Cancel my order" is something to do, so it never comes from memory.
- Personal answers, like "what's my balance".
- Facts that change quickly.
Keep it to question types with stable answers, where a wrong match costs little. When a policy document changes, its version changes, and that version is part of the scope, so old entries can't be matched. If it still doesn't hold up, switch it off for that question type. A miss costs a model call. A false hit costs someone a wrong answer.
The follow-ups
- Can you promise that 40%? No. In this experiment, the safest threshold answered nothing. Label false hits on your own traffic, and report hit rate and false-hit rate together.
- You change the embedding model. Is the threshold still good? Tune again on labelled questions. Old entries stay out because the model is in the scope.
- How do you check it over time? Sample the cached hits, answer them again without the cache, and compare.
| Level | What the answer has (a teaching guide, not a measurement) |
|---|---|
| Weak | "Use a high threshold", and reports hit rate |
| Good | Names false hits, tunes on one set, keeps another set apart, scopes by company |
| Strong | Shows the scores can overlap, chooses by cost, scopes everything first, and can switch it off |
Recap
| Idea | What to remember |
|---|---|
| Matching | One similarity score against one line; similar questions can need opposite answers |
| Threshold | In this experiment, no threshold split right from wrong, and the safest one answered nothing |
| Order | Scope first, then age, then similarity |
| Never cache | Actions, personal answers, fast-changing facts |
Try it yourself
Take two similar questions from a product you know, and ask whether one answer really fits both. If not, what in the scope would keep them apart?
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.