Course contents

16. AI System Design Lesson 9 of 10

Semantic Caching

See a semantic cache embed prompts and skip LLM calls on similar questions, why a looser threshold causes false hits, and how to invalidate safely.

15 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Exact-match caches rarely hit natural-language prompts, because people phrase the same question differently.
  • A semantic cache embeds the prompt, finds the nearest stored prompt and reuses its answer above a similarity threshold.
  • Hits skip a slow, billed generation, so the cache becomes part of model capacity.
  • A lower threshold always raises the hit ratio and silently adds wrong answers; tune it on labelled pairs.
  • Invalidate by source and version tags rather than flushing a cache that carries load.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A semantic cache stores LLM responses keyed by the meaning of the prompt instead of its exact text. Each cached entry holds an embedding of the prompt (a vector), the response and metadata. For a new prompt the application computes its embedding, searches the cache's vector index for the most similar stored prompt, and returns the stored response if the similarity is above a threshold. Otherwise it calls the model and usually stores the new pair.

Why it exists

LLM calls are slow (hundreds of milliseconds to many seconds) and billed per token, and model deployments have limited concurrency. Many applications, especially support and documentation assistants, receive the same questions over and over in different words. An ordinary cache keyed by the prompt string misses almost all of them. Matching by meaning lets one generated answer serve many phrasings, cutting latency, spend and load on the model.

How it works

