AiCredits
Caching Deep Dive

Semantic Cache for LLM Apps: Caching Strategies That Actually Work

A practical guide to semantic caching for LLM apps: how it works, where it silently breaks, how to tune similarity thresholds, and where it fits beside exact caches.

Published 2026-10-29 Updated 2026-10-29 8 min

Why "just add a cache" fails on LLM traffic

A normal cache is keyed on the exact input. Users of your API form rarely type the exact same string twice. "How do I rotate my API key?" and "how can I rotate my api key" are different bytes and identical intent, so an exact-match cache quietly logs a near-zero hit rate while you keep paying for the same answer.

That mismatch is the whole reason semantic caching exists: instead of matching strings, you match meaning. But semantic caching is also the only cache layer that can return a confidently wrong answer, so it needs a different design discipline than the Redis drop-in you are used to.

LayerCatchesWhat it savesMain risk
Exact-match cacheByte-identical normalized promptsThe entire round tripVery low hit rate on human text
Semantic cacheParaphrases of the same intentThe entire round tripWrong answer served with high confidence
Provider prompt cacheRepeated prompt prefixesInput processing on the shared prefixOnly helps if your prefix is stable
Client-side response cacheRepeated HTTP calls from your appNetwork and parse timeBlind to per-user context

How a semantic cache actually works

Three steps. Embed the incoming user question. Compare that vector against vectors of previously answered questions. If the closest neighbour clears a similarity threshold, return the stored answer instead of calling the model.

Two details matter more than the rest. First, embed the question, not the answer — you are matching intent, not phrasing. Second, keep an exact-hash tier in front of the semantic one. It is free, it is risk-free, and on high-traffic FAQ endpoints it will absorb a meaningful share of repeats before the vector search runs at all.

Here is a working two-tier cache. It namespaces entries per tenant, keys them on model plus system prompt so a prompt change invalidates old answers, and expires everything on a TTL.

# pip install openai sentence-transformers numpy
import hashlib
import time

import numpy as np
from openai import OpenAI
from sentence_transformers import SentenceTransformer

client = OpenAI(
    api_key='YOUR_AICREDITS_KEY',
    base_url='https://api.aicreditsapi.com/v1',
)
embedder = SentenceTransformer('all-MiniLM-L6-v2')


def normalize(text):
    return ' '.join(text.lower().split())


def prompt_hash(system, user, model):
    raw = '|'.join([model, normalize(system), normalize(user)])
    return hashlib.sha256(raw.encode()).hexdigest()


class SemanticCache:
    def __init__(self, threshold=0.93, ttl=3600, max_items=1000):
        self.threshold = threshold
        self.ttl = ttl
        self.max_items = max_items
        self.exact = {}     # hash -> (expires_at, answer)
        self.entries = []   # semantic index

    def get(self, system, user, model, namespace):
        now = time.time()
        key = prompt_hash(system, user, model)
        hit = self.exact.get(key)
        if hit and hit[0] > now:
            return hit[1], 'exact', 1.0
        if hit:
            self.exact.pop(key, None)

        query = embedder.encode(normalize(user), normalize_embeddings=True)
        best, best_score = None, 0.0
        for entry in self.entries:
            if entry['namespace'] != namespace or entry['expires_at'] <= now:
                continue
            score = float(np.dot(query, entry['embedding']))
            if score > best_score:
                best, best_score = entry, score

        if best is not None and best_score >= self.threshold:
            return best['answer'], 'semantic', best_score
        return None, 'miss', best_score

    def set(self, system, user, model, namespace, answer):
        now = time.time()
        self.exact[prompt_hash(system, user, model)] = (now + self.ttl, answer)
        self.entries.append({
            'embedding': embedder.encode(normalize(user), normalize_embeddings=True),
            'answer': answer,
            'namespace': namespace,
            'expires_at': now + self.ttl,
        })
        live = [e for e in self.entries if e['expires_at'] > now]
        self.entries = live[-self.max_items:]


SYSTEM = 'You are a support assistant for an API company. Answer in 80 words or fewer.'
MODEL = 'deepseek-v4-flash'


def answer(question, cache, namespace='public'):
    cached, kind, score = cache.get(SYSTEM, question, MODEL, namespace)
    if cached is not None:
        return {'text': cached, 'source': kind, 'similarity': round(score, 4)}

    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {'role': 'system', 'content': SYSTEM},
            {'role': 'user', 'content': question},
        ],
        temperature=0,
    )
    text = response.choices[0].message.content
    cache.set(SYSTEM, question, MODEL, namespace, text)
    return {'text': text, 'source': 'llm', 'similarity': 0.0}


if __name__ == '__main__':
    cache = SemanticCache(threshold=0.93, ttl=1800)
    for q in ['How do I rotate my API key?',
              'How can I rotate my API key?',
              'What models are available?']:
        result = answer(q, cache)
        print(result['source'], result['similarity'], '|', q)

The failure mode nobody budgets for: near-miss hits

"How do I rotate my API key?" and "How do I revoke my API key?" sit very close together in embedding space. One is a routine maintenance task; the other can break a production integration. A threshold tuned too low will serve the rotation answer to someone asking about revocation, and the user has no way to know they got the wrong one.

