Semantic caching
Reuse a stored answer when a new query's embedding is close enough to an earlier one: it skips a full generation, but every false hit serves a confident wrong answer.
Analogy: A help-desk agent who answers from a binder of past replies whenever a question sounds familiar: great for "reset my password", dangerous for "cancel my order" vs "cancel my subscription".
How it works
- A hit needs cosine similarity above a tuned threshold, typically ~0.90–0.95, and costs tens of ms.
- Layer it: an exact-match cache on the hashed prompt first, a semantic layer only where wording varies.
- False hits come from near-duplicates like "cancel my order" vs "cancel my subscription", or "with" vs "without".
- Scope the cache key by tenant, user, locale, model and prompt version, so private answers never leak.
- Set TTLs per content type and invalidate when the source changes: prices and policies go stale.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your airline bot's semantic cache uses a 0.93 cosine threshold. A reviewer finds "Can I bring my dog in the cabin?" answered with the cached reply to "Can my dog travel as checked baggage?" (similarity 0.94). Best fix?
Go deeper
Full explanation
A semantic cache sits in front of the LLM and stores (query embedding, response) pairs. A new query is embedded, matched to the nearest stored query, and gets the cached response if cosine similarity clears a threshold, typically ~0.90–0.95, tuned on your data. A hit costs one embedding and one vector lookup, tens of milliseconds, instead of a multi-second generation.
Build it in layers:
- Exact-match cache first: hash the normalized prompt plus model and prompt version. Zero false hits, nearly free.
- Semantic layer second, only where traffic repeats with different wording.
The risks are why it's an advanced tool:
- False hits: "cancel my order" vs "cancel my subscription", "with" vs "without", Spain vs Mexico all score as near-duplicates. The user gets a fluent answer to a different question.
- Staleness: prices and policies change. Set TTLs per content type and invalidate when the source changes.
- Leakage: a personalized or permissioned answer served to someone else. Scope the cache key by tenant, user or permission set, locale, model and prompt version.
It works for FAQ-like, non-personalized traffic with heavy repetition; measure the near-duplicate rate in your logs before building it. Unlike Prompt caching, which reuses computation and always generates fresh, this reuses the answer.
Code Two-layer cache scoped by tenant and permissions
import hashlib, time
import numpy as np
from openai import OpenAI
client = OpenAI()
EMBED = "text-embedding-3-small" # any embedding model
MODEL = "gpt-4.1-mini" # any chat model
THRESHOLD = 0.93 # tune on labeled "same answer" / "different answer" query pairs
TTL_S = 24 * 3600 # per content type: prices need far less
exact: dict[str, tuple[str, float]] = {}
semantic: dict[str, list[tuple[np.ndarray, str, float]]] = {} # a vector DB in prod
def embed(text: str) -> np.ndarray:
v = np.array(client.embeddings.create(model=EMBED, input=text).data[0].embedding)
return v / np.linalg.norm(v) # unit vectors: dot product = cosine
def cached_answer(query: str, tenant: str, acl: str, prompt_ver: str) -> str:
scope = f"{tenant}|{acl}|{MODEL}|{prompt_ver}" # never share across permission scopes
norm = " ".join(query.lower().split())
key = hashlib.sha256(f"{scope}|{norm}".encode()).hexdigest()
now = time.time()
if key in exact and now - exact[key][1] < TTL_S: # 1) exact match: zero false hits
return exact[key][0]
q = embed(norm)
live = [(float(q @ v), r) for v, r, ts in semantic.get(scope, []) if now - ts < TTL_S]
if live and (best := max(live, key=lambda x: x[0]))[0] >= THRESHOLD: # 2) in scope only
return best[1]
resp = generate(MODEL, query) # 3) miss: call the LLM, then store both layers
exact[key] = (resp, now)
semantic.setdefault(scope, []).append((q, resp, now))
return respReal example
An airline's help bot gets 50k questions/day; logs show ~30% are rephrasings of ~200 baggage, check-in and pet-policy questions. A semantic cache at 0.93, scoped by locale and fare-rules version, answers those in ~40 ms instead of ~3 s. In week one, a reviewer finds "Can I bring my dog in the cabin?" answered with the cached reply to "Can my dog travel as checked baggage?" (similarity 0.94). The fix: a 0.96 threshold for the pets intent, and no caching at all for queries that mention a booking reference, since those are personal.
Trade-offs +3 · −3
+ You gain
- A hit skips generation entirely: tens of milliseconds and near-zero token cost.
- Absorbs bursts of repeated questions during outages, launches or seasonal peaks.
- Model- and provider-agnostic: it lives in the gateway, not in the model.
− You pay
- False hits return confident wrong answers, and users can't tell.
- Needs scoping, TTLs and invalidation: classic cache bugs plus a fuzzy key.
- Low hit rates on long, contextual or multi-turn prompts, where few queries truly repeat.
Use it when
High-volume, FAQ-like, non-personalized traffic where many users ask the same thing in different words and the answers change slowly.
Avoid it when
Personalized, permissioned or multi-turn answers, fast-changing data, agents with tool side effects, or domains where one wrong answer is costly (medical, legal, financial).
Numbers to know 4
- Typical cosine threshold ~0.90–0.95 on normalized embeddings; tune it on labeled query pairs (rule of thumb).
- A hit = one embedding call + one vector lookup: tens of ms vs seconds for a generation.
- text-embedding-3-small: $0.02 per 1M tokens (OpenAI list price, unchanged as of Nov 2026), so lookups are close to free.
- Savings ≈ hit rate × LLM cost: a 20% hit rate saves ~20%, minus embedding and store costs.
Common pitfalls 4
- One global cache across tenants or roles: the fastest way to leak another user's data.
- Copying a threshold from a blog: the right value depends on your embedding model and domain.
- Caching time-sensitive or personal questions ("today", "my balance", "my order").
- Never measuring false hits: sample cache hits and have a human or an LLM judge check them.
Interview questions 2
Answer out loud first, then reveal.
Would you add a semantic cache to our support assistant?Show answer
Maybe, after measuring. I'd first add an exact-match cache, which has no false hits, then check the logs for the near-duplicate rate: if only a few percent of queries repeat, a semantic cache is complexity for little gain. If the rate is high and answers aren't personalized, I'd add it scoped by tenant, locale, model and prompt version, with TTLs per content type and a threshold tuned on labeled pairs. I'd run it in shadow mode first, logging would-be hits and grading them, so I know the false-hit rate before any user sees one.
What are the risks of semantic caching, and how do you contain them?Show answer
Three. False hits: similar wording, different intent, so the user gets a fluent wrong answer. I keep the threshold high, tune it per intent and can add a cheap reranker check on borderline scores. Staleness: TTLs plus invalidation when the source document changes. Leakage: the cache key includes tenant and permission scope, and anything personalized, like a query with an account number or one whose answer used the user's data, is never cached. I monitor the hit rate and audit a sample of hits every week.