Overview
A semantic cache stores past LLM responses alongside their vector embeddings so paraphrased queries can reuse an existing answer. Instead of needing an exact string match, it checks cosine similarity between the new query vector and cached vectors.
- Fewer LLM calls and lower latency: Similar user questions hit Redis directly and skip model inference when similarity passes your threshold.
- Exact metadata and TTL control: Store model name, prompt version, and a time-to-live (TTL) with each entry so stale or mismatched answers are never returned.
Steps
- Embed the incoming query: Generate a vector embedding for the user’s question using the same embedding model used when caching responses.
- Search Redis for nearest neighbors: Query a Redis vector index (such as RediSearch
FT.SEARCHwithKNN) or scan stored entries to find the closest cached vectors. - Check similarity, model, and prompt version: Return the cached answer only if cosine similarity meets your threshold and metadata like
modelandpromptVersionmatch. - Store misses with a TTL: When no close match is found, call the LLM, embed the query, and save the entry in Redis with an expiration time.
Example
import type { RedisClientType } from "redis";
export interface SemanticCacheEntry {
id: string;
queryText: string;
responseText: string;
embedding: number[];
model: string;
promptVersion: string;
createdAtMs: number;
}
export interface SemanticCacheLookupResult {
hit: boolean;
similarity: number;
responseText?: string;
matchedQuery?: string;
entryId?: string;
}
export function cosineSimilarity(a: number[], b: number[]): number {
if (a.length !== b.length || a.length === 0) {
throw new Error("Embeddings must be non-empty arrays of equal length.");
}
let dot = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
const denom = Math.sqrt(normA) * Math.sqrt(normB);
return denom === 0 ? 0 : dot / denom;
}
export class RedisSemanticCache {
private readonly keyPrefix: string;
private readonly similarityThreshold: number;
private readonly ttlSeconds: number;
constructor(
private readonly redis: RedisClientType,
options?: {
keyPrefix?: string;
similarityThreshold?: number;
ttlSeconds?: number;
}
) {
this.keyPrefix = options?.keyPrefix ?? "semcache:";
this.similarityThreshold = options?.similarityThreshold ?? 0.9;
this.ttlSeconds = options?.ttlSeconds ?? 3600;
}
private buildKey(id: string): string {
return `\${this.keyPrefix}${id}`; } async set(entry: Omit<SemanticCacheEntry, "id" \vert{} "createdAtMs">): Promise<string> { const id = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; const record: SemanticCacheEntry = { ...entry, id, createdAtMs: Date.now(), }; const key = this.buildKey(id); await this.redis.set(key, JSON.stringify(record), { EX: this.ttlSeconds, }); return id; } async lookup(params: { queryEmbedding: number[]; model: string; promptVersion: string; maxScanKeys?: number; }): Promise<SemanticCacheLookupResult> { const maxScanKeys = params.maxScanKeys ?? 500; let bestScore = -1; let bestEntry: SemanticCacheEntry \vert{} null = null; let scanned = 0; for await (const key of this.redis.scanIterator({ MATCH: `${this.keyPrefix}*`,
COUNT: 100,
})) {
if (scanned >= maxScanKeys) break;
scanned += 1;
const raw = await this.redis.get(String(key));
if (!raw) continue;
const parsed = JSON.parse(raw) as SemanticCacheEntry;
if (parsed.model !== params.model || parsed.promptVersion !== params.promptVersion) {
continue;
}
const score = cosineSimilarity(params.queryEmbedding, parsed.embedding);
if (score > bestScore) {
bestScore = score;
bestEntry = parsed;
}
}
if (bestEntry && bestScore >= this.similarityThreshold) {
return {
hit: true,
similarity: Number(bestScore.toFixed(4)),
responseText: bestEntry.responseText,
matchedQuery: bestEntry.queryText,
entryId: bestEntry.id,
};
}
return {
hit: false,
similarity: bestScore < 0 ? 0 : Number(bestScore.toFixed(4)),
};
}
}
Tips
- Use RediSearch vector indexes for large caches:
SCANworks for small sets, but once you have tens of thousands of entries, use a Redis vector index (HNSWorFLAT) for fast nearest-neighbor search. - Keep the similarity threshold high (around 0.88–0.95): A low threshold can return a cached answer for a related but different question, such as changing dates, IDs, or negation words.
- Do not cache time-sensitive or user-private answers: Skip semantic caching for live prices, account data, or real-time status queries unless you scope keys strictly and set very short TTLs.
You must log in or register to comment.
