Semantic caching
Step 7 of 14. Colleagues ask the same things in different words, and a cache can answer many of them for free. It can also hand one person's answer to another, so every reuse needs rules.
Semantic caching in 60 seconds
- What: a semantic cache reuses an earlier answer when a new question means the same thing, even if the words differ.
- Risk: similar wording does not mean the same answer. Personal data, changed sources and different contexts all break reuse.
- Key: a hit needs similarity plus a matching scope, role, store, prompt version, model version and source versions.
- Tune: pick the similarity threshold from labelled pairs of questions, not from a guess.
- Measure: hit rate alone flatters you. Track stale-answer incidents and the share of cached answers that fail evaluation.
The problem it solves
Retrieval and generation take time and cost money. A traditional cache keyed on the exact text of a request catches only identical strings, and people rarely type the same string twice. Consider two colleagues on the same morning. One asks "How do I reset my scanner's connection?" The other asks "Scanner stuck, how do I reconnect it?" The words differ and the right answer is identical.
A semantic cache tries to recognise that. It stores earlier questions as embeddings, finds the nearest stored question for a new one, and reuses the old answer when the match is close enough and safe. Done well it shortens the wait and trims the bill. Done carelessly it becomes a quiet source of wrong and private answers, which is worse than having no cache.
How a semantic cache works
- A new question arrives.
- It is converted into an embedding.
- The cache index is searched for the closest earlier questions.
- The best candidate is checked against the similarity threshold, and against validity rules such as age and source versions.
- The candidate is checked again for fitness in the current context: is this answer allowed for this colleague, and does it depend on anything that differs?
- If every check passes, the stored answer is returned and the model is never called.
- If any check fails, the request continues through retrieval and generation, and the new answer may then be stored.
Step five is the one teams skip. Closeness of meaning answers only the question "are these two questions alike?" It says nothing about whether the answer can be shared.
When caching goes wrong
Take the question "How many holiday hours do I have left?" Another colleague asked almost the same thing an hour ago. The questions are nearly identical in meaning, and the answers belong to two different people. Serving the stored one is a data breach, not an optimisation. The same applies to "What is my shift on Saturday?"
Or take the scanner sync procedure that changed on Monday. A cached answer from last week still matches the question perfectly and now describes steps that no longer work. The cache did exactly what it was built to do, and the result is wrong.
What decides whether a stored answer can be reused
- Audience: is the answer public to every colleague, limited to a group such as store managers, or about one individual? Only the first can be shared widely.
- Freshness: has any document behind the answer changed since it was stored?
- Context: does the answer depend on the store, the device model, the region, the role or the earlier turns of the conversation?
- Version of prompt and model: was it written under a prompt and model that you still accept? An answer from a retired prompt may not meet today's standards.
- Time to live: how long may an entry live even if nothing is known to have changed?
- Risk: what would a wrong or mismatched answer cost? A stale tea-break rota is a nuisance. A stale cash-handling step is an incident.
Answers built from widely published procedures can safely live longer, for example a day or two, provided source versions still match. Anything that reads live stock, incident status or a person's own records should skip the shared semantic cache altogether. Those answers are either too volatile or too private to share.
Cache the right thing
A single cache does not suit every stage of the pipeline. Different layers hold different things, with different risks. Several of these have their own pages: exact response cache, prefix cache, embedding cache and retrieval cache. The table gives a starting policy for Store Assist.
| What | Cache it? | Lifetime and key | Reason |
|---|---|---|---|
| Answers to public procedure questions | Yes, in the semantic cache | Up to 24 hours, keyed on question meaning, scope, prompt, model and source versions | Repeated often, identical for everyone who may read the sources. |
| Answers limited to a role, such as store managers | Yes, in a separate cache per role | Up to 8 hours, role in the key | Safe only among people with the same rights. |
| Embeddings of repeated query text | Yes | Several days, keyed on the model version and normalised text | Cheap, deterministic and holds no answer. |
| Search results for a query and filter | Yes, briefly | Minutes, with filter and index version in the key | Saves a search without storing an answer. |
| Stable prompt prefix such as instructions and tool definitions | Yes, at the provider or serving layer | Until the prompt version changes | Cuts input cost and time without reuse risk. |
| Live stock and incident status | No, or a few seconds at most | Short and per user | Changes constantly and must be authoritative. |
| Personal answers such as holiday hours or shifts | No shared cache | Per user and very short, if at all | Sharing them exposes one colleague's data to another. |
| Anything from a sensitive workflow, such as a PIN reset | Never | Not stored | Each run must be verified afresh. |
Designing the cache key
A good cache entry is not just a question and an answer. The key is a bundle, and a lookup only counts as a hit when every part matches. Think of the embedding as the fuzzy part and everything else as exact.
- Normalised query embedding: lower-cased, trimmed text with obvious noise removed, such as greetings, before it is embedded.
- Scope: public, role-limited or personal. Personal entries are never stored in the shared cache.
- Store and region: answers that differ by store layout or local rules must not cross those lines.
- Role: the access class under which the answer was produced.
- Prompt version and model version: so that a release can retire old answers cleanly.
- Source versions: the document identifiers and versions used as evidence, so that a change to any of them invalidates the entry.
Keep separate cache partitions per scope, not one pool with a scope field. A bug in a filter then cannot cross a boundary, because the data is not in the same place. This is the same reasoning as keeping tenants in separate stores.
Tuning the threshold
The similarity threshold is the dial between savings and risk. Set it too low and different questions share an answer. Set it too high and the cache never hits. Do not pick it by feel. Build a set of labelled question pairs, perhaps 2,000 drawn from real logs, each marked "same intent, same answer" or "different". Include the nasty near misses: "reset scanner" against "reset till", or "Saturday shift" against "Sunday shift".
Plot the false-hit rate against the true-hit rate as the threshold moves, then choose the point where wrong reuse is under your limit, for example 0.5 percent. Retune after changing the embedding model, because similarity scores shift between models. For risky topics, set a stricter threshold than for general ones, or exclude them.
Invalidation and poisoning
Each entry stores the identifiers and versions of the sources it used. When the indexing pipeline from Step 6: Knowledge and retrieval processes a change or a deletion, it also publishes the document identifier to the cache. The cache keeps a reverse lookup from document to entries and removes every dependent entry at once. Without this, a withdrawn product-recall notice could keep being quoted from cache long after it left the index.
Poisoning is the other risk. A cache amplifies whatever goes into it, so one bad answer is served to many people. Reduce the chance in several ways.
- Write only answers that passed groundedness and policy checks, never raw model output.
- Do not store answers whose evidence included untrusted text, such as an uploaded supplier manual, until it has been reviewed.
- Never let a user's own phrasing become the stored question for a shared entry without normalisation and review of the answer.
- Limit who and what can write to the cache, and log every write with its sources.
- Provide an emergency purge by scope, topic or time window.
Store Assist, worked through
Store Assist handles 36,000 requests a day. About 60 percent, or 21,600, are public procedure questions that could use the shared cache. Suppose a well-tuned cache hits on 30 percent of those. That is 6,480 requests a day answered without a model call, or 194,400 a month.
- Model cost per request: 1,000 input tokens at £0.40 per million is £0.0004. 250 output tokens at £1.60 per million is £0.0004. The total is £0.0008.
- Monthly saving: 194,400 x £0.0008 is about £155, out of the £864 baseline. After the embedding calls and the cache index it is smaller. The money is modest.
- Time saved: a hit returns in about 80 ms instead of a full generation, so the 95th percentile for these requests drops sharply.
- The real prize: the 08:00 point-of-sale outage. Thousands of colleagues ask the same question within minutes. If 70 percent of those hit the cache, a burst of 10 requests a second needs the model for only 3, protecting provider limits and keeping time to first token under 1.5 seconds.
- What stays out: "How many holiday hours do I have left?" and "What is my shift on Saturday?" bypass the shared cache. Stock for SKU 448812 and the status of INC-5521 do too.
The honest finding is that at this scale the cache is mostly a latency and resilience feature, not a budget feature. Say so when you propose it.
THRESHOLD = 0.92 # tuned from labelled pairs, retune when the embedding model changes
MAX_AGE_S = 24 * 3600 # hard ceiling on entry age
TOP_K = 3 # candidates examined per lookup
NEVER_CACHE = {"personal", "live", "sensitive_action"}
def lookup(question, ctx, cache, embedder, now):
if ctx.scope in NEVER_CACHE:
return None # bypass: never shared
vec = embedder.embed(normalise(question))
# Separate partition per scope, so a filter bug cannot cross a boundary.
partition = cache.partition(ctx.scope, ctx.role, ctx.store_region)
for entry, score in partition.nearest(vec, k=TOP_K):
if score < THRESHOLD:
break # results are sorted, nothing better follows
if now - entry.created_at > MAX_AGE_S:
continue
if entry.prompt_version != ctx.prompt_version or entry.model_version != ctx.model_version:
continue
# Source versions must still be current in the index.
if any(index.current_version(d) != v for d, v in entry.sources.items()):
continue
return entry.answer # all gates passed
return None
def store(question, answer, ctx, cache, embedder, now):
# Write only checked answers that did not rely on untrusted text.
if ctx.scope in NEVER_CACHE or not answer.passed_checks or answer.used_untrusted_source:
return
cache.partition(ctx.scope, ctx.role, ctx.store_region).put(
vector=embedder.embed(normalise(question)), answer=answer.text,
sources=answer.source_versions, prompt_version=ctx.prompt_version,
model_version=ctx.model_version, created_at=now)
normalise, index and the ctx and answer objects are placeholders. Copy the early bypass, per-scope partition, layered checks and guarded write.
Design decisions
- Partitioning: one cache partition per scope, role and region group, with personal and live data excluded by design rather than by a filter.
- Invalidation path: subscribe the cache to the same change and deletion events as the index, with a reverse map from document to entries.
- Version bumps: treat a prompt or model release as an invalidation event, or at least include versions in the key so that old entries stop matching.
- Fail-open behaviour: if the cache is down, slow or unsure, go to the model. A cache must never be able to make the system unavailable.
- Stampede control: when many identical questions arrive together, let one request fill the entry and make the rest wait briefly for it, instead of calling the model thousands of times.
- Lifetimes by risk: set time to live per content class, shorter for anything touching money or safety.
- Purge tooling: build and test an operator action to clear by topic, document or time range.
Measuring it
- Hit rate: hits as a share of eligible requests, split by scope. Quote it against eligible traffic, not total traffic.
- Latency saved: the difference in response time between hits and misses, at the median and 95th percentile.
- Cost saved: avoided model and retrieval spend, net of embedding and cache infrastructure cost.
- False-hit rate: the share of hits where a reviewer or judge says the answer was wrong for the question. Sample hits every day.
- Stale-answer incidents: cached answers that contradicted a current source. The target is zero, and every one is reviewed.
- Evaluation failure rate: run the golden set against cached answers as well as fresh ones, and compare groundedness.
- Invalidation lag: time from a source change to the removal of dependent entries.
When to use it, and how much of it
| Situation | Approach | Why |
|---|---|---|
| High volume of repeated public procedure questions | Semantic cache with a tuned threshold | Strong repeat rate and low risk of sharing. |
| Spiky demand when many people ask the same thing | Semantic cache plus request coalescing | Protects provider limits and response times during an outage. |
| Low volume, mostly unique questions | Exact and embedding caches only | Few hits, so the risk is not worth the effort. |
| Answers that depend on a person, live data or approvals | No shared cache | Sharing is unsafe or answers go stale within seconds. |
| Content that changes several times a day | Short lifetimes with source version checks, or skip | Entries would be invalidated before they paid back. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | A wrong hit is a confident wrong answer, served quickly. A higher threshold lowers that risk and the hit rate together. | Tune on labelled pairs, sample hits for review, and exclude risky topics. |
| Latency | Hits answer in tens of milliseconds. Misses pay a small extra for the lookup. | Set a tight time budget for the lookup and fall through on timeout. |
| Cost | Savings scale with volume and repeat rate. At 36,000 requests a day they are modest. | Present the cache as a latency and resilience investment first. |
| Risk | Shared storage can leak personal data or serve stale rules. | Partition by scope, version the keys and wire in invalidation. |
What this means for your role
Common mistakes
Step checklist
- A written policy lists what is cached, for how long, and what is never cached.
- Personal, live and sensitive requests bypass the shared cache, proved by a test.
- Entries are partitioned by scope, role and region group.
- Each entry stores source versions, prompt version, model version and creation time.
- The threshold was chosen from labelled pairs and has a recorded false-hit rate under the agreed limit.
- Document changes and deletions invalidate dependent entries, with the lag measured.
- Only answers that passed checks and did not use untrusted sources are written.
- Stampede control exists for bursts of identical questions.
- Daily sampling of hits reports false-hit rate and stale-answer incidents.
- An operator purge has been rehearsed, and the cache fails open.
Further reading
- Semantic cache: the pattern in more depth.
- Exact response cache: the safest layer to start with.
- Prefix cache: reusing the stable start of a prompt.
- Embedding cache: saving repeated embedding calls.
- Retrieval cache: reusing search results.
- Caching types: how the layers compare.
A semantic cache earns its place when it is boring: scoped, versioned, invalidated by events and watched for wrong hits. Whatever the cache cannot answer goes on to a model, and the next question is which one. Next: Step 8: Model selection and routing.