# Semantic caching for RAG: how the similarity threshold trades cost against wrong answers

A semantic cache returns a stored answer when a new question looks similar enough to an old one, skipping retrieval and the LLM call. The single number that decides whether it saves money or embarrasses you is the similarity threshold. Here you set it on thirty real-looking question pairs.

<div data-sim="specx" data-spec="{&#34;head&#34;:&#34;A semantic cache in front of RAG: similarity threshold against cost and wrong answers&#34;,&#34;sub&#34;:&#34;Thirty incoming questions, the cosine similarity to the closest cached question, and whether the cached answer is right for them. Move the threshold and see hit rate, wrong answers and cost per answer change.&#34;,&#34;params&#34;:[{&#34;id&#34;:&#34;thr&#34;,&#34;label&#34;:&#34;Similarity threshold&#34;,&#34;min&#34;:0.7,&#34;max&#34;:0.99,&#34;step&#34;:0.01,&#34;value&#34;:0.9,&#34;note&#34;:&#34;Serve the cached answer when cosine similarity is at least this; RedisVL&#39;s default distance 0.1 equals 0.90&#34;},{&#34;id&#34;:&#34;c_llm&#34;,&#34;label&#34;:&#34;Cost of a fresh RAG answer&#34;,&#34;min&#34;:0.1,&#34;max&#34;:5,&#34;step&#34;:0.05,&#34;value&#34;:1.65,&#34;unit&#34;:&#34;¢&#34;,&#34;note&#34;:&#34;Retrieval plus the LLM call, e.g. 4,000 input and 300 output tokens&#34;},{&#34;id&#34;:&#34;c_look&#34;,&#34;label&#34;:&#34;Cost of the cache lookup&#34;,&#34;min&#34;:0,&#34;max&#34;:0.2,&#34;step&#34;:0.005,&#34;value&#34;:0.01,&#34;unit&#34;:&#34;¢&#34;,&#34;note&#34;:&#34;Embedding the question plus one vector search, paid on every query&#34;},{&#34;id&#34;:&#34;c_wrong&#34;,&#34;label&#34;:&#34;Cost of a wrong cached answer&#34;,&#34;min&#34;:0,&#34;max&#34;:50,&#34;step&#34;:0.5,&#34;value&#34;:2,&#34;unit&#34;:&#34;¢&#34;,&#34;note&#34;:&#34;What a wrong answer costs you: a support ticket, a retry, lost trust&#34;}],&#34;data&#34;:{&#34;columns&#34;:[&#34;q&#34;,&#34;sim&#34;,&#34;same&#34;],&#34;rows&#34;:[[1,0.972,1],[2,0.834,0],[3,0.917,1],[4,0.642,0],[5,0.948,0],[6,0.883,1],[7,0.791,0],[8,0.936,1],[9,0.857,0],[10,0.713,0],[11,0.904,1],[12,0.812,1],[13,0.921,0],[14,0.958,1],[15,0.738,0],[16,0.893,0],[17,0.846,1],[18,0.927,1],[19,0.684,0],[20,0.866,0],[21,0.909,1],[22,0.776,1],[23,0.902,0],[24,0.851,0],[25,0.953,1],[26,0.761,0],[27,0.864,1],[28,0.823,0],[29,0.887,1],[30,0.805,0]],&#34;note&#34;:&#34;Modelled on Quora Question Pairs: sim is the cosine similarity of a new question to its nearest cached question, same is 1 when they ask the same thing (the cached answer fits). Paste pairs from your own cache logs.&#34;},&#34;row&#34;:[{&#34;id&#34;:&#34;hit&#34;,&#34;label&#34;:&#34;served from cache&#34;,&#34;expr&#34;:&#34;ge(sim, thr)&#34;,&#34;fmt&#34;:&#34;i&#34;,&#34;tex&#34;:&#34;\\text{hit}_i = [\\cos(\\mathbf{e}_i, \\mathbf{e}_{\\text{nearest}}) \\ge \\tau]&#34;},{&#34;id&#34;:&#34;good&#34;,&#34;label&#34;:&#34;correct hit&#34;,&#34;expr&#34;:&#34;hit*same&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;wrong&#34;,&#34;label&#34;:&#34;wrong hit&#34;,&#34;expr&#34;:&#34;hit*(1 - same)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;missed&#34;,&#34;label&#34;:&#34;missed reuse&#34;,&#34;expr&#34;:&#34;(1 - hit)*same&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;cost&#34;,&#34;label&#34;:&#34;cost of this answer (¢)&#34;,&#34;expr&#34;:&#34;c_look + (1 - hit)*c_llm + hit*(1 - same)*c_wrong&#34;,&#34;tex&#34;:&#34;c_i = c_{\\text{look}} + (1-\\text{hit}_i)\\,c_{\\text{LLM}} + \\text{hit}_i(1-\\text{same}_i)\\,c_{\\text{wrong}}&#34;}],&#34;derived&#34;:[{&#34;id&#34;:&#34;hits&#34;,&#34;label&#34;:&#34;Cache hits&#34;,&#34;expr&#34;:&#34;sum(hit)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;hitrate&#34;,&#34;label&#34;:&#34;Hit ratio&#34;,&#34;expr&#34;:&#34;mean(hit)&#34;,&#34;fmt&#34;:&#34;p&#34;,&#34;tex&#34;:&#34;\\text{hit ratio} = \\frac{\\#\\text{hits}}{\\#\\text{queries}}&#34;},{&#34;id&#34;:&#34;nwrong&#34;,&#34;label&#34;:&#34;Wrong answers served&#34;,&#34;expr&#34;:&#34;sum(wrong)&#34;,&#34;fmt&#34;:&#34;i&#34;},{&#34;id&#34;:&#34;prec&#34;,&#34;label&#34;:&#34;Precision of hits&#34;,&#34;expr&#34;:&#34;sum(good)/max(hits, 1)&#34;,&#34;fmt&#34;:&#34;p&#34;,&#34;tex&#34;:&#34;\\text{precision} = \\frac{\\#\\text{correct hits}}{\\#\\text{hits}}&#34;},{&#34;id&#34;:&#34;recall&#34;,&#34;label&#34;:&#34;Recall of reusable questions&#34;,&#34;expr&#34;:&#34;sum(good)/max(sum(same), 1)&#34;,&#34;fmt&#34;:&#34;p&#34;,&#34;tex&#34;:&#34;\\text{recall} = \\frac{\\#\\text{correct hits}}{\\#\\text{queries the cache should serve}}&#34;},{&#34;id&#34;:&#34;cpa&#34;,&#34;label&#34;:&#34;Cost per answer (¢)&#34;,&#34;expr&#34;:&#34;mean(cost)&#34;,&#34;tex&#34;:&#34;\\bar c = \\frac{1}{n}\\sum_i c_i&#34;},{&#34;id&#34;:&#34;llm_only&#34;,&#34;label&#34;:&#34;Cost per answer without a cache (¢)&#34;,&#34;expr&#34;:&#34;c_llm&#34;},{&#34;id&#34;:&#34;saving&#34;,&#34;label&#34;:&#34;Saving against no cache&#34;,&#34;expr&#34;:&#34;1 - cpa/c_llm&#34;,&#34;fmt&#34;:&#34;p&#34;},{&#34;id&#34;:&#34;bestcase&#34;,&#34;label&#34;:&#34;Cost if the cache were perfect (¢)&#34;,&#34;expr&#34;:&#34;c_look + (1 - mean(same))*c_llm&#34;,&#34;note&#34;:&#34;every reusable question served, nothing wrong&#34;}],&#34;chart&#34;:{&#34;title&#34;:&#34;Which questions the cache answers at this threshold&#34;,&#34;x&#34;:{&#34;var&#34;:&#34;t&#34;,&#34;label&#34;:&#34;Cosine similarity to the nearest cached question&#34;,&#34;from&#34;:0.6,&#34;to&#34;:1},&#34;y&#34;:{&#34;from&#34;:-0.05,&#34;to&#34;:1.05},&#34;series&#34;:[{&#34;label&#34;:&#34;Decision: 1 = serve cached answer&#34;,&#34;expr&#34;:&#34;ge(t, thr)&#34;}],&#34;points&#34;:{&#34;x&#34;:&#34;sim&#34;,&#34;y&#34;:&#34;same&#34;,&#34;label&#34;:&#34;Question (1 = cached answer fits, 0 = it does not)&#34;},&#34;fit&#34;:{&#34;x&#34;:&#34;sim&#34;,&#34;y&#34;:&#34;wrong&#34;,&#34;label&#34;:&#34;Wrong answers served (at 1)&#34;},&#34;mark&#34;:&#34;thr&#34;},&#34;level&#34;:&#34;intermediate&#34;,&#34;bars&#34;:{&#34;title&#34;:&#34;Cost of each answer (¢): misses pay the LLM, wrong hits pay the penalty&#34;,&#34;y&#34;:&#34;cost&#34;,&#34;label&#34;:&#34;q&#34;},&#34;steps&#34;:[{&#34;title&#34;:&#34;Embed and look up&#34;,&#34;text&#34;:&#34;Every new question is embedded and the nearest cached question is found by cosine similarity. This costs {c_look} ¢ per query, hit or miss.&#34;},{&#34;title&#34;:&#34;Apply the threshold&#34;,&#34;text&#34;:&#34;At a threshold of {thr}, {hits} questions are served from the cache: a hit ratio of {hitrate:p}.&#34;,&#34;show&#34;:[&#34;hits&#34;,&#34;hitrate&#34;]},{&#34;title&#34;:&#34;Check the hits&#34;,&#34;text&#34;:&#34;Similar is not the same. {nwrong} hits returned an answer to a different question, so the precision of the hits is {prec:p}.&#34;,&#34;show&#34;:[&#34;nwrong&#34;,&#34;prec&#34;]},{&#34;title&#34;:&#34;Check the misses&#34;,&#34;text&#34;:&#34;Of the questions the cache could have answered, {recall:p} were served; the rest paid for a fresh RAG answer at {c_llm} ¢.&#34;,&#34;show&#34;:[&#34;recall&#34;]},{&#34;title&#34;:&#34;Price it&#34;,&#34;text&#34;:&#34;With {c_wrong} ¢ charged for each wrong answer, the mean cost per answer is {cpa} ¢ against {llm_only} ¢ with no cache: a saving of {saving:p}. A perfect cache would cost {bestcase} ¢.&#34;,&#34;show&#34;:[&#34;cpa&#34;,&#34;saving&#34;,&#34;bestcase&#34;]}]}"><p>Interactive simulation. It needs JavaScript; the text below explains what it shows.</p></div>

