Semantic caching for LLM apps: why a similarity threshold is not enough, tested on 90 questions
A semantic cache reuses an LLM answer when a new question means the same thing. Tested on paraphrases and look-alike traps, no cosine threshold was safe. What worked instead.
A semantic cache stores LLM answers keyed by the meaning of the question instead of its exact text. When a new question arrives, you embed it, find the closest cached question, and if the two are similar enough you return the stored answer without calling the model. Exact-match caching misses "How do I cancel my order?" against "What's the way to cancel an order I placed?". A semantic cache catches it.
The danger is the opposite case. "How much is shipping for orders under Rs 500?" and "How much is shipping for orders over Rs 500?" look almost identical to an embedding model and need different answers. A cache that returns the first answer for the second question is a bug that ships wrong information with full confidence.
I measured how big that problem is with 30 hand-written support questions, each with one paraphrase that should reuse the answer and one look-alike that must not. The result: no similarity threshold separated them. The rest of this post shows the numbers and the two guards that fixed most of it.
How a semantic cache works#
question --> embed --> nearest cached question (cosine similarity)
|
similarity >= threshold ?
yes --> return cached answer (fast, free)
no --> call the LLM, store question + answer
Production versions add a scope (tenant, user, language, prompt version), a time-to-live, and a vector index instead of a list. The decision in the middle is where the risk sits.
The test set#
Thirty base questions for an Indian online store's support bot. For each one I wrote:
- a paraphrase with the same meaning ("Do you offer cash on delivery?" / "Can I pay cash when the parcel arrives?"), which should hit the cache;
- a trap that shares most of the words but needs a different answer ("Do you offer EMI on credit cards?"), which must miss.
The traps cover the ways real queries differ: a number (order 48213 vs 48231, iPhone 16 vs 15, 30 days vs 7 days), a comparison word (under vs over Rs 500), a place (Bangalore vs Dubai), and a different action on the same object (use a gift card vs buy one, Prime cost vs what Prime includes).
Embeddings come from nomic-embed-text through Ollama with the search_query: prefix the model expects, normalised so the dot product is the cosine similarity.
import httpx, numpy as np
from pairs import PAIRS # (cached, paraphrase, trap) x 30
def embed(texts, prefix="search_query: "):
r = httpx.post("http://127.0.0.1:11435/api/embed",
json={"model": "nomic-embed-text", "input": [prefix + t for t in texts]}).json()
v = np.array(r["embeddings"], dtype=np.float32)
return v / np.linalg.norm(v, axis=1, keepdims=True)
base, para, trap = (embed([p[i] for p in PAIRS]) for i in range(3))
pos = (base * para).sum(1) # cached vs paraphrase: should be high
neg = (base * trap).sum(1) # cached vs trap: must stay below the threshold
Result: the two distributions overlap#
paraphrase sims min 0.591 median 0.810 max 0.933
trap sims min 0.557 median 0.772 max 0.993
traps scoring ABOVE their own paraphrase: 10 of 30
The single most similar pair in the whole set is a trap. The eight worst:
| Cached question | Trap | Trap similarity | Paraphrase similarity |
|---|---|---|---|
| How much is shipping for orders under Rs 500? | ...over Rs 500? | 0.993 | 0.863 |
| Where is my order 48213? | Where is my order 48231? | 0.925 | 0.812 |
| How do I use my gift card? | How do I buy a gift card? | 0.889 | 0.804 |
| How do I apply a coupon code? | How do I get a coupon code? | 0.887 | 0.712 |
| How do I report a fake product? | How do I report a fake review? | 0.883 | 0.762 |
| What does Prime membership cost? | What does Prime membership include? | 0.881 | 0.882 |
| Can I return a product after 30 days? | ...after 7 days? | 0.875 | 0.909 |
| Is the iPhone 16 in stock? | Is the iPhone 15 in stock? | 0.869 | 0.882 |
And the paraphrases that scored lowest are perfectly ordinary rewordings: "Can I order without creating an account?" against "Is guest checkout possible?" scored 0.591.
Sweeping the threshold shows the trade:
| Threshold | Paraphrases that hit (good) | Traps that hit (wrong answer served) |
|---|---|---|
| 0.75 | 22/30 | 17/30 |
| 0.80 | 19/30 | 14/30 |
| 0.85 | 11/30 | 10/30 |
| 0.88 | 6/30 | 6/30 |
| 0.90 | 3/30 | 2/30 |
| 0.92 | 1/30 | 2/30 |
| 0.95 | 0/30 | 1/30 |
At no threshold is the false-hit count zero while the cache still does useful work. At 0.95 the cache catches no paraphrases at all and still serves the under/over answer for the wrong question. A common default in tutorials is somewhere between 0.8 and 0.9; on this set, 0.85 serves a wrong answer for one trap in three.
This set is adversarial by design. Real traffic has fewer traps per question. But the traps here are not exotic: order numbers, product versions, price limits and "buy vs use" are what support traffic is made of.
For contrast, the closest unrelated cached question to any paraphrase scored 0.709 at most. Embeddings are good at telling different topics apart. They are bad at telling apart two questions on the same topic that differ in one detail, and that is exactly the decision a cache has to make.
Guard 1: compare the slots#
Most of the dangerous traps differ in a number or a comparison word. A cheap check is to extract those and require them to match exactly:
import re
SLOT_WORDS = {"under", "over", "below", "above", "before", "after", "not", "without",
"less", "more", "minimum", "maximum"}
def slots(q):
q = q.lower()
return set(re.findall(r"\d+", q)), {w for w in re.findall(r"[a-z]+", q) if w in SLOT_WORDS}
def slot_guard(a, b):
return slots(a) == slots(b)
It costs microseconds and catches under/over, 48213/48231, iPhone 16/15 and 30/7 days. It also rejects some good paraphrases: "orders under Rs 500" against "below 500 rupees" fails because under is not below. You can map synonyms to one word, but this guard is blunt by nature. It does nothing for gift card use vs buy.
Guard 2: ask a small model#
For the cases no regex can catch, ask a small LLM a yes/no question before serving the hit:
VERIFY = ("A support bot has a cached answer to question A. Decide if that exact answer would also be correct "
"and complete for question B. Different products, order numbers, amounts, places, dates, or a different "
"action (buy vs use, cost vs include) mean NO.\nA: {a}\nB: {b}\nReply with one word: YES or NO.")
I ran it with qwen3:4b-instruct on all 60 pairs, three times each with different seeds (180 verdicts), and combined it with a low similarity floor of 0.70 so that clearly different questions never reach the verifier.
Results with the guards#
Rates over the 180 verdicts (90 paraphrase checks, 90 trap checks):
| Policy | Paraphrases served from cache | Traps served from cache (wrong) |
|---|---|---|
| Cosine >= 0.80 | 63% | 47% |
| Cosine >= 0.80 + slot guard | 53% | 30% |
| Cosine >= 0.85 | 37% | 33% |
| Cosine >= 0.90 + slot guard | 7% | 0% |
| Cosine >= 0.70 + LLM verifier | 87% | 13% |
| Cosine >= 0.70 + slot guard + LLM verifier | 77% | 7% |
The only threshold policy that served no traps (0.90 plus the slot guard) reused 7% of paraphrases. The verifier with the slot guard reused 77% and served a wrong answer for 7% of traps, against 30% to 47% for the 0.80 policies. The slot guard on top removes the number cases the 4B model sometimes waved through.
Two traps still got through in some runs: "Do you ship internationally?" vs "Do you ship to the Andaman Islands?" and "Is there a size chart for shoes?" vs "...for shirts?". Both need knowledge the verifier does not have: that the Andamans are in India, and that the store keeps separate charts. A bigger verifier model would likely catch more. The safer fix is to keep answers that depend on such details out of the cache (next section).
What the guards cost in time#
Timings on an idle MacBook, with Ollama 0.40.18 serving both models, medians over 10 questions:
| Step | Time |
|---|---|
Embed one question (nomic-embed-text) |
18 ms |
Verifier verdict (qwen3:4b-instruct, 4 output tokens) |
160 ms |
| Full two-sentence answer from the same 4B model | 1,018 ms |
So a verified hit costs about 180 ms against about a second for a fresh answer from a small local model. With a large hosted model, a fresh answer usually takes several seconds and costs money per token, while the verifier stays a small local call, so the gap widens. The verifier also adds its 160 ms to every miss that clears the floor, which is the price of not serving the wrong answer.
What to cache, and what never to cache#
The guards reduce wrong hits. Choosing what goes into the cache removes whole classes of them:
- Cache general answers, not personal ones. "What is your return policy?" is safe to share across users. "Where is my order 48213?" is not: the answer depends on live data and belongs to one customer. Scope those by user, or do not cache them at all. A cache shared across users that stores personal answers is a data leak waiting for a near-duplicate question.
- Scope the key. Include the tenant, language, system-prompt version and model version in the cache scope. When you change the prompt, old answers should stop matching.
- Set a TTL that matches how fast the facts change. Stock levels: minutes or never. Return policy: a day is fine.
- Do not cache answers that came from tools. If the model called an API to answer, the answer reflects that moment's data.
- Log every hit with its similarity and the matched question. Sample them weekly. Wrong hits are invisible in normal metrics because the user gets a fluent, confident answer.
The full cache in about 60 lines#
import re, time
from dataclasses import dataclass, field
import httpx
import numpy as np
OLLAMA = "http://127.0.0.1:11435"
SLOT_WORDS = {"under", "over", "below", "above", "before", "after", "not", "without",
"less", "more", "minimum", "maximum"}
def embed(text):
r = httpx.post(f"{OLLAMA}/api/embed", json={"model": "nomic-embed-text", "input": ["search_query: " + text]}, timeout=60)
v = np.array(r.json()["embeddings"][0], dtype=np.float32)
return v / np.linalg.norm(v)
def slots(q):
q = q.lower()
return set(re.findall(r"\d+", q)), {w for w in re.findall(r"[a-z]+", q) if w in SLOT_WORDS}
def llm(prompt, max_tokens, model="qwen3:4b-instruct"):
r = httpx.post(f"{OLLAMA}/api/chat", timeout=300, json={"model": model, "stream": False,
"messages": [{"role": "user", "content": prompt}],
"options": {"temperature": 0, "num_predict": max_tokens}})
return r.json()["message"]["content"].strip()
VERIFY = "..." # the prompt shown above
@dataclass
class Entry:
question: str
answer: str
vec: np.ndarray
scope: str
expires: float
@dataclass
class SemanticCache:
floor: float = 0.70 # below this, never even ask the verifier
ttl_s: float = 24 * 3600
verify: bool = True
entries: list = field(default_factory=list)
def get(self, question, scope):
now, q = time.time(), embed(question)
live = [e for e in self.entries if e.scope == scope and e.expires > now]
if not live:
return None, "miss: empty scope"
sims = np.array([e.vec @ q for e in live])
best = live[int(sims.argmax())]
if sims.max() < self.floor:
return None, f"miss: best {sims.max():.3f} < floor"
if slots(best.question) != slots(question):
return None, f"miss: slots differ ({best.question!r})"
if self.verify and not llm(VERIFY.format(a=best.question, b=question), 4).upper().startswith("YES"):
return None, f"miss: verifier said no ({best.question!r}, {sims.max():.3f})"
return best.answer, f"hit {sims.max():.3f} <- {best.question!r}"
def put(self, question, answer, scope):
self.entries.append(Entry(question, answer, embed(question), scope, time.time() + self.ttl_s))
def answer(cache, question, scope="faq"):
hit, why = cache.get(question, scope)
if hit is None:
hit = llm(f"You are a support bot for an Indian online store. Answer in 2 sentences: {question}", 120)
cache.put(question, hit, scope)
return hit, why
Running it on eight questions in order, starting from an empty cache:
2438 ms 'How do I cancel my order?' miss: empty scope
202 ms "What's the way to cancel an order I placed?" hit 0.933 <- 'How do I cancel my order?'
1362 ms 'How do I cancel my subscription?' miss: verifier said no ('How do I cancel my order?', 0.843)
703 ms 'How much is shipping for orders under Rs 500?' miss: best 0.526 < floor
520 ms 'How much is shipping for orders over Rs 500?' miss: slots differ ('How much is shipping for orders under Rs 500?')
931 ms 'How do I use my gift card?' miss: best 0.601 < floor
1008 ms 'Where can I redeem a gift card?' miss: verifier said no ('How do I use my gift card?', 0.804)
1226 ms 'How do I buy a gift card?' miss: verifier said no ('How do I use my gift card?', 0.889)
The first line includes loading the model. Two wrong hits were blocked (subscription, over Rs 500). One good hit was lost: the verifier at temperature 0 said "redeem" and "use" are different questions, so that paraphrase paid for a fresh answer. That is the trade you choose with these guards: an occasional extra LLM call instead of an occasional wrong answer.
For more than a few thousand entries, swap the list for a vector index (vector databases explained compares the options). A brute-force NumPy search over 100,000 cached 768-dimension vectors took 3.8 ms on my laptop, so a plain matrix is fine well past the size most FAQ caches reach.
When a semantic cache is worth it#
It pays off when many users ask the same general questions, the answers are stable, and an LLM call is slow or expensive compared with an embedding: FAQ bots, internal help desks, documentation assistants. It is a poor fit for chat that depends on conversation history (the same question means different things in different conversations), for personal or live data, and for agents whose answers come from tool calls.
Before you turn one on, build a set like the one here from your own logs: real questions, real paraphrases, and the near-duplicates that need different answers. Then pick the policy from the numbers, not from a tutorial's default threshold. The LLM cost and latency tracker is a good place to measure whether the cache is saving what you hoped.
Reproduce it#
python3 -m venv v && v/bin/pip install httpx numpy
OLLAMA_HOST=127.0.0.1:11435 ollama serve &
ollama pull nomic-embed-text && ollama pull qwen3:4b-instruct
v/bin/python embed_eval.py # similarity tables
v/bin/python guards.py # slot guard + verifier, 3 seeds
v/bin/python semcache.py # the demo above
Versions: Python 3.15.2, NumPy, httpx 0.28.1, Ollama 0.40.18. All 90 questions are in pairs.py, written for this test.
Sources#
- nomic-embed-text model card (task prefixes such as
search_query:) - Ollama embed API