Tutorial

Caching LLM Responses with Semantic Keys

Cache model answers by meaning rather than exact text, set a similarity threshold that bounds false hits, and invalidate entries when prompts or models change.

On this page

  1. Introduction
  2. Why Exact Match Caching Barely Helps
  3. Building a Semantic Cache Key
  4. Choosing the Similarity Threshold
  5. Invalidating When Prompts and Models Change
  6. Concurrency and Thundering Herds
  7. Privacy and Per-Tenant Isolation
  8. Measuring Hit Rate and Correctness
  9. When Not to Cache at All
  10. Sources

Introduction

Language model calls are slow and metered, so repeating an identical question is pure waste. An exact string cache helps only when users type byte-identical text, which is rare: real questions vary in punctuation, filler words and phrasing. A semantic cache embeds the incoming question and looks for a previous question whose embedding is close enough to reuse its answer. Done carefully this cuts cost and latency dramatically; done carelessly it serves the answer to a different question and nobody notices until a user complains.

Why Exact Match Caching Barely Helps

Exact key caches deduplicate only truly identical requests, which happens for automated retries and scripted clients but almost never for human phrasing. Typing the same question with a different article or an added please defeats the cache entirely. Semantic caching addresses that gap by comparing meaning, but it introduces a new risk: two questions can be close in embedding space while requiring different answers, especially when they differ by a negation, a number or a named entity. The whole design is therefore about bounding that risk.

import hashlib, time
import numpy as np

class SemanticCache:
    def __init__(self, embed, db, threshold=0.93, ttl=86400):
        self.embed = embed
        self.db = db
        self.threshold = threshold
        self.ttl = ttl

    def _namespace(self, tenant, model, prompt_version):
        raw = f"{tenant}|{model}|{prompt_version}".encode()
        return hashlib.sha256(raw).hexdigest()[:16]

    def get(self, tenant, model, prompt_version, question):
        ns = self._namespace(tenant, model, prompt_version)
        vec = self.embed(question)
        best = self.db.search(ns, vec, k=1)
        if not best:
            return None
        entry, score = best[0]
        if score < self.threshold:
            return None
        if time.time() - entry["created_at"] > self.ttl:
            self.db.delete(ns, entry["id"])
            return None
        return entry["answer"]

    def put(self, tenant, model, prompt_version, question, answer):
        ns = self._namespace(tenant, model, prompt_version)
        self.db.upsert(ns, {
            "id": hashlib.sha256(question.encode()).hexdigest(),
            "question": question, "embedding": self.embed(question),
            "answer": answer, "created_at": time.time(),
        })

Building a Semantic Cache Key

Embed each incoming question with the same model you use elsewhere, then search a vector index of previously answered questions. Store the question, its embedding, the answer, the model version, the prompt version and any parameters that affect the output, because reusing an answer produced under a different system prompt is unsafe. Keep the search scoped by tenant and by answer-shaping parameters so the cache can never leak one user answer to another. The key is the pair of question meaning and generation configuration, not the raw string.

lock = redis.lock("llm:{ns}:{key}", timeout=30)

def answer_with_cache(cache, tenant, model, prompt_version, question, generate):
    hit = cache.get(tenant, model, prompt_version, question)
    if hit is not None:
        return {"answer": hit, "cached": True}
    # Single flight: only the lock holder computes; others wait briefly.
    if lock.acquire(blocking_timeout=25):
        try:
            hit = cache.get(tenant, model, prompt_version, question)
            if hit is not None:
                return {"answer": hit, "cached": True}
            out = generate(question)
            cache.put(tenant, model, prompt_version, question, out)
            return {"answer": out, "cached": False}
        finally:
            lock.release()
    return {"answer": generate(question), "cached": False}

Choosing the Similarity Threshold

The threshold is the single most important parameter. Too low and unrelated questions hit, returning confidently wrong answers; too high and the cache rarely hits, saving nothing. Calibrate it on labelled question pairs that are true paraphrases and near misses, then pick the value that keeps false hits below a tolerable rate. A conservative threshold around the high end of your paraphrase distribution usually leaves plenty of hits while avoiding the dangerous region where different questions look similar.

Invalidating When Prompts and Models Change

A cached answer is only valid for the exact instructions and model that produced it, so every cache entry must record them. When you change the system prompt, the model version or a generation parameter, either version the cache namespace or purge the affected entries, otherwise users receive answers from a prompt you no longer use. Expire entries on a time to live as well, because the underlying facts may change even when the configuration does not. Treat invalidation as part of the prompt change checklist, not an afterthought.

Concurrency and Thundering Herds

When a popular question arrives during a cache miss, many requests may compute the same answer at once. Add single flight so the first request computes and the rest await its result, and write the entry once. Under load this prevents a cold cache from multiplying cost exactly when you can least afford it. Use a short distributed lock with a timeout so a crashed worker does not block the key forever, and let waiters fall through to a direct call after the timeout.

Privacy and Per-Tenant Isolation

Semantic caches store user questions verbatim, so they inherit every obligation of the data itself. Namespace entries by tenant and enforce the same access checks on lookup that govern the underlying data, because a cache hit is still a disclosure. Exclude anything classified as sensitive from caching, honour deletion requests by removing matching entries, and encrypt the store at rest. A cache that ignores tenant boundaries turns a latency optimization into a data breach.

Measuring Hit Rate and Correctness

Track hit rate and, more importantly, the rate at which hits are wrong. Sample cached answers and compare them against freshly generated ones on a labelled set, and log the similarity score of every hit so you can audit the threshold in production. Alert when the false hit rate rises, which usually means the question distribution drifted toward near misses. A cache is only worth keeping while correctness stays within budget, so measure both sides, not just the savings.

When Not to Cache at All

Some requests must never be cached. Anything that depends on live data, the current user session or a changing market state will return a stale answer that looks authoritative, which is worse than a slow correct one. Creative tasks where variety is the point should bypass the cache entirely. Requests carrying personal data or secrets should also skip it unless the store meets the same classification as the source. Keep an opt out flag on the request so callers can force a fresh generation, and have the pipeline honour it before any lookup happens.

Sources

Sources: OpenAI prompt caching, Redis documentation, Anthropic prompt caching.

FAQ

Is a semantic cache safe for factual questions?
Only with a conservative threshold and per tenant scoping. Questions that differ by a negation or a number can be close in embedding space yet require different answers, so calibrate against labelled near misses and monitor the false hit rate.
How do I invalidate the cache after a prompt change?
Include the prompt version in the cache namespace. Bumping the version makes old entries unreachable without a destructive purge, and they expire naturally through the time to live.

Related Examples