Home / AI Architecture & System Design / AI System Design
Explain semantic caching and its risks.
30-second answer
Store past query embeddings with their answers; for a new query, return a cached answer if a previous query is similar enough. It saves cost and latency for repetitive traffic. Risks: near-identical questions can need different answers ("cancel my order" vs. "don't cancel my order"), personalization and permission differences, and stale answers. Use conservative thresholds, scope caches by user/tenant, add TTLs, and evaluate false-hit rates.
Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.
New to these terms? 9 terms on this page are explained in the glossary
0–5 min Functional requirements
A semantic cache returns a stored answer when a new question is "similar enough" to an old one. Whether that's safe depends entirely on the traffic, so ask about it first.
You What's the product, and how repetitive are the questions?
Interviewer A public help assistant for a SaaS product, about 2 million questions a day. People ask the same things in many ways: "how do I reset my password", "forgot password", "can't log in, reset?"
You Are answers personalized, or the same for everyone?
Interviewer Mostly the same, but they differ by plan (Free, Pro, Team), language and product version. Some questions are about the user's own account.
You How often does the underlying content change?
Interviewer Help articles change daily; pricing changes a few times a year.
You What's the goal: cost or latency?
Interviewer Both. LLM spend is high, and cached answers would be instant.
| # | Functional requirement | Why it matters |
|---|---|---|
| F1 | Return a cached answer when a new question is equivalent to a previously answered one | The core value |
| F2 | Scope the cache by tenant, language, product version and plan | The same question has different answers in different scopes |
| F3 | Never cache personal, account-specific or action-taking requests | Those answers are wrong for anyone else |
| F4 | Invalidate entries when their source articles change | Stale answers erode trust |
| F5 | Let operators bypass or disable the cache instantly | Safety valve |
| F6 | Measure hit rate and false-hit rate | Hit rate alone rewards dangerous caching |
5–10 min Non-functional requirements and estimates
You The key quality metric is the false-hit rate: how often a cached answer doesn't actually answer the new question. What's acceptable?
Interviewer Very low. A wrong answer is worse than a slow one.
You Then I'll set a strict target, verify every hit before serving it, and accept a lower hit rate.
| Requirement | Target | What it forces in the design |
|---|---|---|
| False hits | ≤ 1 in 1,000 served hits | High threshold, verification step, entity checks |
| Lookup latency | ≤ 40 ms p95 including verification | Small embedding model, in-memory ANN, small verifier |
| Hit rate | ≥ 25% of eligible traffic (otherwise not worth it) | Measure the potential from logs before building |
| Freshness | Invalidation ≤ 5 min after an article changes | Track source articles per entry |
| Availability | Cache failure falls through to the normal path | The cache is never on the critical path for correctness |
Back-of-envelope estimates:
- Potential hit rate: cluster a week of logged questions by meaning. If ~35% fall into clusters whose answers are identical, a realistic served hit rate after safety checks is ~25%.
- Savings: 2M questions/day × 25% × ~$0.01 per LLM answer ≈ $5,000/day, and those users get instant answers.
- Cache size: ~1.4M new entries/day × a 24-hour TTL ≈ 1.4M live entries. Each holds a 1,024-dim vector (4 KB) plus answer and metadata (~2 KB): ~8–9 GB. Fits in memory on a couple of nodes.
- Lookup cost: one query embedding (~5–10 ms), an ANN search (~5 ms) and a verifier call only on candidate hits (~15 ms).
10–18 min High-level design
You The cache sits in front of the normal LLM path. Requests are rewritten to stand alone, checked for eligibility, embedded and looked up within their scope. A candidate hit is served only after an equivalence check; otherwise the LLM answers and the answer is stored with the articles it used.
Scroll sideways to see the whole diagram.
Components:
- Eligibility check: the intent router flags personal ("my invoice"), action ("cancel my plan") and time-sensitive questions as uncacheable.
- Query rewrite: turns follow-ups into standalone questions; only standalone questions are cached.
- Embedder: a small embedding model for questions.
- Semantic cache: an in-memory vector index partitioned by scope key, with entries
{question, embedding, answer, source_doc_ids, created_at, ttl}. - Equivalence verifier: a cross-encoder or small model that confirms the two questions ask the same thing, with an entity check (plan names, product names, numbers).
- Invalidation service: maps article IDs to cache entries and deletes them when articles change.
One request, hit and miss:
Scroll sideways to see the whole diagram.
Internal API:
lookup(question, scope) → { hit: bool, answer?, entry_id?, similarity? }
store(question, scope, answer, source_doc_ids, ttl)
invalidate(doc_id) → entries removed
scope = (tenant, locale, product_version, plan)
How it works: a worked example
A study aid: three questions traced through the cache: a safe hit, a near-miss that the verifier catches, and a request that isn't eligible at all.
Setup. Scope key (tenant=acme, locale=en, product=v12, plan=pro). Yesterday someone asked "How do I export my data to CSV?"; the answer (built from article kb-551) is cached:
{ "entry_id": "sc_9a1", "question": "How do I export my data to CSV?",
"embedding": [0.012, -0.044, …], "answer": "Go to Settings → Data → Export and choose CSV… [kb-551]",
"source_doc_ids": ["kb-551"], "created_at": "2026-11-15T09:12Z", "ttl_s": 86400 }
Question 1: "how can i download my data as a csv file"
- Eligibility: router says
how_to, not personal, not an action → eligible. - Embed (~6 ms) and search the scope's index (~4 ms): nearest is
sc_9a1, cosine similarity 0.94 (threshold 0.90). - Verifier (cross-encoder, ~15 ms):
same_question = 0.97. Entity check: both mention CSV; no plan names or numbers differ. Serve the cached answer. - Total ~30 ms instead of ~2.5 s, and $0 instead of ~$0.01. The hit is logged with the similarity and verifier score.
Question 2: "How do I export my data to Excel?"
- Nearest entry is again
sc_9a1, similarity 0.92 (above threshold). - Verifier:
same_question = 0.31. Entity check: "Excel" vs "CSV" differ. Rejected: this is the false hit the verifier exists to stop. - The normal LLM path answers; the new answer is stored as a new entry with its sources.
Question 3: "Why was my invoice higher this month?"
- Router marks it
personal(depends on this user's account). Not eligible: skip the cache entirely and never store the answer.
Invalidation. At 14:00 article kb-551 is edited. The CMS webhook calls invalidate("kb-551"); the reverse index doc_id → entry_ids finds sc_9a1 and 37 other entries and deletes them within seconds. The next question rebuilds the answer from the new article.
Where each piece runs:
| Component | Runs as | Example technology | Sizing (2M questions/day) | If it fails |
|---|---|---|---|---|
| Embedder | Small embedding model | Self-hosted on CPU/GPU or hosted API | ~25 embeddings/s average | Skip the cache (treat as miss) |
| Cache index | In-memory ANN per scope, replicated | Redis with vector search, or an in-process HNSW | ~1.4M entries, ~8–9 GB | Miss; requests go to the LLM path |
| Verifier | Cross-encoder service | Small GPU replica | Only on candidate hits | Treat as miss |
| Reverse index | Key-value map doc → entries | Redis sets | Updated on every store | If unavailable, shorten TTLs until fixed |
| Hit/miss log | Async events | Event stream → warehouse | 2M events/day | — |
The design principle in this trace: the cache can only ever make a request faster, never wrong. Every uncertain case falls through to the normal path.
18–32 min Deep dive
You The hard parts are deciding what's cacheable, deciding when two questions really match, and keeping answers fresh. I'd also like to cover how to measure false hits safely.
Interviewer Start with matching. Isn't a similarity threshold enough?
Deep dive 1 · When do two questions match?
Embedding similarity measures topic closeness, not equivalence. Close-but-different pairs are common:
| New question | Cached question | Similarity | Same answer? |
|---|---|---|---|
| "How do I reset my password?" | "Forgot my password, how to reset" | 0.95 | Yes |
| "How much is the Pro plan?" | "How much is the Team plan?" | 0.96 | No |
| "Can I cancel my order?" | "How do I not cancel my order?" | 0.93 | No |
| "Export data to CSV" | "Export data to Excel" | 0.94 | No |
So use three layers:
- Similarity threshold (e.g. ≥ 0.93) to find a candidate cheaply.
- Entity check: extract plan names, product names and numbers from both questions; any mismatch is a miss. Adding these entities to the scope key prevents many false hits outright.
- Equivalence verifier: a cross-encoder trained on question pairs (or a small LLM) answers "do these ask the same thing?". Only hits that pass are served.
Choosing the threshold with a labelled set of question pairs (illustrative numbers):
| Threshold | Candidate hit rate | False hits before verifier | After verifier |
|---|---|---|---|
| 0.88 | 41% | 6.0% | 0.4% |
| 0.91 | 33% | 2.1% | 0.15% |
| 0.93 | 27% | 0.8% | 0.06% |
| 0.95 | 18% | 0.3% | 0.02% |
Pick the lowest threshold that meets the false-hit target after verification, here 0.93.
Interviewer How do you keep answers fresh when an article changes?
Deep dive 2 · Invalidation and freshness
Scroll sideways to see the whole diagram.
- Every cache entry records the article IDs its answer was built from.
- The CMS publishes an event when an article changes; the invalidation service looks up dependent entries in a reverse index (
doc_id → entry_ids) and deletes them. - TTL (e.g. 24 hours) as a safety net for anything missed.
- Versioned scope keys: when a product version ships or pricing changes, bump the version in the scope key; old entries simply stop matching.
Deep dive 3 · What not to cache
- Personal questions: "What's on my last invoice?" Detected by the intent router or by references to account data.
- Actions: "Cancel my subscription." These should never be answered from a cache.
- Time-sensitive questions: "Is the service down right now?"
- Low-confidence answers: if the original answer was a handoff or "I'm not sure", don't cache it.
- Answers that used tools or account data.
A safer alternative for borderline traffic is to cache retrieval results instead of answers: reuse the retrieved articles for similar questions, but still generate a fresh answer for the exact wording.
Deep dive 4 · Measuring false hits safely
- Shadow mode first: for a week, compute would-be hits without serving them, generate the fresh answer as usual, and have a judge compare the cached and fresh answers. This gives a false-hit estimate before any user sees a cached answer.
- In production: sample ~1% of served hits for automated judging and a smaller sample for human review. Track false hits by category and scope.
- Kill switch per tenant and per category if the false-hit rate rises.
- User signals: thumbs-down and immediate rephrasing after a cached answer are strong false-hit indicators.
32–37 min Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Matching | Threshold + entity check + verifier | Threshold only | Similar ≠ same; verification makes strict false-hit targets reachable |
| Scope | Tenant, locale, version, plan in the key | Global cache | Same wording, different correct answers |
| What's cached | Standalone, generic questions only | Everything | Personal and action answers are wrong for others |
| Freshness | Source-tracked invalidation + TTL | TTL only | Article changes reach users in minutes |
| Rollout | Shadow mode, then sampled audits | Turn it on and watch hit rate | Hit rate rewards wrong answers |
| Alternative | Cache retrieval results for borderline intents | Cache final answers | Lower risk, still saves retrieval time |
Build first: an exact-match cache with scoping and invalidation (zero false-hit risk), then add the semantic layer in shadow mode with the verifier, then serve.
37–40 min Wrap-up and likely follow-ups
Close with: "I'd only cache standalone, generic questions, scoped by tenant, locale, version and plan. Candidate matches come from a similarity threshold, but a hit is served only after an entity check and an equivalence verifier. Entries track their source articles for fast invalidation, and false hits are measured in shadow mode before launch and by sampling afterwards."
Likely follow-ups:
- How is this different from prompt caching? Prompt caching reuses the provider's computation for an identical prompt prefix; the output is still freshly generated, so there's no correctness risk. A semantic cache reuses the output itself.
- Does it work for multi-turn chat? Only after rewriting the latest turn into a standalone question; otherwise context changes the meaning.
- Where would you store the cache? An in-memory vector index with TTL support, partitioned by scope; Redis with vector search or a vector database both work at this size.
What interviewers listen for
- Concrete false-hit examples and a layered matching strategy.
- Scoping and exclusions (personal, actions, time-sensitive).
- Source-tracked invalidation.
- Measuring false hits, not just hit rate.
Red flags
- A single similarity threshold as the whole design.
- Caching personalized answers globally.
- Reporting hit rate as the success metric.
Discussion
Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.