Semantic Caching for LLMs: Slashing Latency & API Token Costs
High LLM API bills and 2s P99 latency? Build vector semantic caching with Redis and pgvector, tune cosine similarity thresholds, and isolate tenant scopes.
You review your monthly foundation model invoices, and the cost trajectory looks unsustainable. A customer support chatbot or code analysis assistant answers thousands of queries daily, and P99 latency hovers around 2,800 milliseconds while token billing increases exponentially.
Traditional key-value caching (like hashing prompt strings in Redis) fails completely for generative AI because users never ask questions using identical wording. Asking “How do I reset my password?” and “I forgot my password, where can I change it?” represent identical semantic intent, yet traditional key-value stores see two completely distinct SHA-256 hashes, generating two separate expensive LLM completions.
Semantic caching bridges this gap by indexing prompt embeddings in a vector database. Conceptual duplicates hit sub-15 millisecond vector lookups, slashing external LLM token spend by 40% to 70% while dropping P99 latencies to near-zero.
Here is the immediate triage checklist to implement a production-grade semantic cache:
- Normalize User Prompts Before Embedding: Strip trailing punctuation, collapse duplicate whitespace, lowercase characters, and remove ephemeral markers (like timestamps or UUIDs) before generating the vector embedding.
- Calibrate the Cosine Distance Threshold: Set your similarity threshold to
0.92as a starting baseline. Never set thresholds below0.88unless your application tolerates approximate answers. - Partition by Tenant Boundaries: Always combine vector similarity search with strict scalar metadata filtering (
tenant_id == current_tenant) to prevent multi-tenant data leakage. - Enforce TTL Expiration: Apply time-to-live expiration (e.g., 7 days) on cached records to prevent stale domain facts from persisting indefinitely after application updates.
Illustrative architectural flow of a semantic cache pipeline:
+-------------------------------------------------------------------------+
| Semantic Cache Execution Lifecycle |
| |
| [ Incoming User Prompt: "How do I update my billing credit card?" ] |
| | |
| v |
| [ Fast Embedding Generation: text-embedding-3-small (15ms / $0.00002) ] |
| | |
| v |
| [ Vector Similarity Search (Redis VSS / pgvector with HNSW) ] |
| Query: Cosine Distance <= 0.08 (Similarity >= 0.92) |
| Filter: tenant_id = 'org_441' |
| | |
| +------------------------+------------------------+ |
| | | |
| [CACHE HIT] [CACHE MISS] |
| Similarity = 0.948 Similarity = 0.821 |
| | | |
| v v |
| Return Cached Completion Execute Full LLM Call |
| Latency: 12ms (OpenAI/Claude API) |
| Cost: $0.00002 Latency: 2,400ms |
| Cost: $0.018 |
| | |
| v |
| Store Vector + Answer |
| in Cache (TTL: 7d) |
+-------------------------------------------------------------------------+
The Economics: Traditional Caching vs Semantic Vector Caching
The table below contrasts operational metrics between un-cached LLM systems, exact-match string caching, and vector semantic caching across a sample workload of 500,000 monthly enterprise queries:
| Metric | Direct LLM (No Cache) | Exact Match Cache (SHA-256) | Semantic Vector Cache |
|---|---|---|---|
| Typical Cache Hit Rate | 0% | 4% to 8% | 38% to 65% |
| P99 Response Latency | 2,800ms to 4,200ms | 2,700ms (overall) | 18ms (on cache hit) |
| Monthly Token Invoice | $12,400 | $11,500 | $4,800 (61% savings) |
| Sensitivity to Phrasing | High (every call costs) | Total failure on synonyms | Zero (embeddings map intent) |
| Infrastructure Cost | $0 (API only) | $15/mo (small Redis) | $45/mo (Redis VSS / pgvector) |
| Net Monthly ROI | Baseline | Minimal | +$7,555 net profit |
When an application scales past 10,000 requests daily, the compute cost of generating prompt embeddings (fractions of a cent per thousand tokens) is dwarfed by the massive savings generated by bypassing high-parameter generation models like GPT-4o or Claude 3.5 Sonnet.
Architectural Pitfall: The Similarity Threshold Dilemma
The single most critical engineering decision in a semantic cache is selecting the distance threshold.
Vector databases measure similarity using cosine similarity, where a score of 1.0 represents an identical vector direction and 0.0 represents orthogonal meaning. In distance terms, Cosine Distance = 1 - Cosine Similarity.
0.80 0.88 0.92 0.96 1.00
<------------------+------------------+------------------+------------------>
FALSE POSITIVE SWEET SPOT CONSERVATIVE EXACT MATCH
HALLUCINATION PRODUCTION BASELINE INEFFICIENT
"Cat" matches "Dog" Balanced Precision High Accuracy High Miss Rate
The Under-Filtering Trap (< 0.88 Similarity)
If you configure your threshold too permissively (e.g., cosine similarity 0.85), the vector engine treats queries with related entities as interchangeable.
Consider this catastrophic failure:
- Cached Prompt: “How do I delete my production database cluster?”
- New User Prompt: “How do I create my production database cluster?”
Because both sentences share words like “production”, “database”, and “cluster”, their embedding vectors are remarkably close in geometric space (often hovering around 0.86 similarity). A permissive cache returns the deletion runbook to a user attempting creation.
The Over-Filtering Trap (> 0.96 Similarity)
Conversely, setting the threshold to 0.98 neutralizes the benefits of vector search. Even minor variations in grammar or synonym replacement cause similarity scores to drop below 0.98, reducing your semantic cache to a bloated, expensive exact-string cache.
The Production Target: 0.91 to 0.94
Empirical production testing demonstrates that the ideal similarity sweet spot sits between 0.91 and 0.94 when utilizing modern dense embedding models (like OpenAI text-embedding-3-small or Cohere embed-english-v3.0). At 0.92, variations like:
- “How do I invite teammates to my organization?”
- “Where is the team invitation link in my workspace?”
score at 0.932 similarity, delivering accurate cached answers while rejecting contradictory or distinct operations.
Building a Production Semantic Cache with pgvector
If your architecture already leverages PostgreSQL, you do not need to introduce another operational dependency like a dedicated vector engine. PostgreSQL’s pgvector extension provides high-performance vector indexing with HNSW (Hierarchical Navigable Small World) graphs alongside native relational integrity.
1. Schema Definition with Tenant Metadata and Vector Index
-- Enable vector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- Define semantic cache table with metadata filtering
CREATE TABLE llm_semantic_cache (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id VARCHAR(64) NOT NULL,
prompt_text TEXT NOT NULL,
prompt_hash VARCHAR(64) NOT NULL,
prompt_embedding vector(1536) NOT NULL, -- 1536 dimensions for text-embedding-3-small
completion_text TEXT NOT NULL,
model_name VARCHAR(64) NOT NULL,
hit_count INTEGER DEFAULT 1,
created_at TIMESTAMPTZ DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL
);
-- Compound index for exact-string fast path
CREATE INDEX idx_semantic_cache_hash ON llm_semantic_cache (tenant_id, prompt_hash);
-- HNSW Vector index using cosine distance (vector_cosine_ops)
CREATE INDEX idx_semantic_cache_embedding ON llm_semantic_cache
USING hnsw (prompt_embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
2. High-Performance Query with Distance Filtering
-- Query semantic cache with strict tenant isolation and cosine threshold
SELECT
id,
prompt_text,
completion_text,
-- Calculate cosine similarity: 1 - cosine distance
(1 - (prompt_embedding <=> $1::vector)) AS similarity
FROM llm_semantic_cache
WHERE tenant_id = $2
AND expires_at > now()
-- Distance threshold <= 0.08 is equivalent to Similarity >= 0.92
AND (prompt_embedding <=> $1::vector) <= 0.08
ORDER BY prompt_embedding <=> $1::vector ASC
LIMIT 1;
Complete TypeScript Implementation with OpenAI
Here is an enterprise-grade TypeScript implementation integrating prompt normalization, exact-match fast path, vector fallback, and asynchronous cache hydration:
// semantic-cache.ts
import crypto from "crypto";
import { Pool } from "pg";
import OpenAI from "openai";
const db = new Pool({ connectionString: process.env.DATABASE_URL });
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const SIMILARITY_THRESHOLD = 0.92;
const DISTANCE_THRESHOLD = 1 - SIMILARITY_THRESHOLD; // 0.08
// 1. Text Normalization Function
function normalizePrompt(text: string): string {
return text
.toLowerCase()
.trim()
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()?]/g, "") // Remove punctuation
.replace(/\s+/g, " "); // Collapse multiple spaces
}
export async function askLLMWithSemanticCache(
tenantId: string,
userPrompt: string
): Promise<{ answer: string; cached: boolean; latencyMs: number }> {
const startTime = Date.now();
const normalized = normalizePrompt(userPrompt);
const promptHash = crypto.createHash("sha256").update(normalized).digest("hex");
// Step 1: Fast Path (Exact string match via B-tree index in < 2ms)
const exactMatch = await db.query(
`SELECT completion_text FROM llm_semantic_cache
WHERE tenant_id = $1 AND prompt_hash = $2 AND expires_at > now()
LIMIT 1;`,
[tenantId, promptHash]
);
if (exactMatch.rows.length > 0) {
return {
answer: exactMatch.rows[0].completion_text,
cached: true,
latencyMs: Date.now() - startTime,
};
}
// Step 2: Generate Vector Embedding for Semantic Lookup
const embeddingResponse = await openai.embeddings.create({
model: "text-embedding-3-small",
input: normalized,
});
const vector = embeddingResponse.data[0].embedding;
const vectorString = `[${vector.join(",")}]`;
// Step 3: Semantic Vector Lookup via pgvector HNSW index
const semanticMatch = await db.query(
`SELECT id, completion_text, (1 - (prompt_embedding <=> $1::vector)) as similarity
FROM llm_semantic_cache
WHERE tenant_id = $2
AND expires_at > now()
AND (prompt_embedding <=> $1::vector) <= $3
ORDER BY prompt_embedding <=> $1::vector ASC
LIMIT 1;`,
[vectorString, tenantId, DISTANCE_THRESHOLD]
);
if (semanticMatch.rows.length > 0) {
const hitId = semanticMatch.rows[0].id;
// Asynchronously update hit count without blocking client response
db.query("UPDATE llm_semantic_cache SET hit_count = hit_count + 1 WHERE id = $1", [hitId]).catch(console.error);
return {
answer: semanticMatch.rows[0].completion_text,
cached: true,
latencyMs: Date.now() - startTime,
};
}
// Step 4: Cache Miss - Execute Full Foundation Model
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "You are a concise customer engineering assistant." },
{ role: "user", content: userPrompt },
],
temperature: 0, // Deterministic generation required for caching
});
const generatedAnswer = completion.choices[0].message.content || "";
// Step 5: Hydrate Semantic Cache Asynchronously (TTL: 7 Days)
const ttlDays = 7;
db.query(
`INSERT INTO llm_semantic_cache
(tenant_id, prompt_text, prompt_hash, prompt_embedding, completion_text, model_name, expires_at)
VALUES ($1, $2, $3, $4::vector, $5, $6, now() + interval '${ttlDays} days');`,
[tenantId, userPrompt, promptHash, vectorString, generatedAnswer, "gpt-4o"]
).catch(console.error);
return {
answer: generatedAnswer,
cached: false,
latencyMs: Date.now() - startTime,
};
}
When to Invalidate or Bypass Semantic Caches
Semantic caching is a high-leverage architectural pattern, but applying it indiscriminately will introduce subtle data integrity bugs. Adhere to these four operational guardrails:
1. Bypass on Non-Zero Temperature
If your invocation uses temperature > 0 (such as creative copywriting, narrative generation, or exploratory analysis), bypass the cache completely. Caching a temperature 0.8 prompt forces deterministic answers onto users who expected divergent responses.
2. Context-Bound Prompts with Dynamic Timestamps
If the user’s prompt incorporates dynamic runtime variables (e.g., “What is my pending balance as of 11:45 PM today?”), semantic caching will serve stale balance numbers from earlier sessions. Either strip dynamic timestamps before embedding or tag queries containing real-time state with Cache-Control: no-cache.
3. Immediate Domain Invalidation
When an organization updates its documentation, pricing tiers, or terms of service, stale answers stored in the cache will continue serving obsolete facts. Provide an administrative webhook to purge cache records by tenant_id:
-- Invalidate tenant cache upon knowledge base synchronization
DELETE FROM llm_semantic_cache WHERE tenant_id = 'tenant_xyz';
Frequently Asked Questions
Which embedding model is best for semantic caching?
OpenAI’s text-embedding-3-small (1536 dimensions) or Cohere’s embed-english-v3.0 are standard industry baselines. They deliver high semantic separation, calculate in under 20 milliseconds, and cost less than $0.00002 per request.
Can semantic caching handle multi-turn chat conversations?
Yes, but only if the embedding vector represents the aggregated conversation context rather than the isolated final turn. A common pattern embeds the concatenation of the last two turns: User: <previous> Assistant: <previous> User: <current>.
Does pgvector scale to millions of cached semantic prompts?
Yes. With an HNSW index configured with m = 16 and ef_construction = 64, pgvector evaluates cosine nearest neighbors across 500,000 vectors in 3 to 7 milliseconds, consuming minimal RAM compared to dedicated Java/Rust vector clusters.
How does semantic cache handle user-specific sensitive data?
By strictly partitioning every query by tenant_id and user_id. Never allow a global semantic search across unpartitioned vector tables; always include scalar filters in the WHERE clause so similarity calculations evaluate only within authorized tenant boundaries.
Related Engineering Guides
- Production RAG Architecture: Slashing Vector DB Invoices: Content-addressed chunk hashing, vector dimensionality right-sizing, and pgvector hybrid search.
- Structured JSON from LLMs: Eliminating Parse Retry Latency: Schema-constrained decoding, context-free grammar logit masking, and retry penalty elimination.
- Real-Time LLM Streaming: Stopping Serverless Token Waste: Wiring AbortController into ReadableStream lifecycles to stop orphaned serverless token billing.
Elena Rostova
Product Strategy LeadProduct and operations lead dedicated to helping non-technical founders navigate technical scale and architectural decisions. Advises founders on technical debt triage, cloud unit economics, and rapid pre-launch risk evaluation.
How does semantic caching differ from standard key-value caching for LLMs?
What is the optimal cosine similarity threshold for an LLM semantic cache?
Why must semantic caching be constrained to temperature 0 queries?
How do you prevent cross-tenant data leakage in semantic caches?
Have our team inspect your AI-generated codebase.
48-hour turnaround with direct pull requests fixing security and scale bottlenecks.