Semantic Caching for LLM Apps: When Similar Queries Can Share an Answer (2026)

Khimananda Oli 12 min read Database, Virtualization
Semantic Caching for LLM Apps: When Similar Queries Can Share an Answer (2026)

By Khimananda Oli | Last reviewed: November 2026

A semantic cache stores LLM responses keyed by the meaning of the query rather than its exact text. When a new query lands close enough in embedding space to one already answered, the cache returns the stored answer and the model is never called. "How do I reset my password?" and "I forgot my password, how do I change it?" can share one response. The saving is a whole model call per hit. The risk is the mirror image: a cache hit that's close in embedding space but different in meaning serves a wrong answer with no error and no warning. Semantic caching works when you treat the similarity threshold as a safety control, scope the cache key carefully, and keep personalised and time-sensitive answers out of it entirely.

How is semantic caching different from prompt caching?

The names are close enough that the two get mixed up, but they work at different layers and save different things. Prompt caching is a provider-side optimisation: the inference engine reuses the computed state for an identical prompt prefix (a long system prompt, a shared document) and only processes the new tokens after it. The model still runs and still generates a fresh answer; you just pay less for the repeated prefix. Semantic caching sits in your application, in front of the model, and when it hits, the model doesn't run at all.

Exact-match cachePrompt (prefix) cachingSemantic caching
Where it livesYour app (Redis, memory)The model provider / inference engineYour app, plus an embedding model and vector index
Matches onIdentical query textIdentical prompt prefix, byte for byteSimilar meaning, within a distance threshold
On a hitModel skippedModel still runs, prefix is cheaperModel skipped
Can it return a wrong answer?Only if the answer went staleNo, the answer is always freshly generatedYes: a close-but-different query gets the other query's answer
Hit rate on real trafficLow, since people rarely phrase things identicallyHigh wherever the prefix is reusedHigher than exact match, depends on the threshold

The bottom two rows explain why the techniques aren't interchangeable. GPTCache, one of the better-known open-source semantic cache libraries, explains its own reason for existing in these terms: exact-match caching is "less effective due to the complexity and variability of LLM queries," which leads to a low hit rate. Semantic caching raises the hit rate by accepting near matches, and accepting near matches is exactly what makes a wrong answer possible. The layers stack, too. A request that misses the semantic cache still benefits from prompt caching on its way to the model.

How does a semantic cache actually work?

Every implementation follows the same loop. The incoming query is turned into an embedding vector. A vector search finds the closest stored query. If that query's distance is within the threshold, the stored response is returned. If not, the LLM is called, and the new query, its embedding and the response are written to the cache for next time.

GPTCache's README breaks this into separate modules, and the breakdown is a useful checklist even if you build your own. There's an LLM adapter that puts one interface in front of different providers, and an embedding generator that turns requests into vectors (with embeddings disabled, GPTCache notes it becomes a keyword-matching cache). Cache storage holds the responses themselves, and a vector store finds the K most similar earlier requests. The cache manager handles eviction, and the similarity evaluator makes the final call on whether a candidate counts as a match. That last module is the one that matters most. The vector store only finds the nearest neighbour, and the nearest neighbour always exists. The evaluator decides whether it's near enough.

The semantic cache request loopThe nearest match always exists: the threshold decides whether it's near enoughUser queryEmbedquery to vectorVector searchnearest cached queryDistance within threshold?and same scope (tenant, model, version)Yes: cache hitReturn the stored responseNo model call: fast, near-zero costNo: cache missCall the LLMfull cost and latencyStore query, vector, responsewith a TTL, if the answer is cacheableThe failure mode nobody seesA false hit returns another query's answer as if it were correct.No error is raised and no model runs, so nothing flags it.Only deliberate sampling against the live model catches it.
A semantic cache embeds each query, finds the nearest stored one, and uses a distance threshold to choose between returning the cached answer and calling the model.

Why is the similarity threshold the whole game?

