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.