Semantic cache: reusing answers for questions that mean the same thing
A semantic cache matches a new question to earlier ones by meaning, and returns the stored answer when the match is close enough. Use it for repetitive, low-risk questions where wording varies a lot.
Semantic cache in 60 seconds
- What: a store of earlier questions and answers, searched by meaning using embeddings, with a similarity threshold.
- Saves: the model call for questions that are worded differently but ask the same thing.
- Key knob: the threshold. Too low and you return wrong answers. Too high and you rarely hit.
- Main risk: a near match is not always the same question, such as 'cancel my order' and 'cancel my subscription'.
- Safe when: answers are generic, public and low-stakes, and you can measure wrong hits.
Where this type fits
The semantic cache is an application-controlled cache, a looser cousin of the exact-match response cache. It sits with the embedding cache and the retrieval-result cache in the caching hub. It is the only cache in that group that can return an answer written for a different request, which is why it needs the most care.
The problem it solves
People rarely ask the same question twice in the same words. 'Where is my order?', 'order status please' and 'has my parcel shipped yet' all want the same answer. An exact-match cache sees three different strings and misses every time. In a customer-facing assistant, the hit rate can be close to zero even though the questions are highly repetitive.
The cost of those misses is real. Each one is a full model call with its tokens and delay. At scale, a large share of the bill may go to answering the same dozen questions in different phrasings.
A semantic cache closes that gap. It embeds each question as a vector and compares it with stored vectors. If the nearest stored question is similar enough, it returns the stored answer. The model is called only for questions the cache has not seen in any form.
How it works
- Normalise and scope: clean the question and attach scope fields such as tenant, language and content version. Only compare within the same scope.
- Embed: turn the question into a vector with an embedding model.
- Search: find the nearest stored question vector within the same scope.
- Check the threshold: compare the similarity score with a set value. If it is below, treat it as a miss.
- Hit: return the stored answer. Optionally run a cheap check that the answer still fits.
- Miss: call the model, then store the question vector, the answer and the versions used, with a TTL.
Similarity scores measure closeness in meaning space, and meaning is not the same as intent. Two questions can sit very close and still need different answers. 'How do I cancel my order?' and 'How do I cancel my subscription?' share most words and context, but the right answers are different. Embedding models are often weakest on negation, numbers, names and small but important differences.
For this reason, the threshold is not a number you pick once. It is tuned on labelled pairs from your own traffic, and it may differ by topic. Many teams add a second check for risky topics, or exclude them from the cache altogether.
A worked example
Acme's help assistant has a semantic cache with a threshold of 0.90 on cosine similarity. The scope is tenant 'acme', language 'en', and help-centre version 5.
- Question 1: 'What is your refund policy?' No similar entry exists. The model answers with the 30-day policy. The cache stores the vector, the answer and the version.
- Question 2: 'How do I get my money back?' The nearest stored question scores 0.93. That passes 0.90, so the stored answer is returned in a few milliseconds.
- Question 3: 'Can I get a refund after 45 days?' The nearest stored question scores 0.91. It passes, but the stored answer does not mention the 45-day case. This is a wrong hit, which is why Acme later raises the threshold for policy questions to 0.95.
- Question 4: 'What is your return address?' The nearest score is 0.72. It is a miss, so the model is called and a new entry is stored.
- Content update: Acme publishes help-centre version 6. The version in the scope changes, so old entries no longer match and new answers are generated.
Building it
import time
# Placeholders: embed() returns a unit-length vector; vector_index supports
# search(vector, filter, top_k) and add(id, vector, payload); llm.generate() is the model call.
THRESHOLD = 0.92 # tune on labelled pairs from your own traffic
TTL_SECONDS = 6 * 3600 # bound how long a stored answer can live
BLOCKED_TOPICS = {'medical', 'legal', 'payments'} # never serve these from cache
def cosine(a, b):
return sum(x * y for x, y in zip(a, b)) # vectors are unit length
def answer(question, scope, topic, embed, vector_index, llm, metrics):
if topic in BLOCKED_TOPICS:
return llm.generate(question) # risky topics always get a fresh answer
vec = embed(question)
# Filter by scope so one tenant or content version never sees another's entries.
hits = vector_index.search(vec, filter=scope, top_k=1)
if hits:
best = hits[0]
fresh = time.time() - best.payload['stored_at'] < TTL_SECONDS
score = cosine(vec, best.vector)
if fresh and score >= THRESHOLD:
metrics.count('semantic_hit')
# Log the pair so reviewers can audit wrong hits later.
metrics.log_pair(question, best.payload['question'], score)
return best.payload['answer']
metrics.count('semantic_miss')
result = llm.generate(question)
if result.get('finish_reason') == 'stop' and not result.get('flagged'):
vector_index.add(
id=f'{scope}:{hash(question)}',
vector=vec,
payload={'question': question, 'answer': result['text'],
'stored_at': time.time(), **scope},
)
return result['text']
The code does four things worth copying. It filters by scope before comparing. It applies a threshold and a TTL. It skips risky topics. And it logs every hit with its pair of questions, so a person can review wrong hits and move the threshold with evidence.
Design decisions
- Threshold: start high, around 0.95, and lower it only while labelled tests show an acceptable wrong-hit rate. Use different values per topic if needed.
- Scope fields: include tenant, language, content version and user role as hard filters. Similar questions from different audiences must not share answers.
- Embedding model: pick one that separates your domain's close intents well, and record its version. Changing it means rebuilding the cache.
- Eligible topics: allow only generic, public, stable answers. Exclude anything personal, financial, medical, legal or time-sensitive.
- TTL and invalidation: keep TTLs short and put the content version in the scope, so updates invalidate old entries automatically.
- Verification step: for borderline scores, optionally ask a small model whether the stored answer fits the new question. This adds cost and delay, so use it only in a score band.
- Failure handling: if the vector index is down or slow, skip the cache and call the model. Never block the user on the cache.
Measuring it
- Hit rate: semantic hits divided by lookups, split by topic.
- Wrong-hit rate: from a human-reviewed sample of hits, the share where the stored answer did not fit the new question. This is the key quality metric.
- Threshold curve: on labelled pairs of same-intent and different-intent questions, plot precision and recall against the threshold, and pick the point that meets your wrong-hit limit.
- Saved cost: hits multiplied by the average miss cost, minus the cost of embedding every question and running the index.
- Latency: embedding plus search time. On a miss this is added delay, so it must stay small compared with a model call.
- Staleness: sample hits, regenerate the answers and compare, as with an exact-match cache.
def pick_threshold(pairs, max_wrong_rate=0.01):
"""pairs: list of (score, same_intent) from labelled data.
Returns the lowest threshold whose wrong-hit rate stays under the limit."""
best = 1.0
for t in [x / 100 for x in range(99, 60, -1)]: # try 0.99 down to 0.61
passed = [same for score, same in pairs if score >= t]
if not passed:
continue
wrong = passed.count(False) / len(passed)
if wrong <= max_wrong_rate:
best = t # lower threshold means more hits, if still safe
else:
break
return best
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| Public FAQ with many rephrasings of the same questions | Yes | Hits are frequent and wrong answers are low-risk. |
| Internal help bot with stable how-to answers | Yes | Similar questions share an answer, and content versions control staleness. |
| Questions about one user's account or order | No | The answer depends on the user, not only on the wording. |
| Medical, legal or payment advice | No | A near match can give a harmful answer. |
| Facts that change often, such as prices or stock | Only with very short TTL and versioned scope | Stored answers go stale quickly. |
| Requests that need exact wording or numbers | No | Embeddings blur small but vital differences. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Some hits return an answer meant for a similar, not identical, question | Set a high threshold, exclude risky topics and review sampled hits. |
| Latency | Fast on a hit, slightly slower on a miss because of embedding and search | Cache embeddings and keep the index small and close. |
| Cost | Saves model calls, but adds embedding and index costs | Compare saved cost with total cache cost per route. |
| Complexity | Needs embeddings, an index, a threshold and review tooling | Start with one low-risk route and expand. |
| Failure modes | Wrong hits, cross-audience leaks and stale answers | Use scope filters, TTLs, content versions and audit logs. |
Compared with related types
The exact-match response cache is safer and simpler, but it hits only on identical requests. Use it first. Add a semantic cache only where measurements show many rephrased repeats.
The embedding cache is a helper. A semantic cache embeds every question, and an embedding cache avoids re-embedding text it has seen. Retrieval for question answering is described in vector search and chunking, which uses the same kind of nearest-neighbour search.
What this means for your role
Common mistakes
Further reading
- Types of caching in AI systems: the hub that compares every cache type.
- Exact-match response cache: the safer cache to try first.
- Vector search and chunking: how embeddings and nearest-neighbour search work.
- Guardrails and safety: checks to run on answers before storing them.
A semantic cache is a bet that similar wording means the same need. Make the bet only on safe topics, set the threshold from evidence, and keep reviewing the hits.