Semantic Caching for LLM Applications: Architecture (2026)

Semantic Caching for LLM Applications: Architecture (2026)

Semantic Caching for LLM Apps: Architecture, Thresholds and Risks (2026)

Last Updated: November 13, 2026

A semantic cache that returns the right answer 97% of the time sounds like a win. Run it at a million requests a month and it serves around six thousand confidently wrong answers, with no error, no alert and a sub-50-millisecond latency that makes the mistake look authoritative. That is the hidden contract of semantic caching LLM systems: you are not building a lookup table, you are deploying a classifier whose false positives ship straight to users.

The economics changed in 2026, too. Anthropic, OpenAI and Google now discount cached input tokens by 90% or more on exact prompt prefixes, which captures much of the savings teams once chased with similarity matching. A semantic layer now has to justify itself on skipped output tokens and latency, not on input cost.

This guide treats caching as a stack of four layers with very different risk profiles. You will leave with a reference architecture, verified provider mechanics, a key-design rule set, a runnable Python cache, an evaluation method for hit precision and an honest cost model.

What this covers: exact vs semantic caching, similarity thresholds and false hits, provider prompt caching as of November 2026, KV-cache reuse, cache keys with tenant, model and version scoping, invalidation, hit-precision evaluation, costs and failure modes.

Context and Background

Caching is the oldest performance trick in computing, and it rests on one assumption: the same key always maps to the same correct value. HTTP caches, CDNs and Redis key-value stores all work because a URL or a primary key identifies its content exactly. When the key matches, the answer is right by construction.

Language model workloads break that assumption from both sides. On the input side, users phrase the same intent in endless ways, so exact string keys almost never collide. “How do I return an item?” and “what’s your returns process” are different bytes and the same question. On the output side, model responses depend on far more than the user’s words. The system prompt, the model snapshot, retrieved documents, tool results, the user’s account state and sampling settings all shape the answer.

Three families of caching emerged in response. Response caches store a finished answer and return it without calling the model, either on exact text match or on embedding similarity. Prompt caches, offered by model providers, store the attention key-value tensors for a repeated prompt prefix so the provider skips recomputing it, while still generating a fresh answer. KV-cache reuse in self-hosted inference engines such as vLLM and SGLang does the same thing inside your own GPUs. Our deep dive on KV cache optimization for LLM inference covers the memory mechanics of that layer.

Early semantic caching tools, including the open-source GPTCache project from Zilliz and the semantic cache extension in Redis’s RedisVL library, popularised the pattern in 2023 and 2024. The typical recipe was simple: embed the query, find the nearest stored query, and return its answer if cosine similarity exceeds a fixed cutoff.

Research since then has been sobering. The vCache paper from UC Berkeley researchers, accepted at ICLR 2026, showed that the similarity scores of correct and incorrect cache hits overlap heavily, so no single global threshold separates them cleanly (arXiv 2502.03771). Separately, a Stanford-led audit presented at ICML 2025 detected prompt cache sharing across users at seven API providers, a privacy problem rooted in timing side channels (arXiv 2502.07776). Both findings shape the architecture below.

The Four-Layer LLM Cache Architecture

A production semantic caching LLM stack has four layers, ordered from safest to riskiest by correctness: an exact-match response cache, a semantic response cache with guards, the provider’s prompt cache, and KV-cache reuse inside the inference engine. The exact and prefix layers are correct by construction. Only the semantic layer can return a wrong answer, so it needs a precision budget, scoped keys and continuous evaluation.

Semantic caching LLM reference architecture with exact cache, semantic cache, provider prompt cache and KV-cache reuse

Figure 1: The four cache layers in a production LLM request path, from exact response match to prefix KV reuse inside the model server.

The request enters a gateway that first decides whether the request is cacheable at all. Cacheable requests check an exact-match store keyed on a normalised query plus scope. A miss falls through to the semantic cache, which embeds the query and runs an approximate nearest-neighbour search inside the same scope. A semantic candidate must pass guards before it is served. Anything that still misses goes to the model, where the provider’s prompt cache or the engine’s prefix cache cuts the cost of the stable prefix. The answer is then written back into both response layers if it is safe to reuse.

Exact and prefix caches are free precision; semantic caches spend it

The single most useful mental model is to separate caches that reuse computation from caches that reuse answers. Provider prompt caching and engine KV reuse reuse computation. The model still reads the full prompt and generates a new answer, so the output is the same as an uncached call. A mismatch of even one token before the breakpoint simply produces a miss, never a wrong answer.

