Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 15 steps

AI System Design: Reliable, Fast and Affordable LLM Apps
  1. 1
    Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  2. 2
    Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  3. 3
    Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  4. 4
    A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  5. 5
    Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  6. 6
    Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  7. 7
    LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  8. 8
    Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  9. 9
    Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  10. 10
    Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  11. 11
    Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  12. 12
    Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  13. 13
    Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  14. 14
    A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  15. 15
    A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. AI System Design

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.

Chaand Sheikh

·27 November 2026AI System Design

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.

Right and wrong similarity scores overlap 0.95 Practice right 0.63-0.89 wrong 0.42-0.91 Fresh right 0.77-0.93 wrong 0.16-0.91 0.2 0.4 0.6 0.8 1.0
Synthetic experiment, 32 questions, one small model. Green is right matches, red is wrong ones. They overlap on both sets.

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.

Scope, then age, then similarity 1 Scope company, access, model, prompt version 2 Age past the time limit means stale 3 Similarity the threshold, only the last gate Scope is a rule you enforce; the threshold is a guess you tune
Check scope first, then age, then similarity.

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.
LevelWhat the answer has (a teaching guide, not a measurement)
Weak"Use a high threshold", and reports hit rate
GoodNames false hits, tunes on one set, keeps another set apart, scopes by company
StrongShows the scores can overlap, chooses by cost, scopes everything first, and can switch it off

Recap

IdeaWhat to remember
MatchingOne similarity score against one line; similar questions can need opposite answers
ThresholdIn this experiment, no threshold split right from wrong, and the safest one answered nothing
OrderScope first, then age, then similarity
Never cacheActions, 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?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path AI System Design: Reliable, Fast and Affordable LLM Apps · step 6 of 15

Previous
Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
Next post
LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic

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.

On this page

  • A receptionist answering from memory
  • One score, one line
  • Try every threshold
  • The scores overlap
  • Scope comes first
  • What you never cache
  • The follow-ups
  • Recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.