## What you are looking at

Each row is a question arriving at a RAG chatbot. Before running retrieval and the LLM, the system embeds the question and looks up the closest question already in the cache. The column sim is the cosine similarity between the two; the column same says whether they really ask the same thing, so that the cached answer is right (1) or wrong (0). The pairs are modelled on the Quora Question Pairs data, where over 400,000 question pairs are labelled as duplicates or not, which is the standard way to test whether "similar" means "the same question".

On the chart every dot is a question placed at its similarity, at the top if the cached answer fits and at the bottom if it does not. The step line is the cache's decision: everything right of the threshold is served from the cache. The markers at 1 show the wrong answers that were served. The bars show what each answer cost: a miss pays for a fresh RAG answer, a wrong hit pays the penalty you set, and a correct hit costs only the lookup.

## The algorithm

1. **Embed and search.** The question is turned into a vector and the nearest cached question is found, usually in the same kind of vector index the RAG retriever uses. Every query pays for this, hit or miss.
2. **Threshold.** If the cosine similarity is at least τ the cached answer is returned. GPTCache expresses this as a similarity threshold between 0 and 1 (its Config default is 0.8); RedisVL's SemanticCache uses a cosine distance threshold between 0 and 2 with a default of 0.1, which is the same as a similarity of at least 0.90.
3. **Count the outcomes.** A hit can be correct or wrong (a false positive); a miss can be necessary or a missed reuse (a false negative). GPTCache reports the hit ratio and the recall, the share of the queries that should have been served by the cache that actually were. Precision, the share of hits that were right, is the number that decides how often users see an answer to someone else's question.
4. **Price it.** The cost of one answer is the lookup, plus the RAG cost if it missed, plus a penalty if a wrong answer was served. The mean over all queries is compared with running every question through RAG.