Response caches reuse answers. An exact response cache is still safe if the key captures everything that influences the answer. A semantic response cache is different in kind. It deliberately serves an answer generated for a different input, betting that the difference does not matter. Every semantic hit is a prediction, and predictions have an error rate.

This is why the layers are complementary rather than competing. Prompt caching cuts input cost on every call, including semantic misses. The semantic layer removes whole calls, including output tokens, but only for workloads where paraphrased repeats are common and answers are not personalised.

The cacheability gate matters more than the threshold

Most semantic caching incidents do not come from a badly tuned threshold. They come from caching a request that should never have been cached. “What is my balance?”, “summarise the document I just uploaded” and “what changed today?” all embed close to earlier queries yet need fresh, user-specific answers.

The gate should run before any lookup. It combines static rules, such as routes or intents marked non-cacheable, with request features. Personal pronouns tied to account data, temporal words like “today” or “latest”, attached files, and tool calls with side effects should all bypass the response layers. A conservative gate that sends 40% of traffic to bypass is far cheaper than a permissive gate that leaks a personal answer.

Write-back needs the same discipline. Only store answers that were generated without user-specific context, that passed output safety checks, and that came from a non-streaming or fully completed stream. Never cache an error message, a refusal caused by a transient tool failure, or a truncated answer.

Semantic hits need guards, not just a score

A cosine score compresses an entire sentence into one number, and that number is blind to small tokens that change meaning. “Warranty on model 200” and “warranty on model 300” score very high in most embedding spaces. So do “enable SSO” and “disable SSO”, and “cancel my plan” and “cancel my order”.

Cheap guards catch a large share of these. An entity guard compares numbers, product codes, dates and named entities between the probe and the cached query, and rejects the hit on any mismatch. A negation guard checks for “not”, “never”, “without” and similar operators. An intent guard requires that both queries were classified into the same intent bucket. For high-stakes routes, a small cross-encoder or a lightweight LLM judge can verify equivalence before serving, which costs a few milliseconds but still far less than a full generation.

Where KV-cache reuse fits

If you self-host, the engine layer gives you prefix reuse for free. vLLM’s automatic prefix caching hashes each full KV block from its parent block’s hash, its own tokens and extra keys such as LoRA adapter IDs and multimodal input hashes, then evicts with LRU (vLLM design docs). SGLang’s RadixAttention organises cached prefixes in a radix tree for the same purpose.

The important design hook is vLLM’s cache_salt. Mixing a per-tenant salt into the first block hash means only requests with the same salt can share cached blocks. The vLLM documentation states this prevents timing attacks in which an adversary infers cached content from latency differences. The same docs warn that the faster non-cryptographic hash options raise collision risk that could leak private information in multi-tenant setups, which is why SHA-256 is the default. Our vLLM cost economics deep dive covers how prefix hit rates change GPU sizing.

Provider Prompt Caching in November 2026

Provider prompt caching is now the first optimisation to switch on, because it is correct by construction and the discounts are large. The mechanics differ by vendor and change often, so treat the table below as a dated snapshot verified against official documentation on November 13, 2026.

Provider How you enable it Minimum prefix Cache read price Write cost and lifetime Isolation
Anthropic Claude API Automatic top-level cache_control, or up to 4 explicit breakpoints 512 to 4,096 tokens depending on model 0.1x base input on most models; 0.05x on Opus 5.5 and Sonnet 5.5; 0.025x on some newer models 1.25x for 5-minute TTL, 2x for 1-hour TTL Organization, and workspace on the Claude API
OpenAI API Implicit; optional explicit breakpoints and prompt_cache_key on GPT-5.6 and later 1,024 visible tokens on GPT-5.6 and later 0.1x on GPT-5.6 and later, 0.05x on GPT-6.1 Sol and Terra; model-dependent on earlier models GPT-5.6 and later: 1.25x for 30 minutes, 2.5x for 12 hours; no write charge on earlier models Organization and regional processing boundary
Google Gemini API Implicit on Gemini 2.5 and newer; explicit context caches on Gemini 2.5 and 3 models 2,048 tokens on 2.5 models, 4,096 on 3.1 Pro Preview, 3.6 Flash, 3.8 Flash and 4 Argon About 10% of input on 2.5 and 3.x Flash list prices; $0.10 vs $2.00 per million on 4 Argon Explicit caches add hourly storage billing; default TTL 1 hour Not detailed on the caching page

Sources: Anthropic prompt caching docs, OpenAI prompt caching guide, Google Gemini caching docs and pricing page, all read November 13, 2026. Prices and multipliers change; check before budgeting.

Anthropic: breakpoints, lookback and TTL