Everything good and bad about a semantic cache comes down to one number. RedisVL, Redis's Python library for vector workloads, uses cosine distance for its SemanticCache. Its documentation describes the range as 0 to 2, "where 0 means identical and 2 means completely different," and a lower threshold is stricter. A query hits only if its distance to a stored query is within the threshold.

A loose threshold (high distance allowed) gives more hits and a lower bill, but more queries that only look similar get the wrong answer. A strict threshold (low distance allowed) means fewer wrong answers but fewer hits, until the cache saves so little that it isn't worth running. GPTCache's README states the trade-off plainly: "In a semantic cache, you may encounter false positives during cache hits and false negatives during cache misses." No threshold value is universally right. It depends on your embedding model, your domain and how much a wrong answer costs you.

The hard cases are queries that embed close together but mean different things. "How do I cancel my order?" and "How do I cancel my subscription?" share almost every word and most of their meaning, and they need different answers. So do "Is the API down?" asked on two different days, and "What's my account balance?" asked by two different users. Embedding similarity measures how alike the wording and topic are. It can't tell whether two questions need the same answer, which is the only thing that matters for a cache.

One number, two failure modesCosine distance threshold (RedisVL: 0 = identical, 2 = completely different)Strictlow distanceLoosehigh distanceYour setting: found by measurementToo strictFew false hits, so answers stay correctOnly near-duplicate phrasings hitHit rate drops toward exact-match levelsCost: a cache that barely savesToo looseHigh hit rate, low model bill"cancel my order" can hit"cancel my subscription"Cost: wrong answers, silently servedStart strict, label real near-miss pairs from your traffic,and loosen only as far as the false-hit rate allows
A strict threshold keeps semantic cache answers correct but saves little; a loose one saves more and starts serving wrong answers. The right value comes from labelled pairs taken from your own traffic.

What does a semantic cache look like in code?

RedisVL's SemanticCache is a compact example of the API shape most libraries share. The import path, method names and parameters below come from RedisVL's own user guide. The threshold value is the one from its example, not a recommendation for your traffic.

from redisvl.extensions.cache.llm import SemanticCache
from redisvl.utils.vectorize import HFTextVectorizer

cache = SemanticCache(
    name="support_llmcache",
    redis_url="redis://localhost:6379",
    distance_threshold=0.1,   # cosine distance, 0-2; lower is stricter
    vectorizer=HFTextVectorizer("redis/langcache-embed-v2"),
    filterable_fields=[
        {"name": "tenant_id", "type": "tag"},
        {"name": "prompt_version", "type": "tag"},
    ],
    ttl=86400,                # default is None: entries never expire
)

def answer(query: str, tenant_id: str, llm) -> str:
    from redisvl.query.filter import Tag
    scope = (Tag("tenant_id") == tenant_id) & (Tag("prompt_version") == "v7")

    hits = cache.check(prompt=query, filter_expression=scope, num_results=1)
    if hits:
        return hits[0]["response"]

    response = llm.generate(query)
    cache.store(
        prompt=query,
        response=response,
        filters={"tenant_id": tenant_id, "prompt_version": "v7"},
    )
    return response

Two details in that snippet carry most of the safety. The first is ttl. RedisVL's documented default is None, meaning entries persist forever, and that's the wrong default for almost any LLM answer. Product details change, policies change and documentation changes, while a cached answer stays exactly as it was on the day it was stored. The second is the filterable_fields scope. Without it, every tenant shares one cache, and a query from one customer can be answered with a response generated for another. Scoping by tenant, and by the prompt or model version that produced the answer, turns "is this close enough" into "is this close enough and from the same context." That's the question you actually need answered.

What should never go into a semantic cache?