### Worked example

With the defaults (τ = 0.90, a fresh answer at 1.65 ¢, a lookup at 0.01 ¢, a wrong answer charged 2 ¢) eleven of the thirty questions are served from the cache, a hit ratio of 36.7%. Eight of those are right and three are not (similarities 0.948, 0.921 and 0.902 belong to different questions), so precision is 72.7%. Fourteen questions could have been reused and eight were, a recall of 57.1%. The bill is 30 × 0.01 + 19 × 1.65 + 3 × 2 = 37.65 ¢, or 1.255 ¢ per answer, against 1.65 ¢ with no cache: a saving of 23.9%. A perfect cache would cost 0.89 ¢.

## Things to try

- Lower the threshold to 0.77. Every reusable question is now served (recall 100%) and the cost falls to 1.018 ¢, a 38.3% saving, but 11 of the 25 hits are wrong answers.
- Keep τ at 0.90 and raise the cost of a wrong answer to 10 ¢. The cache now costs 2.055 ¢ per answer, 24.5% more than having no cache at all.
- At a wrong-answer cost of 5 ¢, try 0.95: only three hits, all correct, and 1.495 ¢ per answer, cheaper than the 1.555 ¢ that 0.90 costs at the same penalty.
- Drop the RAG cost to 0.3 ¢, as for a small model with short context. Even at τ = 0.90 the cache now loses money: 0.40 ¢ against 0.30 ¢.
- Paste pairs from your own logs and look for the similarity where the dots at 0 stop: that is where your threshold belongs.

