The interview problem
An AI product-support service handles one million questions per day. Many questions are paraphrases of earlier ones. Design a semantic response cache that reduces model calls while preserving answer correctness, customer isolation and freshness. Show how a highly similar question can require a different answer, and calculate whether the cache actually saves work.
Original ML-design practice, not a reported company interview. Queries, prices, timing and error rates are hypothetical. Official Microsoft technical references retrieved September 27, 2026.
1. Separate answer reuse from text similarity
A semantic cache retrieves a prior request by meaning similarity and proposes reusing its response. The acceptance condition is stronger: the old answer must still correctly answer the new request under the current context. Similarity is candidate selection, not proof of interchangeable answers.
“How do I enable backups in version 4?” and “How do I disable backups in version 4?” may have close embeddings but opposite intent. “Does the trial include exports?” differs from “Does the paid plan include exports?” by a small amount of text with a decisive answer change. A follow-up such as “Does it support that?” is uninterpretable without conversation context.
Start with public, read-only product questions tied to a known product/version and source snapshot. Exclude account balances, current incidents, user-specific entitlements, state-changing tools and requests requiring fresh external observations. Expand eligibility only after validating each class. An exact string match is also unsafe if hidden context has changed.
2. Partition exactly, then search approximately
request + authenticated context → cache eligibility classifier
↓
exact context partition → embedding → nearest cached candidates
↓
compatibility checks + source freshness + authorization
↙ accepted ↘ rejected / miss
cached answer + provenance retrieval + generation
↓
validation → cache insertionUse exact partition keys for tenant or approved public scope, product/version, locale, policy revision, prompt/template version, model configuration and any context that must match. For private content, permissions and source dependencies require current validation as well; a cached permission fingerprint is not eternal authorization.
Store canonical request, relevant structured slots, answer, embedding version, source revisions, creation/expiry times and eligibility provenance. A matching candidate is accepted only after deterministic slot checks and a validated compatibility rule. The number of semantic candidates searched is bounded. If any required context is unknown, treat it as a miss rather than guessing.
Microsoft's cited semantic-cache policy supports similarity thresholds and cache partitioning. These mechanisms help implement a cache; they do not establish that two business questions have equivalent answers. Keep application-specific eligibility and reuse validation explicit.
3. Work through a false-hit example
Assume cosine similarity, with larger values meaning closer embeddings. A cache contains an answer saying exports are included in the paid plan. A trial-plan query obtains similarity 0.97, above a proposed threshold of 0.95. A paraphrase about the paid plan scores 0.93, below it. The threshold would accept the wrong answer and reject the reusable one.
Extracting and exactly matching the plan slot blocks the first hit. The second may be accepted with a lower semantic threshold if other checks pass. But slot extraction is itself fallible: uncertain or contradictory slots should force a miss. Test negation, numbers, product versions, account scope and comparative questions rather than choosing a threshold from a few obvious paraphrases.
Scores depend on the embedding model, preprocessing, metric and index configuration. A distance threshold may run in the opposite direction from cosine similarity. Do not copy a vendor example value into a different embedding space and assume equivalent behavior.
On a labeled set of 10,000 cache-eligible requests, suppose a policy accepts 3,000 reused answers and 30 are invalid. Invalid-reuse rate among hits is 30/3,000=1%; its contribution across all eligible requests is 30/10,000=0.3%. Neither number is the entire system error rate, which must also include mistakes on misses and independently wrong original cached answers. Define whether invalidity means changed applicability, factual error or both.
4. Calculate savings after lookup overhead
For an illustrative cost model, generation costs $0.010 per request and embedding plus lookup costs $0.0002 per eligible request. If all one million daily requests are eligible and the validated hit rate is 30%, generation without caching costs $10,000/day. With caching, lookup costs $200 and 700,000 misses cost $7,000, totaling $7,200 before cache infrastructure and validation overhead. Gross savings are $2,800/day.
With hit rate h, per-request cost is 0.0002+(1−h)×0.010. Ignoring other costs, break-even requires h>0.02. If a compatibility verifier costs $0.002 on every eligible request, break-even becomes h>0.22. A sophisticated verifier can consume much of the intended saving; measure actual calls, not only cache hits.
Suppose lookup takes 40 milliseconds, an accepted hit takes another 10 milliseconds to serve, and a miss then needs 1,000 milliseconds for generation. With a 30% hit rate and these fixed illustrative timings, mean latency is 0.3×50+0.7×1,040=743 milliseconds versus 1,000 without caching. Misses are slower, and the mean does not prove a better p99. Measure latency by hit/miss path and under cache outages.
5. Invalidate by dependencies, not just age
A one-hour TTL limits how long an entry survives; it does not guarantee one hour of correctness. If product policy changes one minute after insertion, the answer may be wrong for nearly the remaining hour. Track source revisions and invalidate or reject entries whose dependencies changed. For dynamic sources, validate a current version before reuse or make the request ineligible.
Store all source dependencies conservatively, not only citations selected by the model. If an answer used documents A and B but cites only A, a permission or content change to B may still invalidate it. A source update event should invalidate affected entries, while periodic reconciliation repairs missed events. Fail closed on authorization uncertainty. If cache freshness cannot be established, regenerate only from sources whose current state and access can be validated; otherwise report the limitation rather than generate from the same uncertain evidence.
Namespace the cache by embedding and generation configuration versions. Updating the embedding model requires rebuilding or separately serving its index; vectors from incompatible spaces must not be compared. Policy and prompt changes can invalidate prior answers even when document content is unchanged.
Distinguish deletion from ordinary expiry. When a source is removed or a tenant requests deletion, account for stored answers, prompts, embeddings, replicas and backups under the agreed retention policy. A vector is derived data, not automatically exempt from the source's access and retention constraints.
6. Bound cache amplification and stampedes
Use single-flight coordination for identical normalized requests within the same exact context partition. Do not merge merely similar concurrent requests before compatibility is established. On a miss, a failed generation should not populate a reusable success entry; partial streaming output is not a completed answer.
Validate entries before insertion and retain their origin. Guard against a fill-versus-invalidate race: a generation started on source revision 7 must not repopulate the cache after revision 8 invalidates it. Compare dependency revisions at publication, retain versioned invalidation markers, and reject stale fills. Revalidate at serve time under the agreed freshness boundary as well. Otherwise one bad answer can be served thousands of times. A hit should reference the original entry and dependencies rather than recursively creating new entries that launder an unverified answer into apparent independent evidence. Track reuse count and provide a targeted invalidation mechanism for discovered bad entries.
At one million entries, 768-dimensional float32 embeddings require 1,000,000×768×4=3.072 GB raw vector storage. If answers average 2 KB decimal, they add 2 GB. These 5.072 GB exclude index overhead, prompts, metadata, replicas and allocator overhead. Set tenant quotas and eviction rules so one noisy customer cannot consume the shared cache.
If the cache is unavailable, bypass it under downstream rate limits. A cache outage turns hits into generation load: at 30% normal hits, generation rises from 70% of traffic to 100%, about a 42.9% increase. Provision headroom, queue or shed work according to the service contract instead of allowing a cache failure to overload the model tier.
7. Evaluate reuse as its own prediction task
Build query pairs labeled for answer interchangeability under explicit context, not just topical similarity. Include hard negatives with changed negation, dates, versions and permissions. Split related template families and source snapshots across development and test data to avoid an overly easy paraphrase benchmark.
Measure valid-hit rate, invalid reuse, total answer quality, latency and realized cost. Examine risk by request class and the volume served from each entry. A single unsafe high-traffic cache entry can matter more than many low-traffic misses. Audit cached answers against authoritative sources, not only against a fresh model response that may repeat the same error.
Run shadow lookup first, logging candidate hits without serving them. Then launch on the validated scope with sampled audits and an immediate bypass switch. Include stale-source events, revoked access, cache poisoning attempts, model upgrades and malformed context in acceptance tests. Increasing hit rate is useful only while reuse remains within the quality contract.
8. Follow-ups and self-review
Follow-ups: Does 0.99 similarity prove equivalent answers? No. Is exact caching always safe? Only with a complete context and freshness contract. Can prompt caching replace response caching? They save different work: reusing computation is not the same as returning an earlier answer. Should permission checks be skipped on hits? No. Can cache failure increase downstream load? Yes, potentially sharply.
Score 0–2 each for eligibility boundaries, exact-context partitioning, false-hit reasoning, dependency/permission invalidation and measured end-to-end economics. A strong answer treats reuse as a fallible decision rather than a free optimization.
Sources and next steps
- Microsoft: enabling semantic caching — lookup/store flow and threshold configuration.
- Microsoft: semantic-cache lookup policy — vector proximity and partitioning.
The counterexamples, cost model and serving design are original. Continue with enterprise permission mapping for authorization across derived content.
Continue your preparation
Choose a connected learning path or browse more ML system design questions. Read our editorial method and attribution policy.