Skip to main content
Back to all articles
AI Engineering 7 min readUpdated August 31, 2026

Semantic Caching Is a Retrieval Problem With Invalidation Attached

Semantic caching can avoid repeated LLM work for equivalent questions, but similarity alone is not a safe cache key. A production design that scopes by tenant and policy, preserves provenance, validates freshness, and measures false cache hits.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#semantic-caching#rag#llm-cost#cache-invalidation#multi-tenancy#vector-search#typescript#python
On this page

The most expensive LLM call is often the one you already answered five minutes ago.

A customer asks:

How long do I have to return an enterprise order?

Another asks:

What is the return window for enterprise purchases?

A string cache sees two different keys. A semantic cache sees the same intent and has a chance to reuse the previous result.

That sounds straightforward until the answer depends on tenant policy, document versions, user permissions, current account state, or a source that changed between the two requests.

At that point semantic caching stops being “Redis plus embeddings.” It becomes a retrieval system with an invalidation problem.

The example here is a multi-tenant support assistant answering policy questions from a RAG knowledge base. I only want to reuse an answer when I can defend the statement that the previous result is still valid for this caller and this version of the world.

Decide what is actually cacheable

I do not start by embedding every user message.

Some requests should not be reused at all:

Text
What is our refund policy?                 possibly cacheableSummarize this public product document.   possibly cacheableWhat is my current account balance?       usually not answer-cacheableRefund order ORD-91.                      never replay a cached side effectWhat changed in the last ten minutes?     freshness-sensitive

A semantic answer cache works best for read-only questions whose correct answer is stable for some useful period.

For stateful questions, I may still cache a lower-level artifact—retrieval results, embeddings, or a deterministic tool response with normal cache semantics—rather than cache the generated final answer.

I make cache eligibility explicit:

type CachePolicy = {  eligible: boolean;  ttlSeconds: number;  requiresSourceValidation: boolean;};​function cachePolicyFor(operation: string): CachePolicy {  switch (operation) {    case "knowledge-question":      return {        eligible: true,        ttlSeconds: 900,        requiresSourceValidation: true,      };    case "account-status":    case "tool-write":      return {        eligible: false,        ttlSeconds: 0,        requiresSourceValidation: false,      };    default:      return {        eligible: false,        ttlSeconds: 0,        requiresSourceValidation: false,      };  }}

The TTL is illustrative. A policy manual and a live inventory system have completely different freshness requirements.

Similarity is only one part of the key

If two prompts have cosine similarity of 0.94, that tells me something about their text. It says nothing about whether they belong to the same tenant or policy version.

I keep an exact scope around the fuzzy match.

type SemanticCacheScope = {  tenantId: string;  knowledgeBaseId: string;  policyVersion: string;  promptVersion: string;  modelFamily: string;  locale: string;};​type SemanticCacheEntry = {  id: string;  scope: SemanticCacheScope;  query: string;  queryEmbedding: number[];  answer: string;  sourceVersions: Array<{    documentId: string;    version: string;  }>;  createdAt: string;  expiresAt: string;};

The vector search happens only *inside* an exact scope.

A cache for tenant A should never retrieve tenant B's answer and then rely on the model not to reveal it. Cross-tenant cache isolation belongs in the storage query, just like RAG retrieval isolation.

Do not put user identity into the scope unless the answer needs it

There is a tradeoff here.

If I key every entry by userId, cache reuse collapses even when ten users in the same organization are asking about the same public policy.

If I ignore identity completely, I may reuse an answer that was built from documents visible only to one role.

The useful scope is the *authorization view* that affected the answer.

For example:

TypeScript
type AccessView = {  tenantId: string;  permissionSetVersion: string;  visibilityClass: "public" | "employee" | "admin";};

If permissions are highly granular per document/user, semantic answer caching may be less attractive. It can be safer to cache retrieval primitives behind normal authorization and regenerate the answer.

Do not widen the trust boundary just to improve a hit rate.

Look up candidates, then validate them

The cache lookup is a two-stage operation:

  1. retrieve semantically similar entries inside the exact scope;
  2. apply freshness and source validation before returning one.
interface SemanticCacheStore {  search(input: {    scope: SemanticCacheScope;    embedding: number[];    limit: number;  }): Promise<Array<{ entry: SemanticCacheEntry; similarity: number }>>;}​interface SourceVersionStore {  currentVersions(    ids: string[],  ): Promise<Map<string, string>>;}​async function findReusableAnswer(input: {  scope: SemanticCacheScope;  embedding: number[];  now: Date;  minSimilarity: number;  cache: SemanticCacheStore;  sources: SourceVersionStore;}): Promise<SemanticCacheEntry | null> {  const candidates = await input.cache.search({    scope: input.scope,    embedding: input.embedding,    limit: 5,  });​  for (const candidate of candidates) {    if (candidate.similarity < input.minSimilarity) continue;    if (Date.parse(candidate.entry.expiresAt) <= input.now.getTime()) continue;​    const ids = candidate.entry.sourceVersions.map((item) => item.documentId);    const current = await input.sources.currentVersions(ids);​    const fresh = candidate.entry.sourceVersions.every(      (source) => current.get(source.documentId) === source.version,    );​    if (fresh) return candidate.entry;  }​  return null;}

This is more work than returning the nearest vector. That work is the difference between a semantic cache and an answer lottery.

Thresholds should come from false-hit evaluation

A similarity threshold such as 0.92 is not universally safe.

These questions can be semantically close and still require different answers:

Text
Can an administrator delete a workspace?Can a member delete a workspace?

The difference is one role word, and it is the most important word in the sentence.

I build an evaluation set with positive and negative pairs:

TypeScript
type CachePairCase = {  firstQuery: string;  secondQuery: string;  shouldReuse: boolean;  reason: string;};

Negative cases should include:

  • changed IDs;
  • changed dates;
  • changed role/permission terms;
  • negation;
  • different product tiers;
  • same topic but different requested operation;
  • questions whose answer depends on current state.

The metric I care about most is false reuse. A cache miss costs another model call. A false hit can return a confidently wrong answer without running the model at all.

That asymmetry usually means I choose precision over maximum hit rate.

Normalize only what is safe to normalize

Lowercasing and trimming whitespace are harmless for many queries. Removing numbers or named entities to get “better semantic matching” can destroy meaning.

For example:

Text
What does error PAYMENT_409 mean?What does error PAYMENT_401 mean?

A normalizer that strips identifiers turns those into the same question.

I keep the original query and embed an intentionally normalized search representation only when I have tests for that normalization.

Exact identifiers can also become hard constraints in the candidate filter rather than hoping an embedding preserves them.

This mirrors hybrid RAG retrieval: semantic similarity is powerful, but exact tokens still carry information.

Cache the provenance with the answer

A cached answer without its evidence is difficult to validate and difficult to show responsibly.

I store the source IDs/versions that produced it and render citations from those records on reuse.

That also means a source update can invalidate entries selectively.

If document refund-policy@17 becomes version 18, I can find entries referencing version 17 and expire them rather than flush every answer in the tenant.

For a knowledge base with high update volume, an inverted index from source version to cache entry can make this invalidation cheap.

The same idea works with application resources: if an answer depends on pricing-plan:pro@42, that version belongs in the cache dependency set.

TTL is a safety net, not the primary invalidation strategy

A fifteen-minute TTL sounds safe until a critical policy changes one minute after an entry is created.

If the cache knows which source versions it used, version validation gives stronger semantics than waiting for time to pass.

TTL still helps with:

  • entries whose dependencies cannot expose versions;
  • limiting old prompt/model behavior;
  • bounding storage;
  • forcing periodic refresh even when source metadata is imperfect.

I prefer dependency-aware invalidation plus TTL rather than TTL as the only concept of freshness.

Prompt changes can invalidate answer semantics

Suppose the source documents are unchanged but I deploy a new prompt that requires shorter answers and stronger abstention behavior.

Should old cached answers remain eligible?

Maybe not.

That is why promptVersion appears in the scope. The same goes for policy and output-schema versions when they materially change the response contract.

I am more selective with model version. If two model releases produce the same validated answer contract, forcing a full cache flush may be unnecessary. If the cache is used to compare model quality during a rollout, model identity absolutely matters.

Cache scope should represent the things whose change would make reuse invalid for the product.

Do not cache hallucinations forever

A semantic cache amplifies whatever quality the original response had.

I only write entries after the answer has passed the same checks I expect for a fresh request:

Text
retrieval authorizationsource/citation validationgrounding checks where requiredoutput policydomain validation

The write boundary comes after validation, not immediately after generation.

If a user reports a bad cached answer, I want an administrative path to invalidate its entry and related variants immediately.

Caching is a multiplier. Good answers get cheaper. Bad answers get repeated faster too.

Cache reads need observability

A cache hit should be visible in the same run trace as a model call would have been.

Useful fields include:

Text
cache.hit = truecache.entry_age_mscache.similaritycache.source_validation_mscache.entry_id

I keep entry_id on traces, not metrics, because it is high-cardinality.

Metrics should report:

Text
hit ratemiss ratefalse-hit rate from sampled/human-reviewed trafficaverage latency savedestimated model cost avoidedinvalidation count by reason

A 70% hit rate is not impressive if users keep receiving stale policy answers. Quality metrics belong next to economic metrics.

A cache hit can still be slower than expected

If source validation requires ten remote database calls, the cache may save model cost while adding almost as much latency as generation.

Batch version reads. Keep version metadata near the cache when possible. Use content/version hashes that can be checked cheaply.

The validation path itself needs a budget.

At some point it can be cheaper and simpler to regenerate the answer. That is another reason to measure end-to-end latency instead of assuming “cache hit” always means fast.

Semantic caching and prompt caching are different layers

Semantic caching reuses an application result across meaningfully equivalent requests.

Provider prompt caching reuses computation for an exact/stable prompt prefix while still running the model for the current request.

They solve different problems and have different invalidation semantics.

I can use both:

Text
semantic cache hit  -> no generation call needed​semantic cache miss  -> build prompt with a stable prefix  -> provider prompt cache may reduce cost/latency  -> generate and validate answer  -> write semantic cache entry if eligible

The next article goes deeper into the prefix side because its engineering tradeoffs are almost the opposite: stable prompt structure matters more than semantic similarity.

When semantic caching is unnecessary

If traffic has little repetition, knowledge changes constantly, every answer is user-specific, or the model call is already cheap and fast, a semantic cache may add more failure modes than value.

Start by measuring repeated intent clusters in real traffic.

A normal exact cache may cover templated requests. Retrieval caching may be enough for RAG. Provider prefix caching may capture most of the cost reduction without reusing final answers.

Semantic answer caching earns its complexity when equivalent questions repeat often and the application can describe exactly what makes an answer reusable.

That last condition is the important one.

Similarity finds candidates. Correctness comes from scope, provenance, authorization, versioning, and invalidation. Without those, a semantic cache is just a fast way to reuse assumptions.

KEEP READING

Related engineering notes