That is the real cost of a semantic cache: not the infrastructure, but the judgement. A cache miss costs you one API call. A bad hit costs you trust. Tune accordingly, and tune on your own traffic — a threshold that works on a cooking-recipe bot is wrong for anything with account, billing, or security intent.

Before trusting any threshold, hand-label a few dozen paraphrase pairs from your real logs and check where the scores actually land. This script is the five-minute version that saves you a week of confusion.

# pip install sentence-transformers numpy
import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer('all-MiniLM-L6-v2')


def similarity(a, b):
    va, vb = model.encode([a, b], normalize_embeddings=True)
    return float(np.dot(va, vb))


# Label each pair yourself: should this be a HIT or a MISS?
pairs = [
    ('How do I rotate my API key?', 'How can I rotate my API key?'),
    ('How do I rotate my API key?', 'How do I revoke my API key?'),
    ('How do I rotate my API key?', 'Where do I find my API key?'),
    ('Does the API support streaming?', 'Is streaming supported?'),
    ('Does the API support streaming?', 'Does the API support fine-tuning?'),
]

for a, b in pairs:
    print(f'{similarity(a, b):.3f}  {a}  <->  {b}')

Tuning rules that hold up in production

  • Start strict. A high threshold (0.93 and up is a reasonable opening bid for sentence-embedding models) gives you a small number of safe hits. Loosen only after reading cached pairs by hand.

  • Keep separate thresholds per intent class. Billing, security, and account questions deserve a stricter bar than "what is your rate limit". One global number is a compromise you will regret.

  • Never cache personalised answers. Anything that embeds a user ID, account balance, or order status must be namespaced per user, which usually means it should not enter the semantic tier at all.

  • Include model and system prompt in the cache key. Otherwise a prompt rewrite leaves old answers alive under a new contract.

  • Log the similarity score on every hit. Without that number you cannot audit a bad answer after the fact, and you cannot re-tune with evidence.

  • Set a TTL even when the content feels timeless. Docs change, products ship, and stale-but-confident is worse than slow-but-correct.

  • Skip semantic caching for code generation and structured extraction. Small wording differences in a prompt produce materially different output, and a near-match is a bug you ship.

  • Ship a kill switch. One environment flag that bypasses the cache entirely turns an incident from an outage into a config change.

A semantic cache is a product decision disguised as an infrastructure task. Someone has to decide which questions are allowed to be treated as the same question.

Where your provider already caches for you

Semantic caching is only one layer. DeepSeek models behind AiCredits also benefit from provider-side prompt caching: if many of your requests share an identical prefix — a long system prompt, a tool definition block, a fixed instruction preamble — that repeated prefix is processed more cheaply than fresh input. Cache hits are cheaper than misses, and off-peak usage costs less than peak, so the ordering of your messages array is a real cost lever.

The practical rule: put static text first, variable text last. A system prompt that changes per request destroys the prefix cache; the same system prompt with the user question appended keeps it warm. Combine that with a semantic cache in front for paraphrased FAQ traffic, and you are attacking both the shared prefix and the repeated question.

AiCredits sells DeepSeek credits to international developers with a card or PayPal — no Chinese phone number or bank account required — which matters if you want to run experiments like these against deepseek-v4-flash without friction. Current rates live at aicreditsapi.com/pricing. Use deepseek-v4-flash as the default in your pipeline and reserve deepseek-v4-pro for the requests where quality actually changes the outcome.

A lookup order that stays sane

  • Exact hash, scoped to tenant — cheap, safe, no threshold to argue about.

  • Semantic tier, only for intents you have explicitly whitelisted as paraphrase-safe.

  • Provider prompt cache for the stable prefix of every request that reaches the model.

  • Full generation with deepseek-v4-flash, temperature 0 for cacheable paths so the stored answer is stable.

  • Store the result, log the similarity, and emit a metric for hit rate by intent class so you notice when a prompt change silently drops it to zero.

One last note: cache logic is code, and cache-key code is the kind that fails silently. Normalisation bugs, a missing namespace field, a hash that forgets the model name — none of them throw an exception, they just quietly serve the wrong thing. Run your caching module through a linter before it ships.

FAQ

What hit rate should I expect from a semantic cache?

It depends entirely on your traffic shape. A public FAQ endpoint and a per-user coding assistant are not the same problem. Measure for a week before you set expectations, and treat any hit rate on personalised traffic as a red flag rather than a win.

Is semantic caching the same as DeepSeek's context caching?

No. Provider-side prompt caching reuses the processed prefix of a prompt to make input cheaper and faster. A semantic cache skips the model call entirely because a near-identical question was already answered. They stack: the semantic cache catches paraphrases, the prompt cache catches the shared prefix on whatever still reaches the model.

Should I cache code generation responses?

Generally no. Two prompts that look nearly identical can require structurally different code, and the user has no easy way to spot that the answer was borrowed from a different question. Use exact-match caching only for code paths, if at all.

Can I use semantic caching with a shared cache across all users?

Only for genuinely public, non-personalised content. Namespace by tenant or user ID for everything else, and keep account, billing, and security intents out of the shared tier entirely.

What embedding model should I use?

Any small sentence-embedding model works as a first pass; swap it for a domain-tuned one if your vocabulary is specialised. Whatever you choose, re-calibrate your threshold whenever you change the embedding model, because similarity scores are not comparable across models.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×