Semantic Cache: 10x Faster AI Responses

📘 Tutorials 2026-07-19 · Updated 2026-11-28 3 min read

Semantic caching maps differently worded but equivalent questions to the same answer, absorbing most repeat traffic. Here is how to set the threshold, wire the code, when not to use it, and how to contain wrong hits.

📜 Table of Contents

📖 Keep reading

Semantic Caching for LLM Apps: Faster Answers, Lower Bills (2026)

In support chat, most questions repeat: returns policy, payment methods, shipping times. Running the full LLM call every time is slow and expensive when the answer already exists. Exact-match caches break the moment a user rephrases. Semantic caching matches by vector similarity, so "how long until my refund lands" and "when will the money come back" hit the same entry.

How it works

  1. Embed the question
  2. Find the nearest cached question and compute cosine similarity
  3. Above the threshold, return the cached answer; otherwise call the model and store the new pair

Everything hinges on the threshold. Too high and the hit rate is worthless; too low and different questions collide.

Setting the threshold

Threshold Hit rate Wrong-hit risk Use for
0.95+ Low Very low Policy, pricing, legal
~0.90 Medium Low General support
~0.85 Higher Medium High-repetition, short answers
Below 0.80 High High Not recommended

Determine it empirically: take 100 real questions, pair them, label whether one answer fits both, and find where confusion starts. Score distributions differ per embedding model, so borrowed thresholds do not transfer.

A minimal working prototype

from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("BAAI/bge-small-zh-v1.5")

def embed(text):
    return model.encode(text, normalize_embeddings=True)

def lookup(rows, vec, threshold=0.90):
    best, best_score = None, 0.0
    for q, v, ans in rows:
        s = float(np.dot(vec, v))
        if s > best_score:
            best, best_score = (q, ans), s
    return best if best_score >= threshold else None

Linear scan is fine to a few thousand entries. Beyond that, use a vector index, or a production component: Redis Stack with RediSearch vector indexes (TTL included), GPTCache, or semantic caching built into a gateway such as LiteLLM.

Three things beyond similarity

  1. Context fingerprint - the same question differs by tenant, language and product version. The key must include them or you leak answers across customers
  2. Log the hit - store similarity plus the original question; it is the only trail when a wrong answer ships
  3. Invalidate deliberately - tag entries by topic so a pricing or policy change clears the right subset at once

When not to use it

Rule of thumb: if the answer could live in a help center, it can be cached. If it requires a database lookup, it cannot.

Measuring it

Track hit rate, wrong-hit rate (sample 100 hits and read them), P95 latency, and cost per 1k requests. Typical outcomes: 40-60% hit rate, 30-50% cost reduction, an order of magnitude faster on hits - but measure on your own week of traffic.

FAQ

Combine with exact caching? Yes. Exact match first, semantic second. Stacking raises the hit rate.

Hit rate too low at a safe threshold? Use a stronger embedding model, or normalize questions (strip "hi", "thanks") before matching.

Do cached answers go stale? Yes. Set TTL by volatility: policy 7 days, product docs 30 days, campaigns tied to end dates.

Cache multi-turn conversations? Only single-turn standalone questions. Multi-turn answers depend on context; keying by full conversation state costs more than it saves.

Self-host or managed? High volume or compliance needs: self-host Redis. Low volume: validate the benefit with a gateway's built-in cache first.

Thresholds and savings depend on your corpus; verify on real traffic. Component configuration per official docs.

Related Articles
2026-08-14
Which AI API Should You Use in 2026? 8 Providers Compared on Price and Quality
2026-08-10
LLM Meaning Explained: What Is a Large Language Model and How It Actually Works
2026-08-01
AI Safety Red Teaming in 2026: Complete Guide with 15 Test Prompts
2026-08-02
Self-Hosted Vector Database 2026: Qdrant vs Milvus vs Chroma - Which to Run Yourself
2026-08-01
AI Model Deployment Types Explained 2026: Batch, Online, Edge, and Serverless
2026-08-06
Vespa (7,037 Stars) 2026: The Big Data Serving Engine for Vector Search, Ranking and Recommendations

Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.

💬 Comments (0)

No comments yet. Be the first!

Login to comment