Anthropic caches the prefix in the order tools, then system, then messages, up to a block marked with cache_control. You can let the API place the breakpoint automatically or mark up to four blocks yourself. The default TTL is five minutes, refreshed at no cost on every hit, and a one-hour TTL is available at a 2x write multiplier. Writes cost 1.25x base input for the five-minute tier, and reads cost 0.1x on most models, according to the Anthropic prompt caching documentation.

Two details catch teams out. First, prompts below the model’s minimum, which ranges from 512 to 4,096 tokens, are silently processed without caching and no error is returned. Check that cache_creation_input_tokens or cache_read_input_tokens is non-zero. Second, each breakpoint looks back at most 20 blocks for an earlier write, so a long agent conversation can drift beyond the reach of its last cache write unless you add a second breakpoint.

Changing tool definitions invalidates the entire cache, and toggling features like web search invalidates the system and message segments. Keep tool schemas stable and sorted.

OpenAI: routing, keys and the 15 requests per minute rule

OpenAI caching is implicit. Requests are routed using a hash of the initial prompt tokens and an optional prompt_cache_key, and caches live on individual machines. The OpenAI prompt caching guide suggests keeping each key to roughly 15 requests per minute and partitioning busier traffic across several keys, because overflow routing to a cold machine causes misses.

For GPT-5.6 and later models, OpenAI added write pricing and explicit lifetimes: 1.25x for the default 30-minute lifetime and 2.5x for 12 hours, with reads at 0.1x. On those models the cache key is mainly for per-customer accounting, and OpenAI notes separate keys help prevent cache-hit probing across users. Earlier models have no write charge and model-dependent read discounts. Read usage.input_tokens_details.cached_tokens to confirm hits.

Gemini: implicit by default, explicit for big shared context

Google enables implicit caching by default on Gemini 2.5 and newer models, passing savings through automatically when a request hits. Explicit context caching lets you upload a large shared context once, reference it by name and pay hourly storage, with a default TTL of one hour. The Gemini caching documentation notes explicit caching is not supported on Gemini 4 Argon, which relies on implicit caching only.

The practical rule for all three

Put everything stable at the front and everything variable at the end. Tool schemas, the system prompt, policies and few-shot examples go first. Retrieved documents, conversation history and the user’s message go last. Never put a timestamp, request ID or randomised example order in the prefix, because a single changed token before the breakpoint turns every request into a miss.

Similarity Thresholds and False-Hit Risk

The similarity threshold is where semantic caching for LLM apps earns or loses trust. A cosine cutoff converts a continuous similarity score into a binary serve-or-skip decision, and every choice trades hit rate against precision. The uncomfortable fact is that the trade-off curve is often flat in the region you care about.

Semantic cache lookup decision flow with similarity threshold, entity guard and verifier

Figure 2: A semantic hit must clear the score threshold, freshness, an entity guard and, on high-stakes routes, a verifier before it is served.

Figure 2 shows the decision path. The top-k neighbours are retrieved inside the request’s scope, then checked in order. A candidate below the threshold ends the search. A candidate above it must also be unexpired, match on entities and, where configured, pass a cross-encoder or judge check. Only then is the cached answer returned and the hit logged with its score for later evaluation.

Why one global threshold fails

Embedding models place sentences by topic and phrasing, not by whether two questions have the same answer. Two questions about return policies sit close together whether one asks about returns and the other about exchanges. Meanwhile, a terse query and a verbose paraphrase of the same intent can sit further apart than two different questions with shared vocabulary.

The vCache authors measured this directly and found that the similarity distributions of correct and incorrect hits overlap heavily. Their answer is to learn a separate threshold for each cached embedding online, fitting a sigmoid model of correctness against similarity, so the cache meets a user-specified maximum error rate. The paper reports up to 12.5x higher hit rates and up to 26x lower error rates than static-threshold baselines on its benchmarks, while noting that its guarantees assume i.i.d. traffic.

The lesson applies even without vCache: thresholds should vary by route and come from labelled data, not library defaults.

What the scores look like in practice

The runnable example later in this post makes the problem concrete with a deliberately simple embedder. The genuine paraphrase “What is the return policy?” scores 0.667 against the cached “What is your return policy?”. The different question “What is your exchange policy?” scores exactly the same 0.667. No threshold can admit the first and reject the second.

Real embedding models produce higher absolute scores and better separation than a hashed bag of words, but the structure of the problem is the same. Similarity measures overlap in wording and topic. It does not measure whether the answer transfers. Exchanges and returns share a policy page; they do not share an answer.

The precision budget

