Contextwaise
Semantic caching

Semantic caching for LLMs: when a similar question can reuse an old answer

Semantic caching stores LLM responses keyed by the meaning of the prompt instead of its exact text. Each new prompt is turned into an embedding, compared with the prompts already cached, and if one is close enough, its stored answer is returned without calling the model. It cuts cost and latency on repeated questions, but a cache hit can be the wrong answer, so the similarity threshold, what goes into the cache key and what you never cache matter more than the tool you pick.

Updated November 26, 202613 min readBy the Contextwaise team
Key takeaways
  • A semantic cache skips the LLM call when a new prompt is close enough in embedding space to one it has already answered. It saves the whole request, input and output, on every hit.
  • It is not prompt caching. Prompt caching discounts a repeated prefix inside a call that still runs; a semantic cache replaces the call. Most apps should use both: prompt caching first, because it is free of accuracy risk.
  • Embedding the question costs almost nothing: about $1 a month for 1M questions of 50 tokens on text-embedding-3-small. The real cost of a semantic cache is the wrong answers it serves.
  • Thresholds are not portable. RedisVL uses cosine distance (default 0.1, lower is stricter), LiteLLM uses similarity (0.8 in its examples, higher is stricter), and the same number means different things on different embedding models. Tune on labelled pairs from your own logs.
  • Put everything that changes the right answer into the cache key, not just the question: tenant, user for personal data, model, prompt version, locale. Never cache answers that depend on live data or on who is asking.

What semantic caching is

A normal cache returns a stored value when the key matches exactly. LLM prompts rarely match exactly: "How do I reset my password?", "password reset steps" and "I forgot my password, what now?" are three strings with one answer. A semantic cache matches on meaning instead.

  1. Embed the incoming prompt, or the part of it that carries the question, with an embedding model.
  2. Search the cache for the nearest stored prompt by vector similarity, usually cosine.
  3. Compare the score with a threshold. Close enough is a hit: return the stored response.
  4. Miss: call the LLM, return its answer, and store the prompt embedding and the response for next time.

On a hit, the app pays for one embedding and one vector lookup instead of a full model call, and answers in milliseconds instead of seconds. On a miss, it pays for both, so a cache that rarely hits makes the app slower and slightly more expensive.

Semantic caching vs prompt caching vs exact-match caching

Three different things are called LLM caching, and they stack rather than compete:

Exact-match response cacheProvider prompt cachingSemantic cache
What is reusedThe whole responseThe model's work on a repeated prompt prefixThe whole response
Matches whenThe prompt is byte-for-byte identicalThe start of the prompt is identicalThe prompt is similar in meaning
The LLM callSkippedStill runs, cached tokens billed at 5 to 10% of the input priceSkipped
Risk of a wrong answerNone, beyond stalenessNoneYes: a similar question with a different answer
Who runs itYou (Redis, a dict, a CDN)The provider (Claude, OpenAI, Gemini)You (Redis, a vector database, a gateway)
Best forDeterministic calls, retries, tool calls with the same argumentsLong fixed system prompts, tools, documentsFAQ-style questions that repeat in different words

The order to adopt them in follows the risk column. Turn on prompt caching first: it costs nothing in accuracy and it applies to every call, hit or miss. See Anthropic prompt caching for how the prefix rules work. Add an exact-match cache where calls are deterministic. Add a semantic cache last, for the traffic where the same question really does arrive in many forms.

What a semantic cache saves, with real numbers

Take a support assistant on Claude Sonnet 5.5 ($2 per million input tokens, $10 output, $0.10 cached input). It gets 1 million questions a month. Each request sends 3,000 input tokens (a 2,000-token fixed system prompt and 1,000 tokens of retrieved help articles plus the question) and gets a 300-token answer.

SetupCost per LLM callMonthly cost
No caching$0.0090$9,000
Prompt caching on the 2,000-token prefix$0.0052$5,200
Semantic cache, 20% hit rate$0.0090 on the 80% that miss$7,200
Semantic cache at 20% + prompt caching$0.0052 on the 80% that miss$4,160

