Semantic Caching for LLMs: How It Works and When It Saves You Money

Semantic caching for LLMs is a way to skip a repeat API call when a new question means roughly the same thing as one you already paid to answer. Instead of matching the prompt text exactly, you convert each incoming query into an embedding vector, search an index of past queries, and reuse the stored answer when the similarity score passes a threshold you set. For apps that answer the same questions over and over, like support bots and FAQ assistants, this turns a large share of billable generation calls into millisecond cache lookups.

How Semantic Caching Works

A semantic cache sits between your app and the LLM API. Every request flows through four steps:

  • Embed the query. A small embedding model turns the prompt text into a vector. This call is far cheaper than a full completion.
  • Search past queries. The cache compares the new vector against stored vectors using cosine similarity, scored from 0 to 1.
  • Compare against a threshold. If the best match scores at or above your threshold, the cache treats it as the same question. If not, it is a miss.
  • Hit or miss. On a hit, return the stored answer immediately. On a miss, call the LLM as usual, then store the new embedding and answer for next time.

The core idea is simple: users rarely phrase the same question the same way twice. “What is your refund policy?” and “How do refunds work at your store?” are different strings with the same intent, and a semantic cache catches that.

A Minimal Lookup Flow in Python

The following example shows the lookup logic without any special dependencies. In production you would swap the list for a vector database (FAISS, Redis, or a managed vector index) and call a real embedding API, but the flow is the same:

import math
import time

SIMILARITY_THRESHOLD = 0.95
CACHE_TTL_SECONDS = 86400  # 24 hours

cache = []  # entries: {embedding, response, model, stored_at}

def cosine_similarity(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    norm_a = math.sqrt(sum(x * x for x in a))
    norm_b = math.sqrt(sum(y * y for y in b))
    return dot / (norm_a * norm_b)

def ask(question, model="chat-model"):
    query_vec = embed(question)  # cheap embedding call, not the LLM
    now = time.time()

    best, best_score = None, 0.0
    for entry in cache:
        if entry["model"] != model:
            continue  # answers from another model are not reusable
        if now - entry["stored_at"] > CACHE_TTL_SECONDS:
            continue  # expired
        score = cosine_similarity(query_vec, entry["embedding"])
        if score > best_score:
            best, best_score = entry, score

    if best is not None and best_score >= SIMILARITY_THRESHOLD:
        return best["response"], "cache-hit"

    response = llm_complete(question)  # the expensive call
    cache.append({
        "embedding": query_vec,
        "response": response,
        "model": model,
        "stored_at": now,
    })
    return response, "cache-miss"

Three details in that snippet carry most of the real-world weight. First, the cache key is not just the query text: the model name is part of the match, because an answer generated by one model should not be served as if it came from another. Second, entries expire via TTL, so stale answers eventually fall out. Third, the threshold is a single tunable number that decides everything about hit quality.

Exact-Match Cache vs Semantic Cache

An exact-match cache hashes the prompt string and only hits on byte-identical repeats. It is trivial to build and has almost no false positives, but in user-facing apps it misses constantly because people rephrase. This table lays out the trade-off:

Exact-match cache Semantic cache
Matches on Byte-identical prompt plus parameters Similar meaning in embedding space
Hit logic Hash lookup of the prompt string Cosine similarity at or above a threshold
“What is your refund policy?” vs “How do refunds work?” Two separate misses One hit, one stored answer reused
False positives Practically none Possible; requires threshold tuning and spot checks
Setup cost A dict or Redis key Embedding model plus a vector index
Best for Deterministic pipelines, retried identical calls User-facing Q&A with heavy phrasing variety

Tuning the Similarity Threshold

The threshold is the one knob you will touch most. Set it too low and the cache serves answers to questions that only vaguely resemble the original, which users notice fast. Set it too high and the cache barely hits, which defeats the purpose.

A practical way to tune it:

  • Start strict, around 0.95. Loosen it only after you have evidence the misses above, say, 0.90 were genuinely equivalent questions.
  • Log near-misses. Record pairs that scored just below the threshold. Reading a few dozen of these by hand is the fastest way to learn what your embedding model considers “similar” in your domain.
  • Sample your hits. Periodically pull random cache hits and check whether the stored answer truly fit the new question. This is your precision check; do it by hand on a small sample rather than trusting a dashboard number.
  • Re-tune when the embedding model changes. Similarity scores are not portable across embedding models, so a threshold tuned for one model means nothing for another.

Cache Keys, TTL, and Eviction

The query text is only part of what determines an answer. A correct cache key also folds in the model name, the system prompt, the temperature, any enabled tools or functions, and the version of the knowledge base the answer was drawn from. Leave the system prompt out and a support answer written in a formal tone gets served to a user whose session expects a casual one.

For expiry, combine two mechanisms. TTL handles answers that age: pricing, policies, documentation, anything tied to facts that change. Eviction handles size: cap the number of entries and drop the least recently used ones so the cache does not grow forever. And when you upgrade the underlying model, invalidate the whole cache; answers from the old model do not belong in the new one.

One more rule that matters in multi-tenant apps: scope entries per user or per tenant when answers can contain personal data. A shared semantic cache that serves one customer’s order details to another is a bug you do not want to explain.

When It Saves You Money

Semantic caching pays off where the same intents repeat across many users. The clearest cases:

  • Support bots. “Where is my order?”, “track my package”, “order status please” are one intent wearing many outfits. A support bot that fields thousands of these daily converts a large fraction of generation calls into cache hits.
  • FAQ and onboarding assistants. New users ask the same setup and pricing questions in endless paraphrases. The answer set is small and stable, which is exactly what a cache wants.
  • Classification and extraction pipelines. When you run the same prompt template over similar inputs, repeated intents hit the cache even though the raw text differs.
  • Rate-limit pressure. Beyond cost, a cache absorbs traffic spikes. Hits never touch the API, so they never count against your rate limits.

The savings math is qualitative but direct: every hit skips one generation call, and an embedding call costs a small fraction of a completion. Check your provider’s official pricing to see the exact ratio, then estimate from your own repeat-intent rate, not from anyone else’s benchmark.

When It Does Not Help

Semantic caching is a bad fit in several common situations, and recognizing them early saves you a wasted build:

  • Creative tasks. Brainstorming, writing help, and open-ended chat should produce different answers each time. Caching them makes the product feel broken.
  • Time-sensitive queries. Stock levels, prices, delivery ETAs, and news go stale fast. You can shorten TTL to compensate, but at some point the cache is just overhead.
  • Heavily personalized answers. If the response depends on the user’s history, plan, or data, per-user scoping shrinks the hit rate until the cache earns nothing.
  • Fast-changing knowledge bases. When the underlying facts update daily, you will spend more effort invalidating entries than you save serving them.
  • Low-traffic apps. If your app makes a few hundred LLM calls a day, the engineering time to build, tune, and monitor a semantic cache costs more than the API calls it would skip.

Getting Started

If you already run an exact-match cache, check your logs for repeat intents that missed because of rephrasing. That gap is your business case. For the build itself, you have two paths: wire it yourself with an embedding API and a vector store following the flow above, or use an open-source library like GPTCache, which bundles the embedding, vector search, TTL, and eviction pieces into one package. Either way, start on one high-repeat endpoint, tune the threshold by hand on real traffic, and expand only after the hit quality holds up.

A cheap way to estimate your ceiling before writing any cache code: take your last few thousand prompts, embed them, and count how many cluster above 0.95 similarity. That number is roughly the share of calls a well-tuned semantic cache could absorb. If it is small, your money is better spent on prompt optimization or a cheaper model.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.