Instead of asking “what threshold should we use?”, ask “how many wrong answers per million requests can this route tolerate?”. That number, the precision budget, is a product and risk decision. A marketing FAQ bot might accept one wrong answer in a hundred hits. A medication dosage assistant should accept zero, which means it should not use a semantic response cache at all.

Once the budget exists, the threshold becomes an output. You label a sample of candidate hits, compute precision at each threshold, and pick the lowest threshold whose lower confidence bound on precision still clears the budget. If no threshold clears it with a useful hit rate, the route is not a semantic caching candidate. That is a valid and common outcome.

Verifiers move the frontier

A verifier changes the shape of the curve rather than sliding along it. With a cross-encoder or a small judge model checking each candidate, you can run a lower similarity threshold to widen recall, then let the verifier reject the false positives. The cost is extra latency on candidate hits only, typically far below a full generation, plus the verifier’s own error rate, which you must measure the same way.

Cache Key Design: Tenant, Model and Version Scoping

A cache key is a claim that everything outside the key does not affect the answer. Most semantic cache bugs are keys that make that claim falsely. The fix is to scope every lookup by a namespace derived from all answer-shaping inputs, then match on meaning only within that namespace.

Cache key design for LLM semantic cache scoped by tenant, model, prompt version and corpus version

Figure 3: The namespace hash combines tenant, pinned model, prompt version, embedding model, corpus version and locale. Similarity search runs only inside one namespace.

What belongs in the namespace

Tenant ID comes first, always. Even when two tenants ask identical questions, their answers may differ by contract, configuration or data, and a shared entry is a data-leak path. Sharing across tenants should be an explicit, reviewed opt-in for genuinely public content only.

Pinned model snapshot, not an alias. An alias like “latest” can move under you, so a cache keyed on the alias serves answers from the old model after an upgrade. Use the dated snapshot identifier your provider returns.

Prompt and template version. Any change to the system prompt, few-shot examples, output format or tool definitions changes answers. Version these artefacts and put the version in the key. Our guide to context engineering for LLM agents covers how to structure and version those prompt components.

Embedding model and version. Vectors from different embedding models live in incompatible spaces. Mixing them in one index produces meaningless scores, so a new embedding model means a new namespace and a re-embed or cold start.

Corpus or index version for retrieval-augmented generation (RAG) answers. If the answer was grounded in documents, the cached entry is only valid for that document snapshot. Bumping the corpus version invalidates every dependent entry at once without a scan.

Locale and output settings, such as language, region, reading level or response format, whenever they change the answer.

What stays out of the namespace

Do not put the raw user ID into the namespace for shared-answer routes, or your hit rate collapses to the per-user repeat rate. If the answer depends on the user, the route is not cacheable at the response layer. Equally, do not include volatile request metadata such as timestamps or trace IDs.

Hash the namespace, store the fields

Hash a canonical, sorted serialisation of the scope fields to get a short, uniform namespace. Also store each field as metadata on every entry, so you can purge by tenant and audit what a model version served.

Walk-through: A Runnable Two-Tier Cache in Python

The example below implements the architecture in about 150 lines with only NumPy as a dependency. It includes a cacheability gate, an exact tier on normalised text, a semantic tier with top-k search, TTL expiry, an entity guard, scoped namespaces and a precision-at-threshold evaluator. Save it as semcache.py and run python3 semcache.py; it was tested with Python 3.10 and NumPy 2.2.

The embedder is a hashed bag of words and word pairs, chosen so the code runs offline. It is deliberately weak, which makes threshold behaviour easy to see. Replace toy_embed with a real embedding model, such as a sentence-transformers model or a hosted embeddings API, before using it for anything real.

"""Two-tier (exact + semantic) LLM response cache with scoped keys.

Runs with numpy only. toy_embed() is a hashed bag-of-words stand-in;
swap in a real embedding model for production use.
"""
import hashlib, json, re, time
from dataclasses import dataclass, asdict
import numpy as np

DIM = 1024

def toy_embed(text: str) -> np.ndarray:
    v = np.zeros(DIM, dtype=np.float32)
    toks = re.findall(r"[a-z0-9]+", text.lower())
    for f in toks + [a + "_" + b for a, b in zip(toks, toks[1:])]:
        h = int.from_bytes(hashlib.blake2b(f.encode(), digest_size=8).digest(), "big")
        v[h % DIM] += 1.0
    n = np.linalg.norm(v)
    return v / n if n else v

@dataclass(frozen=True)
class CacheScope:
    tenant_id: str
    model: str            # pinned model snapshot, never an alias
    prompt_version: str   # system prompt + template version
    embed_model: str      # embedding model and version
    corpus_version: str = "none"  # RAG index snapshot id
    locale: str = "en"

    def ns(self) -> str:
        raw = json.dumps(asdict(self), sort_keys=True)
        return hashlib.sha256(raw.encode()).hexdigest()[:16]

def normalize(q: str) -> str:
    return re.sub(r"\s+", " ", q.strip().lower()).rstrip("?.! ")

NUM = re.compile(r"\d+(?:\.\d+)?")
NO_CACHE = re.compile(r"\b(my|today|now|latest|current)\b", re.I)

class TwoTierCache:
    def __init__(self, embed=toy_embed, threshold=0.80, ttl_s=3600):
        self.embed, self.threshold, self.ttl_s = embed, threshold, ttl_s
        self.exact = {}   # (ns, normalized query) -> entry
        self.sem = {}     # ns -> {"vecs": [...], "entries": [...]}

    def cacheable(self, q: str) -> bool:
        return not NO_CACHE.search(q)

    def lookup(self, scope, q, now=None):
        now = now or time.time()
        if not self.cacheable(q):
            return None, "bypass", None
        ns = scope.ns()
        e = self.exact.get((ns, normalize(q)))
        if e and now < e["expires"]:
            return e["response"], "exact", 1.0
        bucket = self.sem.get(ns)
        if not bucket or not bucket["vecs"]:
            return None, "miss", None
        qv = self.embed(q)
        sims = np.stack(bucket["vecs"]) @ qv
        verdict = "miss"
        for i in np.argsort(-sims)[:3]:          # top-k, then guards
            e, s = bucket["entries"][i], float(sims[i])
            if s < self.threshold:
                break
            if now >= e["expires"]:
                continue
            if set(NUM.findall(q)) != set(NUM.findall(e["query"])):
                verdict = "guarded"               # entity guard
                continue
            return e["response"], "semantic", s
        return None, verdict, float(sims.max())

    def store(self, scope, q, response, now=None):
        if not self.cacheable(q):
            return
        now = now or time.time()
        ns = scope.ns()
        e = {"query": q, "response": response, "expires": now + self.ttl_s}
        self.exact[(ns, normalize(q))] = e
        b = self.sem.setdefault(ns, {"vecs": [], "entries": []})
        b["vecs"].append(self.embed(q)); b["entries"].append(e)

    def purge_namespace(self, scope):
        ns = scope.ns()
        self.sem.pop(ns, None)
        self.exact = {k: v for k, v in self.exact.items() if k[0] != ns}

def precision_at(cache, scope, labelled, thresholds):
    """labelled: (query, expected_cached_query or None)."""
    rows = []
    for t in thresholds:
        cache.threshold = t
        hits = correct = 0
        for q, gold in labelled:
            resp, kind, _ = cache.lookup(scope, q)
            if kind in ("exact", "semantic"):
                hits += 1
                correct += int(resp == ANSWERS.get(gold))
        rows.append((t, hits / len(labelled), correct / hits if hits else float("nan")))
    return rows

ANSWERS = {
    "What is your return policy?": "Returns accepted within 30 days with receipt.",
    "How do I reset the device to factory settings?": "Hold the reset button for 10 seconds.",
    "Which plan includes SSO?": "SSO is included in the Enterprise plan.",
    "What is the warranty on model 200?": "Model 200 carries a 2-year warranty.",
}

if __name__ == "__main__":
    a = CacheScope("tenant-a", "model-2026-10-01", "support-v7", "toy-hash-1024")
    b = CacheScope("tenant-b", "model-2026-10-01", "support-v7", "toy-hash-1024")
    cache = TwoTierCache(threshold=0.80)
    for q, r in ANSWERS.items():
        cache.store(a, q, r)

    probes = [
        "what is your return policy",
        "What is the return policy?",
        "How do I reset the device to factory settings please?",
        "What is the warranty on model 300?",
        "Which plan includes SAML SSO?",
        "What is your exchange policy?",
        "What is my order status?",
    ]
    for p in probes:
        resp, kind, s = cache.lookup(a, p)
        print(f"{kind:8s} {'' if s is None else f'{s:.3f}':6s} {p!r} -> {resp}")
    print("tenant-b:", cache.lookup(b, "What is your return policy?")[1])

    labelled = [(p, g) for p, g in [
        ("What is the return policy?", "What is your return policy?"),
        ("How do I reset the device to factory settings please?",
         "How do I reset the device to factory settings?"),
        ("Which plan includes SAML SSO?", "Which plan includes SSO?"),
        ("What is the warranty on model 300?", None),
        ("What is the refund policy for gift cards?", None),
        ("How do I reset the router password?", None),
        ("What is your exchange policy?", None),
    ]]
    for t, hr, prec in precision_at(cache, a, labelled, [0.5, 0.6, 0.7, 0.8]):
        print(f"threshold={t:.2f} hit_rate={hr:.2f} precision={prec:.2f}")

