AI

Semantic Caching for LLMs: Cut Cost and Latency

Semantic caching reuses LLM answers for questions that mean the same thing. How it works, real benchmark numbers, code, thresholds and the risks to avoid.

By OmniAI Editorial · Nov 22, 2026 · 12 min read

Semantic caching stores the answers a language model has already given and reuses them when a new question means the same thing, even if it is worded differently. "How do I reset my password?" and "I forgot my password, how can I change it?" are different strings but the same request. A semantic cache turns each question into an embedding (a vector that captures meaning), searches for a close enough earlier question, and returns its stored answer in milliseconds instead of calling the model again.

Done well, it cuts both cost and response time for apps with many repeated questions, such as support bots, FAQ assistants and internal help desks. Done badly, it returns the wrong answer to a question that only looked similar, or leaks one user's answer to another. This guide covers how semantic caching works, how it differs from prompt caching, what real benchmarks show, how to implement it with working code, how to choose a threshold, and the failure modes to design against.

What Is Semantic Caching in LLM Apps?

In LLM apps, semantic caching is a layer between your application and the model. For each incoming request it asks one question: have we already answered something that means the same? If yes, it returns the cached answer. If no, it calls the model, returns the answer and stores the new question-and-answer pair for next time.

The difference from an ordinary cache is the matching rule:

  • An exact-match cache returns a stored answer only when the request text, after light normalisation, is identical. It is safe, but it rarely hits for natural language, because people phrase things in many ways.
  • A semantic cache compares meaning. It uses embeddings and vector similarity, so paraphrases, typos and reordered words can still hit.

That flexibility is the point and the danger. A semantic cache will hit more often than an exact cache. It will also sometimes treat two questions as the same when they aren't.

How Semantic Caching Works

A light speech bubble, an ink arrow to a small light box with grey bars, an ink arrow to a grey cylinder, which splits into an ink arrow up to an orange document and an ink arrow down to a grey chip.
A query is embedded and compared with stored queries; close matches return the cached answer, misses go to the model.

Every semantic cache follows the same loop:

  1. Embed the query. An embedding model turns the incoming question into a vector. Our guide to embeddings explains how these vectors capture meaning.
  2. Search the cache. A vector index finds the stored question whose embedding is closest, usually by cosine similarity.
  3. Apply the threshold. If the similarity is above your threshold (or the distance below it), it's a hit.
  4. Hit: return the stored answer. No model call. The response arrives in milliseconds.
  5. Miss: call the model. Generate the answer as usual.
  6. Store the pair. Save the question, its embedding, the answer and any metadata, with an expiry time (TTL).

The cache usually lives in a vector-capable store: Redis with vector search, a dedicated vector database, or an in-memory index for small apps. Managed options also exist. Redis offers a managed semantic cache service, and Azure API Management has a built-in semantic cache lookup policy with a configurable score threshold.

Semantic Caching vs Prompt Caching

The two are often confused because both "cache" LLM work. Semantic caching vs prompt caching comes down to what is reused:

Semantic cachingPrompt cachingExact-match response cachingKV cache
What is reusedThe final answerThe model's processing of a repeated prompt prefixThe final answerAttention keys and values for earlier tokens
Where it runsYour app or gatewayThe model provider or inference serverYour app or gatewayInside the model during generation
Match ruleSimilar meaningIdentical prefix, token for tokenIdentical textSame sequence
SavesThe entire model callPart of the input cost and time to first tokenThe entire model callRecomputing past tokens
OutputOld answer, reusedNew answer, generated freshOld answer, reusedNew answer
Risk of a wrong answerYes, on false hitsNoLowNo
Best forRepeated user questionsLong system prompts, documents, tool definitionsIdentical API callsEvery generation

The two combine well. Prompt caching makes every miss cheaper, and semantic caching avoids some calls entirely. See our guide to prompt caching for how the provider-side version works.

What Real Benchmarks Show