Cache write fees are left out; with a warm prefix they are small. The embedding is not: it is just negligible. If each question is about 50 tokens, 1 million of them is 50 million tokens, $1 a month on OpenAI's text-embedding-3-small at $0.02 per million. The vector store is a fixed cost you can price from your provider.

Two things stand out. Prompt caching alone saves more than a semantic cache at a 20% hit rate, with no accuracy risk. And the semantic cache's savings scale with the hit rate, which you do not control: it depends on how repetitive your users are.

The number most guides skip: cost per wrong answer

Suppose 97% of hits are correct, the level the GPT Semantic Cache paper reports for its positive hits. At a 20% hit rate, that is 200,000 hits and 6,000 wrong answers a month. Without prompt caching, the semantic cache saves $9,000 − $7,200 = $1,800, so it is worth it only if a wrong answer costs you less than $1,800 / 6,000 = $0.30, in support tickets, refunds or churn. With prompt caching already on, it saves $5,200 − $4,160 = $1,040, and the break-even drops to about $0.17 per wrong answer. For an FAQ bot that is plausible. For billing, medical or legal answers it is not, and you need a much stricter threshold or no semantic cache at all.

Paste a real prompt into the token counter to get your own cost per call, then redo this table with your hit rate.

What hit rates people actually measure

Published numbers vary widely because they depend on the traffic, not the tool. What each source measured, and how much to trust it:

SourceWhat it reportsCaveat
GPT Semantic Cache (arXiv 2411.05276)Hit rates of 61.6% to 68.8% across query categories, API calls cut by up to 68.8%, positive hits over 97% correctCurated query sets; real traffic is less repetitive
Portkey, 2023About 20% hit rate at 99% accuracy for Q&A; 18% to 60% for RAG; hits only above 95% similarityAccuracy is user-rated, method not published
AWS ElastiCache docsInference cost cut by up to 86%, latency by up to 88%, in benchmarksBenchmark not described; "up to" is a best case
LogicMonitor, 2026About 5 s on a miss and 2 s on a hit, a 2.5× speedupNo hit rate or error rate reported
MeanCache (arXiv 2403.02694)About 17% higher F-score and 20% higher precision on hit-or-miss decisions than GPTCacheCompares cache designs, not end-to-end savings

Plan with 20% for open-ended assistants and measure. Higher rates come from narrow products where users ask the same few dozen things.

Choosing the similarity threshold

The threshold is the one setting that decides both the savings and the error rate. Too loose, and "cancel order 1042" returns the answer for "cancel order 1024". Too strict, and the cache almost never hits, so every request pays for the lookup and the model call. Microsoft's Cosmos DB guidance says the same: too high and the cache fills with near-duplicate entries from repeated misses, too low and it returns irrelevant responses.

The numbers mean different things in each tool

ToolSettingScaleStricter isValue in the docs
RedisVL SemanticCachedistance_thresholdCosine distance, 0 (identical) to 2Lower0.1 (default)
LiteLLM redis-semanticsimilarity_thresholdSimilarity, 0 to 1Higher0.8 (example)
LiteLLM qdrant-semanticsimilarity_thresholdSimilarity, 0 to 1Higher0.7 (example)
Azure Cosmos DBSimilarity score0 (no similarity) to 1 (exact)HigherNone: "trial and error"

Cosine distance is 1 minus cosine similarity, so RedisVL's default of 0.1 equals a similarity of 0.9, stricter than LiteLLM's 0.8 example. And a 0.9 on one embedding model is not a 0.9 on another: models spread their scores differently. Copying a threshold from a blog post, including this one, is a guess.

Tune it on your own pairs

Take a few hundred real prompts from your logs. For each, find its nearest earlier prompt, and label the pair: would the earlier answer be correct for the new question? Then sweep the threshold and pick the loosest one that keeps precision above your target.

Python
import numpy as np

def cosine(a, b):
    a, b = np.asarray(a), np.asarray(b)
    return (a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1))

