AI & LLMOps
Semantic Caching for LLM APIs: Slashing Latency and Token Costs with Redis and GPTCache
As enterprise adoption of Large Language Models expands across customer support, coding assistants, and internal copilots, API token costs and inference latency become crippling operational bottlenecks. Standard key-value caching fails completely in generative AI because users phrase semantically identical queries using different syntax. Semantic caching bridges this gap by mapping incoming prompts into high-dimensional vector embeddings, querying similarity indexes in Redis or Qdrant, and serving precomputed responses in single-digit milliseconds.
Exact Match vs Semantic Similarity Caching
Understanding the architectural tradeoffs between hash-based caching and vector-based semantic lookup is vital for tuning cache hit rates and precision:
| Caching Model | Lookup Mechanism | Hit Rate on Varied Queries | Latency | Risk of False Positives |
|---|---|---|---|---|
| Exact String Hash | SHA-256 / MD5 key lookup | 5% – 12% | < 1 ms | 0% (Strict deterministic match) |
| Semantic Vector Cache | Cosine distance on embeddings | 35% – 65% | 8 – 18 ms | Low (Controlled by similarity threshold) |
| Direct LLM Inference | Full model generation pass | N/A | 1,200 – 4,500 ms | N/A |
Production Semantic Caching Engine with Redis and SentenceTransformers
Below is a production Python implementation utilizing Redis vector similarity search (VSS) and local sentence embedding models to achieve sub-20ms cached inference:
# semantic_cache.py
import redis
import numpy as np
from sentence_transformers import SentenceTransformer
from redis.commands.search.query import Query
class SemanticCache:
def __init__(self, redis_host="localhost", redis_port=6379, threshold=0.88):
self.r = redis.Redis(host=redis_host, port=redis_port)
self.model = SentenceTransformer("all-MiniLM-L6-v2")
self.threshold = threshold
self.index_name = "llm_cache_idx"
def get_or_set(self, prompt: str, generate_fn):
# 1. Embed incoming user prompt
prompt_vec = self.model.encode(prompt, normalize_embeddings=True).astype(np.float32).tobytes()
# 2. Query Redis Vector Index via KNN Search
q = Query(f"*=>[KNN 1 @prompt_vector $vec AS score]")\
.sort_by("score")\
.return_fields("response", "score")\
.paging(0, 1)\
.dialect(2)
results = self.r.ft(self.index_name).search(q, query_params={"vec": prompt_vec})
if results.docs:
top_match = results.docs[0]
similarity = 1 - float(top_match.score) # Cosine distance to similarity
if similarity >= self.threshold:
print(f"[CACHE HIT] Similarity: {similarity:.4f}")
return top_match.response
# 3. Cache Miss: Execute expensive LLM inference call
print("[CACHE MISS] Invoking LLM...")
llm_response = generate_fn(prompt)
# 4. Asynchronously populate cache with vector & response
cache_id = f"cache:{self.r.incr('cache_counter')}"
self.r.hset(cache_id, mapping={
"prompt": prompt,
"prompt_vector": prompt_vec,
"response": llm_response
})
return llm_response
- Dynamic Threshold Tuning: Calibrate the cosine similarity threshold (typically 0.85–0.92) to match task sensitivity; higher thresholds prevent semantic drift in regulatory workflows.
- Session Scoping: Partition vector indexes by user account ID or tenant ID to prevent data leakage between multi-tenant environments.
- Time-to-Live (TTL) Eviction: Apply automatic key expiration on cached responses to ensure dynamic knowledge updates don’t serve stale answers.