The best public data comes from AWS. It tested a semantic cache on 63,796 real chatbot queries and their paraphrases from the public SemBenchmarkLmArena dataset. It used Amazon Titan Text Embeddings V2 for embeddings and Claude 3 Haiku for answers, starting with an empty cache:

Similarity thresholdCache hit ratioAccuracy of cached answersDaily costCost savingAverage latencyLatency reduction
No cachen/an/a$49.50n/a4.35 sn/a
0.99 (very strict)23.5%92.1%$41.7015.8%3.60 s17.1%
0.95 (strict)56.0%92.6%$23.8051.9%1.84 s57.7%
0.90 (moderate)74.5%92.3%$13.6072.5%1.21 s72.2%
0.80 (balanced)87.6%91.8%$7.6084.6%0.60 s86.1%
0.75 (relaxed)90.3%91.2%$6.8086.3%0.51 s88.3%
0.50 (very relaxed)94.3%87.5%$5.9088.0%0.46 s89.3%

Source: Amazon ElastiCache documentation, "Impact and benchmarks".

Three lessons:

  • Hit rates depend on your traffic. This dataset was built with paraphrases, so it repeats more than many real apps. A support bot with a narrow topic can get close to this; an open-ended assistant usually won't.
  • Accuracy drops as the threshold loosens. Moving from 0.90 to 0.50 bought a few more points of hit rate and cost a drop from 92.3% to 87.5% in answer accuracy.
  • Latency gains are large. A hit is a vector lookup, not a generation, so average latency fell from over 4 seconds to under a second at moderate thresholds.

The savings are bigger with expensive models and smaller with cheap ones, because embedding and lookup costs stay roughly the same.

How to Implement Semantic Caching

Here's how to implement semantic caching with RedisVL, the Redis Python library, following its documented API. First create the cache with an embedding model and a distance threshold:

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

llmcache = SemanticCache(
    name="llmcache",
    redis_url="redis://localhost:6379",
    distance_threshold=0.1,   # cosine distance; lower is stricter
    vectorizer=HFTextVectorizer("redis/langcache-embed-v2"),
)

Then wrap your model call. Check the cache first, and on a miss call the model and store the result:

def answer(question: str) -> str:
    if hit := llmcache.check(prompt=question):
        return hit[0]["response"]
    response = call_llm(question)          # your existing model call
    llmcache.store(prompt=question, response=response)
    return response

A few production settings matter as much as the code:

  • TTL. Set an expiry with llmcache.set_ttl(seconds) so answers about prices, stock or policies don't live forever.
  • Per-user or per-tenant scope. If answers depend on who is asking, store a user or tenant field and filter on it, so one customer never receives another's cached answer. RedisVL supports this with filterable_fields and a filter_expression on check.
  • Separate caches per prompt version. If you change the system prompt or the model, the old answers may no longer be right. Use a new cache name or clear the old one.

Other libraries follow the same pattern: GPTCache (an open-source semantic cache that plugs into LangChain and LlamaIndex), managed caches from Redis, and gateway-level caches such as Azure API Management's semantic cache policy.

Choosing a Threshold

A grey panel with an ink dot at the centre inside a small dotted ink circle and a larger dotted ink circle, light dots scattered around, and one orange dot between the two circles.
A strict threshold reuses only near-identical questions; a loose one reuses more but returns more wrong answers.

The threshold decides everything, and it's specific to your embedding model and your traffic.

Similarity vs distance. Some tools use cosine similarity (1.0 means identical, higher is stricter). Others use cosine distance (0 means identical, lower is stricter). RedisVL's distance_threshold=0.1 is roughly a similarity of 0.9. Read your tool's docs before copying a number from someone else.

How to pick one:

  1. Collect real queries from your logs, or write a few hundred that match your use case.
  2. Label pairs: true paraphrases that should share an answer, and near-misses that must not ("cancel my order" vs "don't cancel my order", "refund policy for Germany" vs "refund policy for France").
  3. Sweep thresholds and measure, for each one, the hit rate and the share of hits that were correct (precision).
  4. Pick the loosest threshold whose precision you can live with, given what a wrong answer costs. A wrong answer to "what are your opening hours?" is cheap. A wrong answer about medication or account balances is not.
  5. Re-check after changing the embedding model, because similarity scores shift between models.