def sweep(new_vecs, cached_vecs, same_answer):
    sims = cosine(new_vecs, cached_vecs)
    same = np.asarray(same_answer, dtype=bool)
    for t in np.arange(0.80, 1.00, 0.01):
        hit = sims >= t
        precision = (hit & same).sum() / max(hit.sum(), 1)
        print(f"similarity {t:.2f}  served from cache {hit.mean():6.1%}  correct {precision:6.1%}")
Threshold sweep on labelled pairs: same_answer[i] is True when the cached answer would be right

Embed the pairs with the same model the cache will use. Label the hard cases on purpose: different numbers, dates, names, negations ("can I" against "can't I"), and different units or currencies. Those are where embeddings say "similar" and the answer says "different". If no threshold gives you both a useful hit rate and the precision you need, that is a result: your traffic is not a fit for semantic caching. Research such as vCache (arXiv 2502.03771) replaces the single global threshold with per-entry decisions and a user-defined error rate, which is worth reading if one threshold cannot fit all your prompts.

What goes in the cache key, and what never goes in the cache

The embedding only captures the question. Everything else that changes the right answer has to be an exact filter next to it, or the cache will serve one context's answer in another.

  • Tenant, so one customer's answers never reach another.
  • User, for anything that reads personal data. RedisVL's own example caches "the phone number linked to my account" behind a user_id filter for this reason.
  • Model and prompt version: a new system prompt or model should start a fresh cache, not inherit the old answers.
  • Locale and language, and any setting that changes the answer, such as plan tier or region.
  • Conversation context: "What is the second largest?" means nothing alone. Microsoft's guidance is to key on part of the chat history, not just the last message; the simpler fix is to rewrite follow-ups into standalone questions before you embed them, or to cache first turns only.