Lookup. Normalise the prompt (strip boilerplate, maybe keep only the user's question, not the whole conversation), embed it with an embedding model, run a nearest-neighbour search (top-1 or top-k) in a vector index, and compare the best similarity (commonly cosine) with the threshold. The embedding call and the search add a few to tens of milliseconds to every request, including misses.

Scope and keys. Combine the vector match with exact filters: tenant, language, product or plan, model and prompt version. Only entries in the same scope can match. Personal or account-specific answers are not cached at all, or cached per user.

Threshold. The single most important setting. Higher means fewer but safer hits; lower means more hits and more false hits (a stored answer to a different question). The right value depends on the embedding model and the domain; find it by labelling pairs of real questions as same/different and measuring precision and recall at each threshold. Some systems add a second check on candidate hits (a re-ranker or a small model judging equivalence) to allow a lower first-stage threshold.

Writes. On a miss, store the prompt embedding, response and metadata: source documents used (for RAG), model and prompt version, creation time and TTL. Store only responses you would be happy to serve again: not errors, refusals caused by transient issues, or answers flagged by users.

Invalidation. Use a TTL as a safety net; delete entries whose source documents changed (by the stored source ids); and put model and prompt versions in the namespace so a change starts a new, gradually warmed cache. Avoid flushing everything at once if the cache carries significant load.

When to use it

  • High repetition of semantically equivalent questions: FAQs, help centres, internal documentation, product information.
  • Answers that do not depend on the asker, or that can be scoped by a small set of exact parameters.
  • Model latency or cost is a real problem and some staleness is acceptable.

When not to

  • Personalised answers, or anything that reads the user's own data.
  • Agents and tool calls with side effects: a cached "I've issued the refund" is a lie.
  • Creative or open-ended generation where variety is expected.
  • Low-repetition traffic: you pay the lookup on every request and rarely hit.
  • Domains where small wording differences change the answer (legal, medical dosing, numbers), unless the threshold is very strict and verified.

Trade-offs

Choice You gain You pay
Semantic instead of exact-match cache Far more hits on natural language Embedding and search on every request; false hits
Lower similarity threshold Higher hit ratio, lower cost More wrong answers, invisible to system metrics
Verification step on hits Lower threshold with fewer false hits Extra latency and cost on every hit
Long TTL More hits Staler answers after changes nobody tagged
Caching full conversations vs last question Context-correct answers Far fewer hits

Alternatives

  • Exact-match response cache: safe and cheap; works for deterministic, repeated requests (classification of identical inputs, retries).
  • Provider prompt caching: reuses the processing of an identical prompt prefix (system prompt, documents) to reduce cost and latency of the call; the answer is still generated fresh.
  • Precomputed answers: curate the top questions and their answers; route to them with intent classification.
  • Smaller or cheaper models for easy questions, routed by a classifier or a gateway.

Failure modes

  • False hits: similar wording, different meaning (negation, numbers, entity names, "cancel order" vs "cancel subscription"). The user gets a fast, confident, wrong answer.
  • Cross-user leaks: an answer containing one user's data served to another because the cache was not scoped.
  • Stale answers after the underlying facts change.
  • Flush storms: invalidating everything sends all traffic to the model at once, as in the simulation; with capacity sized around the hit ratio, that is an outage.
  • Cache poisoning: a bad or manipulated answer gets cached and served to everyone. Do not cache answers from untrusted contexts, and let users' negative feedback evict entries.
  • Cache down: if lookups fail, every request goes to the model. Fail open to the model, but know whether the model can take the full load.

In production

Measure false-hit rate as well as hit ratio: sample hits for review, track thumbs-down on cached answers separately, and re-run threshold evaluation whenever you change the embedding model. Log for each response whether it came from the cache and which entry, so you can trace and evict. Keep the embedding model stable, since changing it invalidates every stored vector. Size the model deployment for some drop in hit ratio, warm a new namespace gradually, and invalidate by source tags. Put the cache in front of the model call in a gateway or a shared library so policies are consistent.

Common misconceptions

  • "Higher hit ratio is always better." Only if the hits are right. Past a point, more hits means more wrong answers.
  • "Semantic caching is the same as prompt caching." Prompt caching makes a call cheaper; semantic caching skips it and reuses an old answer.
  • "Embeddings understand the question." They capture overall topic and intent well and details poorly.
  • "A cache never makes things worse." Every miss pays the lookup, and a flush can overload the model you were protecting.

Interview angle

When designing a high-traffic assistant, propose a semantic cache for repeated, non-personal questions, then show you know its limits: how the threshold was chosen (labelled pairs), how the cache is scoped (tenant, locale, version), what is never cached (personal, tool-using), how entries are invalidated (source tags, TTL, versioned namespaces) and how you measure false hits. Capacity math helps: "20 questions/s at 40% hits is 12 model calls/s against 16 of capacity; if the cache drops, we overload, so we fail open but also shed or queue".

Model assumptions

The simulation is a simplified queueing model, not a benchmark. The LLM has 24 concurrent slots and a 1.5 s mean call time (lognormal, cv 0.5), about 16 calls per second. The engine does not compare meanings: the semantic cache is modelled as a fixed hit probability with a 30 ms lookup that stands for embedding plus vector search, and the hit ratios (5% exact, 40% at 0.90, 60% at 0.80) are illustrative for an FAQ-heavy workload. After a flush, the hit ratio is stepped back up by scripted updates rather than emerging from traffic. False hits are not simulated, and one request's path through the embedding model is drawn as scripted packets. Arrivals are Poisson; network hops are fixed. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Every question is a model call

    A support assistant gets about 10 questions per second. Each one is a full LLM call: about 1.5 s and a few thousand tokens. The model deployment can run 24 calls at once, roughly 16 per second, so it is a bit over 60% busy.

    Many of those questions are the same question: how to reset a password, where an invoice is, how refunds work. We pay full price, in time and tokens, every time.

    Scene: Users send 10 questions per second to the Support API, which calls the LLM for every one. The LLM is a bit over 60% busy; median latency is over a second.

    Key idea: LLM calls are slow and billed per token; repeated questions repeat the whole cost.

  2. 2. An exact-match cache barely helps

    We add a normal cache keyed by the prompt text. It answers repeats in a couple of milliseconds, but only if the text is identical. “How do I reset my password?”, “forgot my password” and “password reset not working??” are three different keys.

    In this workload only about 5% of questions hit. The LLM is almost as busy as before.

    Scene: An exact-match cache sits in front of the LLM. Only about 5% of questions hit it; the LLM stays almost as busy as before.

    Key idea: People rarely ask the same thing in the same words, so exact-match caching of natural-language prompts hits rarely.

  3. 3. Match by meaning: embed, search, compare

    The semantic cache stores each answered question as an embedding (a vector that represents its meaning) next to the answer. For a new question the API embeds it, searches the vector index for the nearest stored question and, if the similarity is above a threshold (0.90 here), returns that stored answer. The scripted request above shows this path.

    Now about 40% of questions hit (an illustrative figure for an FAQ-heavy workload). Hits come back in about a tenth of a second instead of 1.5 s, and the LLM handles 40% fewer calls. Every request, hit or miss, pays the lookup (about 30 ms) first.

    Scene: The Support API embeds each question, searches the semantic cache for the nearest stored question and returns its answer if it is similar enough. About 40% of questions hit; the LLM gets 40% fewer calls and median latency drops.

    Key idea: A semantic cache trades a cheap embedding and vector search for a chance to skip an expensive generation.

  4. 4. The cache is now capacity

    One second in, traffic doubles to 20 questions per second. Without a cache that would be more than the deployment’s 16 calls per second: queues, then rejections.

    With 40% answered from the cache, the LLM sees about 12 calls per second and is around 75% busy. Nothing fails. That is useful, and a warning: once you size the model deployment assuming the hit ratio, a drop in hit ratio becomes an outage.

    Scene: Traffic doubles to 20 questions per second. With 40% cache hits the LLM handles about 12 calls per second, is about 75% busy and nothing fails.

    Key idea: A cache that absorbs load becomes part of your capacity plan, so losing it hurts.

  5. 5. Lowering the threshold: more hits…

    Someone lowers the similarity threshold from 0.90 to 0.80 to save more. The hit ratio rises to about 60%, the LLM drops to about half busy, and the dashboards look great.

    But the simulation counts every hit as a correct answer, and the real system can’t tell either. Some of those extra hits matched a question that was close in wording but different in meaning. Nothing in latency or error rate shows that.

    Scene: With the threshold lowered to 0.80, about 60% of questions hit the cache and the LLM is about half busy. Latency and error rate look better, but some hits are answers to different questions.

    Key idea: A lower threshold always raises the hit ratio; whether the extra hits are right is invisible in system metrics.

  6. 6. …and some of them are wrong

    A user asks *“How do I cancel my order?”*. The nearest cached question is *“How do I cancel my subscription?”* at similarity 0.84: above 0.80, so the user instantly gets confident instructions for the wrong thing (the red packets). Embeddings are good at topic and weak at details: negation, numbers, product names, “my order” versus “your order”.

    Worse is personal data: an answer that mentions one customer’s order must never be served to another. So: back to 0.90, chosen by testing against labelled question pairs; cache only answers that don’t depend on the user; partition the cache per tenant and per language; and put exact parameters (product, plan, locale) into the key next to the embedding.

    Scene: A scripted request shows a false hit: a question about cancelling an order matches a cached answer about cancelling a subscription and the wrong answer is returned. The threshold goes back to 0.90 and the hit ratio to about 40%.

    Key idea: Pick the threshold from labelled data, keep personal answers out, and scope the cache so a near match can’t cross users or contexts.

  7. 7. Invalidation by flushing everything

    The refund policy changes from 30 to 14 days, so cached answers about refunds are now wrong. The quick fix: flush the whole cache (one second in).

    The hit ratio falls to zero and refills only as new answers are generated (drawn here as a stepwise refill). For several seconds all 20 questions per second hit a model sized for 16: its queue fills, requests are rejected, and P95 jumps. The stale-answer problem became an availability problem.

    Scene: The whole cache is flushed. Every question goes to the LLM, which saturates: its queue fills and requests are rejected until the cache refills over the next seconds.

    Key idea: If the cache carries load, a full flush is a self-inflicted traffic spike on the model.

  8. 8. Invalidate what changed, expire the rest

    Each cache entry now stores metadata: which source documents its answer came from, the model and prompt version, and when it was created. When the refund policy changes, only entries derived from that document are deleted: about a tenth of the cache. The hit ratio dips from 40% to 36% for a few seconds and the LLM barely notices.

    Add a TTL as a safety net for changes nobody tagged, and a version in the cache namespace so that a new model or system prompt starts with a fresh cache, warmed gradually, instead of serving answers the new setup would not give.

    Scene: Only cache entries derived from the changed refund policy are deleted. The hit ratio dips slightly, the LLM stays below capacity and nothing fails.

    Key idea: Tag entries with their sources and versions so invalidation is surgical; use TTLs for what you can’t track.

  9. 9. When a semantic cache pays off

    It pays off when many users ask the same questions in different words and the right answer does not depend on who asks: FAQs, documentation, product questions. It does not pay off for personalised answers, agents that call tools with side effects, creative tasks, or traffic with little repetition, where you pay the lookup on every request and rarely hit.

    Don’t confuse it with prompt caching offered by model providers: that reuses the processing of an identical prompt prefix to make a call cheaper and faster, but the call still happens and the answer is always freshly generated.

    Scene: The final setup: the Support API embeds each question, checks the semantic cache and calls the LLM only on a miss, at 20 questions per second with about 40% hits.

    Key idea: Semantic caching is a correctness trade-off disguised as a performance feature: measure false hits, not just hit ratio.