Start strict and loosen gradually while monitoring complaints and quality.

A Worked Cost Example

Take a support assistant handling 100,000 questions a day, where each model call costs an average of $0.01, and assume each embedding costs $0.00002.

  • No cache: 100,000 × $0.01 = $1,000 a day.
  • With a semantic cache at a 40% hit rate: 60,000 model calls × $0.01 = $600, plus 100,000 embeddings × $0.00002 = $2. That's about $602 a day plus the cache store's running cost, a saving of roughly 40%.
  • At a 70% hit rate: 30,000 × $0.01 + $2 = $302 a day, about a 70% saving.

These are illustrative figures. Plug in your own model price, embedding price and measured hit rate. The pattern holds: savings track the hit rate almost one-for-one, and embedding costs are small next to generation. For more ways to cut model spend, see our guide to reducing LLM costs.

Risks and Failure Modes

  • False hits. Two questions with similar wording but different meaning get the same answer. Negations, numbers, names and places are the usual culprits. Thresholds alone don't fix this; test on hard examples and consider a cheap verification step, such as a small model that checks whether the cached answer fits the new question, for high-stakes answers.
  • Context loss. Follow-up questions like "and how much does that cost?" depend on earlier turns. Caching them on the text alone returns answers about the wrong thing. Either skip the cache for follow-ups, or include a summary of the context in what you embed. The MeanCache research paper reports that existing caches can't handle contextual queries well and produce high false hit and miss rates.
  • Personal data leaks. If answers include user-specific data, a shared cache can serve one user's account details to another. Scope entries by user or tenant, or don't cache personalised answers at all.
  • Stale answers. Cached answers about prices, stock or rules go out of date. Use TTLs and invalidate entries when source data changes.
  • Semantic cache poisoning. If an attacker can get a harmful or misleading answer stored, for example through a prompt that makes the model produce bad output, the cache serves it to everyone who asks something similar. Semantic cache poisoning is the cached cousin of prompt injection. Defend against it by caching only answers that passed your output checks, scoping caches, limiting what anonymous users can write, and being able to purge entries quickly.
  • Non-determinism hidden. A cached answer is frozen. If your app relies on varied outputs (brainstorming, creative writing), caching makes it repetitive.

When to Use It and When Not To

Good fits:

  • Customer support and FAQ bots with many repeated questions.
  • Internal help desks for HR, IT and policy questions.
  • Documentation assistants where answers don't depend on the user.
  • Classification or extraction calls with repeated inputs.

Poor fits:

  • Personalised answers that depend on account data.
  • Agents that take actions or call tools: you don't want to replay an old action.
  • Time-sensitive answers such as prices, inventory or news, unless TTLs are very short.
  • Creative tasks where users expect fresh output.

FAQ

Does semantic caching reduce quality?

It can. Every cache hit returns an answer written for a slightly different question. With a strict threshold and good testing, the drop is small. In the AWS benchmark, cached answer accuracy stayed above 91% down to a 0.75 threshold.

What embedding model should I use for a semantic cache?

Use a fast, inexpensive model that's good at matching short questions, and evaluate it on your own query pairs. Some providers publish embedding models tuned for caching, such as Redis's LangCache embedding models.

Is semantic caching the same as RAG?

No. RAG retrieves documents to help the model write a new answer. Semantic caching retrieves a previous answer to skip the model entirely. Both use embeddings and vector search, which is why they're often built on the same database.

How long should cached answers live?

As long as the answer stays true. Static policy answers can live for days or weeks; anything tied to prices, stock or changing data should expire in minutes or hours, or be invalidated when the data changes.

Can I use semantic caching with streaming responses?

Yes. On a hit, you can return the cached text at once or stream it out in chunks so the interface behaves the same. On a miss, stream from the model and store the full answer after it finishes.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog