Semantic Caching with Redis VL

In production Large Language Model applications, API latency and token costs scale directly with request volume. Traditional caching fails for LLMs because exact string matching cannot catch semantically equivalent queries (e.g., "What is the capital of France?" vs "Tell me France's capital city").

Enter Semantic Caching powered by the Redis Vector Library (Redis VL). Instead of matching exact strings, semantic caching embeds incoming user prompts into vector representations, querying a high-performance Redis vector index to serve cached responses instantly when a similar query is detected.

How Semantic Caching Works

Redis VL acts as an intelligent proxy layer between your application framework and your LLM provider, operating through a fast vector similarity lookup loop:

  • Prompt Embedding: Incoming queries are converted into dense vector embeddings using an efficient embedding model.
  • Vector Distance Search: Redis VL performs a fast KNN vector search against cached prompts stored in memory using cosine similarity or Euclidean distance.
  • Threshold Validation: If the similarity score exceeds your configured threshold (e.g., > 0.92), the cached LLM response is returned immediately with zero API latency.

Exact String Caching vs. Redis Semantic Caching

FeatureExact Match Caching (Redis/Memcached)Semantic Caching (Redis VL)
Matching LogicExact byte-for-byte string comparisonVector cosine similarity on embeddings
Paraphrase HandlingFails (treats rephrased queries as new)Matches semantically identical prompts
Latency ReductionInstant for repeated identical callsInstant for similar queries, saving LLM round-trips
Cost SavingsLow (misses conversational variations)High (drastically reduces redundant LLM token costs)

Python Implementation Blueprint

Using the redisvl package alongside OpenAI embeddings allows you to set up a high-performance semantic cache in just a few lines of code:

Python
Setting up semantic cache with Redis Vector Library
from redisvl.extensions.cache import SemanticCache
from redisvl.utils.vectorize import OpenAIEmbeddings

# Initialize vectorizer and semantic cache
vectorizer = OpenAIEmbeddings(model="text-embedding-3-small")

cache = SemanticCache(
    name="llm_semantic_cache",
    redis_url="redis://localhost:6379",
    vectorizer=vectorizer,
    distance_threshold=0.10  # High similarity cutoff
)

# Check cache or query LLM
prompt = "Explain quantum computing in simple terms."

# Try retrieving from cache
cached_response = cache.check(prompt=prompt)

if cached_response:
    print("Cache hit! Serving response from Redis VL:", cached_response)
else:
    print("Cache miss. Querying LLM and storing response...")
    # Store new response in cache after LLM call
    cache.store(prompt=prompt, response="Quantum computing uses qubits...")

Production Best Practices

Deploying semantic caches in high-traffic enterprise environments requires careful tuning of distance thresholds and cache invalidation policies:

  • Tune Distance Thresholds Carefully: Set your distance threshold strictly enough to prevent false positives where slightly different questions return incorrect cached answers.
  • Set TTLs on Cache Keys: Configure Time-To-Live (TTL) expiration policies on your Redis cache entries to prevent stale data from lingering when underlying source documents update.
  • Monitor Cache Hit Ratios: Track hit rates using Redis metrics to quantify API cost reductions and latency improvements across user sessions.