Some answers should not be cached at all: anything that depends on live data (order status, stock, prices, today's date), on tool calls that change state, or on who is asking in a way your key does not capture. Route those around the cache with an explicit rule rather than hoping the threshold will catch them.

Expiry: watch the TTL refresh

Give every entry a TTL that matches how fast its source changes. Check one default: RedisVL refreshes an entry's TTL each time it is hit (refresh_ttl_on_hit=True). That keeps popular answers warm, but it also means the most-asked answer can live forever after the facts change. For anything that goes stale, pass refresh_ttl=False to check(), and clear the cache when the source documents change.

A semantic cache in Python with RedisVL

This wraps an LLM call with RedisVL's SemanticCache, scoped by tenant and prompt version, with a TTL that does not refresh on hits. call_llm is your existing model call.

Python
from redisvl.extensions.cache.llm import SemanticCache
from redisvl.utils.vectorize import HFTextVectorizer
from redisvl.query.filter import Tag

PROMPT_VERSION = "support-v7"  # bump when the system prompt or model changes

cache = SemanticCache(
    name="support_answers",
    vectorizer=HFTextVectorizer("redis/langcache-embed-v2"),
    distance_threshold=0.1,  # cosine distance: 0.1 = similarity 0.9; tune on your pairs
    ttl=24 * 3600,           # seconds
    filterable_fields=[{"name": "scope", "type": "tag"}],
)

def answer(question: str, tenant: str, cacheable: bool) -> str:
    if not cacheable:  # personal data, live data, state-changing tools
        return call_llm(question)
    scope = f"{tenant}:{PROMPT_VERSION}"
    hits = cache.check(prompt=question, filter_expression=Tag("scope") == scope, refresh_ttl=False)
    if hits:
        return hits[0]["response"]
    reply = call_llm(question)
    cache.store(prompt=question, response=reply, filters={"scope": scope})
    return reply
pip install redisvl; needs a Redis server with the search module (Redis Stack or Redis 8)

Log every hit with the cached prompt it matched. Sampling those pairs each week is how you find false positives in production, and it gives you fresh labelled pairs for the threshold sweep.

Semantic caching tools compared

ToolWhat it isNotes
RedisVLPython library: SemanticCache on RedisFilters, TTL, distance threshold; you run Redis
Redis LangCacheManaged semantic caching service on Redis Cloud, or self-managedIn preview
LiteLLMLLM gateway with redis-semantic, valkey-semantic and qdrant-semantic cachesCaching at the proxy, no app code; threshold is a similarity
GPTCacheOpen-source semantic cache, LangChain and LlamaIndex integrationsMaintainers no longer add new APIs or models; API may change
AWS ElastiCacheManaged Valkey/Redis with vector searchAWS-native option
Azure Cosmos DBVector search in Cosmos DB, used as a semantic cacheAzure-native option

The tool matters less than the threshold and the key. Pick the one that runs where your data already lives.

Caching in AI agents

Agents are where semantic caching is most often misapplied. Each step of an agent loop sends the whole history so far: the task, every tool call and every tool result. No two of those prompts mean the same thing, so a semantic cache on the full prompt almost never hits, and when it does, it is dangerous. What works instead, by layer:

  • Entry point: a semantic cache on the user's first, standalone request, if the same tasks repeat.
  • Every step: provider prompt caching on the fixed prefix (system prompt and tool definitions), which is identical on every step.
  • Tool calls: an exact-match cache for deterministic tools called with the same arguments, such as reading the same file twice in one run.
  • The growing history: shrink it. Tool output and old turns are most of an agent's tokens, and they change on every step, so no cache helps. See agent context optimization.

A semantic caching checklist

  1. Turn on provider prompt caching first and measure what it saves.
  2. Estimate your repeat rate: embed a week of first-turn questions and count near-duplicates.
  3. Compute your break-even: savings per month divided by expected wrong answers per month. If a wrong answer costs more, stop here.
  4. Label a few hundred pairs, including hard negatives, and sweep the threshold with your embedding model.
  5. Scope the cache key by tenant, user where needed, model and prompt version; route live and personal data around the cache.
  6. Set TTLs per source, turn off TTL refresh on hits for anything that goes stale, and clear on content updates.
  7. Log hits with their matched prompt, review a sample every week, and re-tune.

Frequently asked questions

What is semantic caching?

Semantic caching stores LLM responses keyed by the meaning of the prompt. A new prompt is embedded and compared with cached prompts; if one is similar enough, its stored answer is returned instead of calling the model. It saves cost and latency on questions that repeat in different words.

What is the difference between semantic caching and prompt caching?

Prompt caching is done by the provider: a repeated prompt prefix is billed at 5 to 10% of the input price, but the model still runs and answers fresh. Semantic caching is done by you: a similar prompt skips the model and gets a stored answer. Prompt caching has no accuracy risk; semantic caching can return a wrong answer. Use both.

What similarity threshold should I use for a semantic cache?

There is no universal value. RedisVL defaults to a cosine distance of 0.1 (similarity 0.9), LiteLLM's examples use a similarity of 0.8, and scores differ between embedding models. Label a few hundred pairs from your own logs and pick the loosest threshold that keeps precision above your target.

What is caching in AI agents?

Agents use several caches at once: provider prompt caching for the fixed system prompt and tool definitions on every step, an exact-match cache for deterministic tool calls with the same arguments, and sometimes a semantic cache for the user's first request. A semantic cache on full agent prompts rarely hits, because each step carries a different history.

Is Redis a semantic cache?

Redis is a database that can act as one. With vector search, the RedisVL library provides a SemanticCache class, and Redis LangCache is a managed semantic caching service, currently in preview. LiteLLM and other gateways can also use Redis as their semantic cache backend.

How much does semantic caching save?

It depends on how often your users repeat themselves. Published hit rates range from about 20% for open Q&A to over 60% on curated query sets. Each hit saves one full LLM call; embedding the question costs about $0.02 per million tokens on text-embedding-3-small. Measure your own repeat rate before building.

What are the risks of semantic caching?

False positives: two questions that look alike but need different answers, such as different order numbers, dates or a negation. Stale answers after facts change. Leaking one user's or tenant's answer to another if the cache key does not include them. And extra latency on every miss, for the embedding and the lookup.

Keep reading

Cut your LLM costs
without cutting quality.

One layer between retrieval and inference removes the context your model never needed, in milliseconds. Fewer input tokens, lower cost, a prompt cache that keeps hitting, and every removal logged with its reason.

See it live
Keep your model, retriever and prompts. Remove one call to roll back.