Running it produces the following output on the test machine:

exact    1.000  'what is your return policy' -> Returns accepted within 30 days with receipt.
miss     0.667  'What is the return policy?' -> None
semantic 0.946  'How do I reset the device to factory settings please?' -> Hold the reset button for 10 seconds.
guarded  0.846  'What is the warranty on model 300?' -> None
miss     0.756  'Which plan includes SAML SSO?' -> None
miss     0.667  'What is your exchange policy?' -> None
bypass          'What is my order status?' -> None
tenant-b: miss
threshold=0.50 hit_rate=0.71 precision=0.60
threshold=0.60 hit_rate=0.71 precision=0.60
threshold=0.70 hit_rate=0.29 precision=1.00
threshold=0.80 hit_rate=0.14 precision=1.00

Reading the results

Each line teaches one part of the design. The first probe differs from a stored query only in case and punctuation, so the exact tier catches it without computing an embedding. The factory-reset paraphrase scores 0.946 and is served from the semantic tier.

The warranty probe is the important one. It scores 0.846, above the 0.80 threshold, against “What is the warranty on model 200?”. Without the entity guard it would have served the model 200 warranty for model 300. The guard compares the numeric tokens, sees {300} against {200}, and rejects the candidate.

“What is my order status?” never reaches a lookup because the gate spots the possessive “my”. Tenant B’s identical return-policy question misses because its namespace hash differs, which is exactly the isolation we want.

The precision sweep shows the cliff. At thresholds of 0.5 and 0.6 the cache answers five of seven labelled probes, but two of those five are wrong, including the exchange-policy question served the returns answer. At 0.7 precision reaches 1.0 but hit rate falls to 0.29. With seven labelled probes these numbers illustrate the method, not a benchmark. A real evaluation needs hundreds to thousands of labelled pairs per route.

Taking it to production

Three changes turn the sketch into a service. Move storage to a vector database or Redis with a vector index, partitioned or filtered by namespace, and use an approximate nearest-neighbour index such as HNSW. Replace the regex gate with route-level policy plus an intent classifier. Emit a structured log record for every lookup with namespace, top score, decision and cached entry ID, which is the raw material for evaluation.

If you use RedisVL, its SemanticCache already offers ttl, filterable_fields and per-call distance_threshold. Remember that RedisVL thresholds are cosine distance in the range 0 to 2, so a distance of 0.1 means similarity 0.9. Teams regularly invert this and run a wildly permissive cache.

Invalidation and Freshness

Invalidation is harder here than in a key-value cache, because a semantic entry answers a whole neighbourhood of queries. Invalidating one stored answer silently changes the response for every paraphrase that used to land on it.

Four invalidation mechanisms

Version bumps are the workhorse. Because the model snapshot, prompt version and corpus version are in the namespace, publishing any of them creates a fresh namespace. Old entries become unreachable immediately and age out under TTL or a background sweeper. No scan, no race.

TTL bounds staleness for everything else. Set it per route from the rate at which the underlying truth changes. A product-spec FAQ might tolerate seven days; a pricing answer might need one hour; anything citing live inventory should not be cached.

Event-driven purges handle targeted changes. When a source document is updated, delete entries whose stored provenance lists that document ID. This requires recording provenance at write time, which costs a few bytes per entry and pays for itself the first time legal asks you to pull an answer.

Tenant and subject purges cover offboarding and data-subject deletion requests. Because tenant ID is stored as a field on every entry, a purge is a filtered delete rather than a forensic search.

Stale-while-revalidate for LLM answers

A useful hybrid borrowed from HTTP caching is to serve a cached answer while asynchronously regenerating a fraction of hits. Compare the fresh answer to the cached one with a semantic equivalence check. If they diverge, replace the entry and count the divergence. That divergence rate is a live freshness signal per route and an early warning of upstream changes nobody told you about.

Evaluating Hit Precision

You cannot tune what you do not measure, and a semantic cache’s main failure is invisible in latency and error dashboards. Evaluation has to be designed in from the start.

Offline: labelled pairs and a sweep

Build a labelled set from real traffic. Sample probe queries, retrieve their top candidate from the cache with its score, and have humans or a calibrated judge label whether the cached answer is correct for the probe. Stratify the sample across score bands so you have enough examples near the decision boundary, where most errors live.

From the labels, compute hit rate and precision at each candidate threshold, per route. Report a confidence interval, not a point estimate. With 200 labelled hits and zero errors, the 95% upper bound on error rate is still about 1.5% by the rule of three, which may already exceed a strict budget.

Online: shadow mode before serving

Run a new semantic layer in shadow mode first. The cache performs lookups and logs would-be hits, but every request still goes to the model. Comparing the cached answer with the live answer for each would-be hit gives an automatic, continuous precision estimate on real traffic before any user sees a cached response.

After launch, keep a small sampling rate of hits, for example one to five percent, going to the model anyway for comparison. Combine that with user feedback signals such as thumbs-down rates and re-asks within a session, segmented by cache hit versus miss. A higher re-ask rate on hits is a reliable smell.

Metrics to put on the dashboard

Track per route: exact hit rate, semantic hit rate, bypass rate, guard-rejection rate, estimated hit precision with its interval, score distribution of served hits, divergence rate from revalidation, and entry age at serve time. When a model or embedding version changes, these should reset visibly because the namespace changed. If they do not, your key design has a hole.

Cost Model: When a Semantic Layer Pays Off

The model below is illustrative. It uses round numbers to show the structure of the calculation, not any provider’s actual price list. Substitute your own prices, token counts and measured hit rates.

Assume one million requests per month. Each request has 1,500 input tokens, of which 1,200 are a stable prefix of tools, system prompt and examples, plus 400 output tokens. Assume an input price of $3 per million tokens and an output price of $15 per million.

Scenario Input cost Output cost Other Monthly total
No caching $4,500 $6,000 none $10,500
Prompt caching only $1,467 $6,000 none $7,467
Prompt caching plus 20% semantic hits $1,174 $4,800 about $300 infra and embeddings about $6,274

Illustrative numbers only. Prompt caching assumes 95% of requests read the 1,200-token prefix at 0.1x and 5% write it at 1.25x.

The prompt-caching row works out as follows. Reads cost 0.95 x 1.2 billion tokens x $0.30 per million, which is $342. Writes cost 0.05 x 1.2 billion x $3.75 per million, which is $225. The uncached 300-token tail costs $900. Input falls from $4,500 to $1,467, a 67% cut, with zero risk to answer quality.

Adding a semantic layer with a 20% hit rate removes a fifth of the remaining calls, saving about $1,500 in tokens. Subtract a few hundred dollars for the vector store and embedding calls and the net saving is roughly $1,200 a month, or about 16% on top of prompt caching. Embedding cost itself is tiny: at a hypothetical $0.02 per million embedding tokens, a million 50-token queries cost about a dollar.

Now price the errors. At 98% hit precision, 20% hits on a million requests means 4,000 wrong answers a month. If each wrong answer triggers a support contact costing even a few dollars, the semantic layer can be net negative.

Two conclusions follow. First, prompt caching captures most of the input savings with no quality risk, so it should always come first. Second, a semantic layer’s real value is skipping output tokens and cutting latency from seconds to tens of milliseconds. It earns its place on high-volume, repetitive, non-personalised routes where answers are cheap to verify.

Trade-offs, Gotchas, and What Goes Wrong

Semantic caches fail quietly. The failure modes below are the ones that recur, roughly in order of how much damage they do.

Semantic cache failure modes including cross-tenant leakage, stale answers, false hits and timing side channels

Figure 4: Common semantic cache failure modes mapped to the control that prevents each one.

Cross-tenant leakage. A shared index without tenant scoping returns tenant A’s answer, which may contain their pricing, configuration or names, to tenant B. Metadata filters applied after an approximate search are not enough on their own if the top-k results are all from another tenant and get filtered to nothing, or worse, if a filter bug lets them through. Partition by namespace, or apply the tenant filter inside the vector query, and test isolation explicitly.

Personalised answers cached as shared. An answer generated with user context, such as their plan, location or history, gets stored and served to someone else. The fix is write-time policy: only store answers from requests that carried no user-specific context.

Stale answers. Prices, policies and documentation change while cached answers keep serving. TTLs that are too long, missing corpus versions in keys and absent event purges all produce this. Revalidation sampling catches it after the fact.

False hits on near-miss queries. Different numbers, negations, product variants and “my” versus “your” phrasing all score high. Entity and negation guards plus per-route thresholds reduce this; they never eliminate it.

Timing side channels. A cache hit is visibly faster than a miss. If caches are shared, an attacker can probe whether someone else recently asked a specific question. The ICML 2025 audit found exactly this pattern in provider prompt caches. Scope caches per tenant, consider per-user scoping for sensitive routes, and use cache_salt in vLLM.