## How it works in real systems

The lesson of the simulation is that the threshold is a business decision, not a constant: the best value depends on how expensive a fresh answer is and how much a wrong one hurts. Similarity scores are also model-specific, so a threshold tuned for one embedding model does not carry over to another.

Production caches add safeguards. They scope entries with filters (user, tenant, language, document version) so that an answer about one customer's account is never returned to another; they give entries a time to live, because a cached RAG answer goes stale when the indexed documents change; and some re-check a candidate hit with a second model, as GPTCache does with an optional duplicate-question classifier, before serving it. Caching sits next to the other cost levers of a RAG system: fewer, better chunks from [hybrid search](/ai-simulations/rag-hybrid) and [reranking](/ai-simulations/rag-rerank), and provider-side [prompt caching](/ai-simulations/prompt-cache-hits-agent-session), which discounts repeated prompt prefixes but still calls the model. Measure the answers a cache serves with the same checks as fresh ones, for example [RAGAS faithfulness](/ai-simulations/ragas-rag-evaluation).

## Sources

- [GPTCache README: semantic caching, hit ratio and recall](https://github.com/zilliztech/GPTCache/blob/main/README.md)
- [GPTCache Config: similarity_threshold](https://github.com/zilliztech/GPTCache/blob/main/gptcache/config.py)
- [RedisVL SemanticCache source: distance_threshold in cosine units](https://github.com/redis/redis-vl-python/blob/main/redisvl/extensions/cache/llm/semantic.py)
- [Sentence Transformers: training on the Quora Duplicate Questions dataset](https://github.com/UKPLab/sentence-transformers/blob/master/examples/sentence_transformer/training/quora_duplicate_questions/README.md)