The safest semantic cache is one you're picky about filling. Some categories of answer are wrong to reuse even when the query matches perfectly:

  • Personalised answers. Anything built from the user's own data (their orders, balance, tickets, permissions) belongs to that user alone. Scoping by user ID makes this technically safe, but at that point the hit rate is close to zero and the cache adds risk without saving anything.
  • Time-sensitive answers. Status, prices, availability, "latest", "today". The query embeds the same tomorrow while the correct answer doesn't stay the same.
  • Follow-ups that depend on context. "What about the second one?" means nothing without the conversation before it. The MeanCache paper (IPDPS 2025) calls out handling contextual queries as a weakness of existing caches that leads to false hits. Only cache standalone queries, or include the relevant conversation context in what you embed.
  • Agent actions and tool calls. A cached answer can be stale. A cached action repeats a side effect. Never cache anything that executes, writes or calls an external system. Cache the read-only, explanatory layer only.
  • High-stakes answers. Medical, legal, financial or security guidance, where a plausible wrong answer costs far more than a model call. Either leave these out or hold them to a much stricter threshold.

What's left is a lot of genuinely repetitive traffic: FAQ-style support questions, documentation lookups, product explanations, and standard "how do I" queries where the answer is the same for everyone and changes slowly. That's where semantic caching earns its keep. The MeanCache authors report that in their analysis repeated queries made up about 31% of all queries. That's a useful order of magnitude, but measure your own traffic before you plan around it. A support bot and a coding assistant will repeat themselves at very different rates.

What belongs in a semantic cache?Decide by answer type, before any threshold tuningSafe to cacheFAQ-style support questionsDocumentation and how-to lookupsProduct and feature explanationsStandalone queries with no contextRead-only, explanatory answersSame answer for everyone,changes slowly, always with a TTLNever cachePersonalised: orders, balance, ticketsTime-sensitive: status, price, "today"Context-dependent follow-upsAgent actions and tool callsHigh-stakes: medical, legal, securityA perfect match can still bethe wrong answer to reuseScope every entry by tenant plus model and prompt version,so a prompt change never serves answers from the old prompt
Decide what's cacheable by answer type first. Similarity tuning only matters for the answers that were safe to cache to begin with.

How do you run a semantic cache in production without it rotting?

The operational problems are the usual caching problems, plus one new one. The usual ones: entries go stale, memory grows and invalidation is hard. Cache invalidation patterns apply directly. Use TTLs as the backstop, and purge explicitly when the source of truth changes. The rule that's specific to LLM caches is that a prompt change or a model change invalidates every entry it produced. If you edit the system prompt to fix a tone problem, every cached answer still has the old tone. Putting the prompt version in the cache scope, as in the code above, handles this without a manual flush. Bump the version and the old entries can never match again.

Watch eviction too. GPTCache's README warns that its eviction decisions are "based solely on the number of lines", and it says outright that this can cause inaccurate resource estimates and out-of-memory errors. Long LLM responses vary a lot in size, so an entry count is a poor proxy for memory. If your cache runs on Redis, set a memory limit and an eviction policy at the Redis level as well. The Redis caching patterns you already use for web apps carry over unchanged.

The new problem is the one from the first diagram: a false hit is invisible. Nothing errors, so it won't show up on any dashboard unless you deliberately go looking. Two habits make it visible. First, log every lookup with its outcome and its distance score, alongside your normal LLM telemetry. If you instrument with OpenTelemetry's GenAI semantic conventions, a cache hit is simply a request with no model span under it, plus a custom attribute for the distance. A cluster of hits right at the edge of the threshold is where to look first. Second, sample a small share of cache hits and call the model anyway, then compare the fresh answer with the cached one. This is the same idea as the shadow-mode checks in evaluating AI agents, and it's the only way to measure your actual false-hit rate rather than guess it.

Where does semantic caching fit with the other LLM cost levers?

It's one lever among several, and it works best alongside the others rather than instead of them. A typical request path runs through a semantic cache first, then a model router or cascade on a miss to pick the cheapest model that can answer, then provider-side prompt caching on whatever reaches the model. Each layer catches traffic the others miss. If you already run an AI gateway, that's the natural place for the semantic cache, because every request already passes through it. The broader picture of where LLM spend goes and which lever to pull first is in LLM cost optimization for production apps. Under the hood a semantic cache is a small, specialised vector search problem, so if you're choosing the index, vector databases explained covers the same trade-offs.

If you want a semantic cache designed for your own traffic, with the right scoping, a threshold backed by labelled data and the sampling that proves it isn't serving wrong answers, my DevOps and cloud consulting services cover exactly this.

Frequently Asked Questions

Semantic caching stores LLM responses keyed by the meaning of the query instead of its exact text. When a new query is close enough in embedding space to one already answered, the stored response is returned and the model is never called, which saves the full cost and latency of that request.

Prompt caching is a provider-side optimisation that reuses the computed state for an identical prompt prefix. The model still runs and generates a fresh answer, just more cheaply. Semantic caching sits in your application and skips the model entirely on a hit, returning a previously stored answer for a similar query.

Yes, and that's its main risk. If two queries are close in embedding space but need different answers, such as cancelling an order versus cancelling a subscription, a loose threshold returns one query's answer for the other. No error is raised, so false hits have to be measured deliberately.

There's no universal value. It depends on your embedding model, your domain and the cost of a wrong answer. RedisVL uses cosine distance from 0 to 2, where lower is stricter. Start strict, label real near-miss query pairs from your own traffic, and loosen only as far as the measured false-hit rate allows.

RedisVL's SemanticCache, imported from redisvl.extensions.cache.llm, stores prompts and responses with store() and looks them up with check(). It supports a distance_threshold, a TTL, and filterable fields such as tenant or version tags for scoping lookups. Its documented TTL default is None, meaning entries never expire unless you set one.

Because cached LLM answers don't update when the facts behind them change. Product details, policies and documentation move on while the cached response stays as it was. A TTL is the backstop that guarantees stale answers eventually expire even if explicit invalidation is missed.

Scope every entry and every lookup by tenant, using filter fields or separate cache namespaces, so a query only matches entries created in the same context. Without scoping, one customer's query can be answered with a response generated for another customer.

Personalised answers built from a user's own data, time-sensitive answers such as status or pricing, follow-ups that depend on earlier conversation, anything that executes an action or tool call, and high-stakes medical, legal, financial or security guidance where a plausible wrong answer is costly.

They keep reflecting the old prompt until they expire. Including the prompt version and model in the cache scope fixes this cleanly. Bump the version and old entries can no longer match, with no manual cache flush needed.

It depends heavily on your traffic. The MeanCache paper reports that repeated queries made up about 31% of queries in its analysis, which is a useful order of magnitude, but a support bot answering FAQs and a coding assistant will repeat themselves at very different rates. Measure your own traffic before planning around a number.

GPTCache is an open-source library from Zilliz for building semantic caches for LLM queries. Its architecture separates an LLM adapter, embedding generator, cache storage, vector store, cache manager for eviction, and a similarity evaluator that decides whether a candidate counts as a match.

Log every lookup with its outcome and distance score, and watch for hits clustered near the threshold. Then sample a small share of cache hits, call the model anyway, and compare the fresh answer with the cached one. That gives you a measured false-hit rate instead of a guess.

Not by embedding the follow-up alone. A query like "what about the second one?" is meaningless without its context, and the MeanCache paper identifies contextual queries as a source of false hits in existing caches. Cache only standalone queries, or include the relevant conversation context in what you embed.

In front of everything else, often inside an AI gateway. A request checks the semantic cache first, then on a miss goes through model routing or cascading to pick the cheapest suitable model, and provider-side prompt caching reduces the cost of whatever reaches the model.

No. It pays off where many users ask genuinely repetitive questions whose answers are the same for everyone and change slowly, such as support FAQs and documentation lookups. For highly personalised, conversational or action-taking applications, the hit rate is low and the false-hit risk outweighs the saving.