Cache poisoning. If users can influence what gets stored, a crafted prompt can plant a harmful answer that is then served to everyone who asks a similar question. Store only answers that passed output moderation, and never store answers from adversarially flagged sessions.

Embedding drift and mixed spaces. Upgrading the embedding model without changing the namespace produces meaningless similarity scores, and hit precision collapses without any error.

Hit-rate theatre. A high hit rate is not success. A semantic cache serving 40% of traffic at 90% precision is worse than one serving 10% at 99.9%.

Practical Recommendations

Start with what is free and correct, then add risk only where you can measure it. For most teams that means provider prompt caching this week, an exact response cache next, and a semantic layer only on routes that pass a precision-budget review.

Treat the semantic layer as a model you deploy. It has a training set (your cached entries), a decision threshold, an error rate and drift. It deserves the same shadow testing, evaluation and rollback paths as any model. If nobody owns its precision number, switch it off.

Design keys before choosing a vector database. The namespace scheme decides whether invalidation is a version bump or an incident, and whether tenant isolation is structural or hopeful. Vector store choice is comparatively easy to change later.

Checklist:

  • [ ] Stable prefix first, variable content last; provider cached-token counts monitored per route.
  • [ ] Cacheability gate in front of all response layers, with route-level allow-lists.
  • [ ] Namespace hash includes tenant, pinned model, prompt version, embedding model, corpus version and locale.
  • [ ] Entity and negation guards on every semantic hit; verifier on high-stakes routes.
  • [ ] Per-route thresholds set from labelled data with confidence intervals.
  • [ ] Shadow mode before launch, 1 to 5 percent revalidation sampling after.
  • [ ] TTL per route, provenance stored per entry, tenant purge tested.
  • [ ] Only moderated, non-personalised, complete answers written back.

Frequently Asked Questions

What is semantic caching for LLM applications?

Semantic caching stores previous LLM responses alongside an embedding of the query that produced them. When a new query arrives, the cache embeds it, searches for the most similar stored query and, if similarity clears a threshold and safety guards pass, returns the stored answer without calling the model. Unlike an exact-match cache, it catches paraphrases. Unlike provider prompt caching, it skips generation entirely, which saves output tokens and latency but introduces the risk of serving an answer to a question that only looks similar.

What similarity threshold should a semantic cache use?

There is no universal value. Library defaults such as RedisVL’s cosine distance of 0.1, equivalent to similarity 0.9, are starting points, not answers. The right threshold depends on the embedding model, the route and how many wrong answers that route can tolerate. Label a sample of real candidate hits, compute precision at several thresholds and choose the lowest threshold whose confidence bound still meets your precision budget. Expect different routes to need different values, and recalibrate whenever the embedding model changes.

Is provider prompt caching the same as semantic caching?

No. Prompt caching from Anthropic, OpenAI and Google reuses the computed attention state for an identical prompt prefix, then generates a fresh answer. It requires an exact token match up to the cache point and cannot return a wrong answer. Semantic caching returns a previously generated answer for a similar but different query. Prompt caching cuts input cost, with cached reads at around 0.1x of the input price on many current models, while semantic caching removes whole calls. Most production systems should use both.

How do you prevent cross-tenant data leakage in a semantic cache?

Put the tenant ID into the namespace that scopes every lookup, so similarity search never sees another tenant’s entries. Prefer physical partitioning or filters applied inside the vector query over post-filtering. Never write back answers generated with user-specific context into a shared namespace. Add automated tests that store an entry for one tenant and assert a miss for another. For self-hosted engines, use per-tenant cache salts so prefix KV blocks are not shared, which also blocks timing side-channel probing.

How do you invalidate a semantic cache when content changes?

Combine four mechanisms. Version the model, prompt and document corpus and include those versions in the namespace, so a release creates a fresh cache automatically. Set per-route TTLs based on how fast the underlying facts change. Record source document IDs with each entry so an update can purge dependent answers. Finally, sample a small share of hits for regeneration and compare the fresh answer with the cached one, which measures staleness on live traffic and catches changes nobody announced.

When should you not use a semantic cache?

Skip it when answers depend on the user’s identity, account or recent actions, when facts change faster than any useful TTL, and when a single wrong answer is costly, as in medical, legal or financial advice. It is also a poor fit when traffic has little paraphrased repetition, because hit rates will be too low to cover infrastructure and evaluation effort. In those cases provider prompt caching and engine prefix caching still deliver large savings with no correctness risk.

Further Reading

By Riju — about

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *