Semantic Caching with Amazon Titan V2, ElastiCache Serverless and Valkey


When most people hear "semantic cache", they immediately think about embedding a query, doing a vector search, and returning a cached response if the similarity crosses some threshold.
In reality, the hard part isn't the vector search.
The hard part is figuring out when semantic caching should even be attempted.
While designing a multilingual customer support RAG system, I studied about semantic caching with:
- Amazon Titan Text Embeddings V2
- Amazon ElastiCache for Valkey Serverless
Along the way I discovered that semantic caching is much more of a routing problem than a vector database problem.
This post documents the final architecture and some of the engineering decisions behind it.
The Goal
The objective was straightforward:
- User sends a query.
- Check whether a semantically similar question was already answered.
- If yes, return the cached response immediately.
- If not, continue through the normal RAG pipeline.
- Cache the generated result for future requests.
Conceptually:
User Query
│
▼
Semantic Cache
│
┌───┴────┐
│ Hit │ Miss
▼ ▼
Return Retrieval
Cache │
▼
Generator
│
▼
Store Response
Simple on paper.
Why Amazon Titan Embeddings V2?
Titan V2 supports multiple output dimensions:
- 256
- 512
- 1024
Initially I assumed 1024 dimensions would always be the safest choice.
After looking into the model design, that wasn't necessarily true.
For semantic caching, retrieval accuracy isn't the only metric that matters.
Other things I considered were:
- Memory usage
- Search latency
- Throughput
- Cost
Since Titan V2 supports dimensionality reduction natively, dropping to 256 dimensions dramatically reduces vector storage requirements while still retaining most of the semantic information needed for customer-support-style intent matching.
For my use case, I tried with 256 and 512 dimensions instead of going with 1024 dim size by default.
{
"inputText": query,
"dimensions": 256,
"normalize": True
}
The benefits:
- 75% less storage than 1024 dimensions
- Smaller network payloads
- Faster vector distance calculations
- Better cache density in Valkey
For semantic caching, that's usually a worthwhile tradeoff.
Why Valkey + HNSW?
For vector search, the choice was relatively easy.
Use HNSW. Not FLAT.
A FLAT index performs exhaustive comparisons against every vector.
That approach works for small datasets but scales poorly.
HNSW builds a graph structure that allows approximate nearest-neighbor search with very high recall and significantly better performance characteristics.
The index configuration looked roughly like:
VectorField(
"$.embedding",
"HNSW",
{
"TYPE": "FLOAT32",
"DIM": 256,
"DISTANCE_METRIC": "COSINE",
"M": 16,
"EF_CONSTRUCTION": 200
}
)
For semantic caching, HNSW is almost always the correct choice.
The Similarity Threshold Problem
One of the first questions was:
What similarity threshold should trigger a cache hit?
At first, 95% sounded reasonable.
Then I started thinking about actual customer behavior.
These two messages are obviously the same intent:
How do I update my credit card?My subscription renews tomorrow.
How can I change my payment method?Yet a very strict threshold might reject the second query.
A semantic cache that rarely hits provides little value.
Eventually I settled on aiming around 90% semantic similarity for the POC (Proof of concept).
import os
import json
import struct
import hashlib
import boto3
import litellm
from valkey import Valkey
from valkey.commands.search.field import VectorField, TextField
from valkey.commands.search.indexDefinition import IndexDefinition, IndexType
from valkey.commands.search.query import Query
# Configuration parameters
VALKEY_HOST = os.environ.get("VALKEY_HOST", "://amazonaws.com")
VALKEY_PORT = int(os.environ.get("VALKEY_PORT", 6379))
INDEX_NAME = "semantic_cache_idx"
DIMENSIONS = 256 # Truncating Titan V2 for optimal performance
DISTANCE_THRESHOLD = 0.10 # 1.0 - 0.90 = 0.10 (Enforces a strict 90% similarity)
CACHE_TTL_SECONDS = 86400 # 24-hour expiration safety window
# AWS Service Clients
bedrock_client = boto3.client("bedrock-runtime", region_name="us-east-1")
valkey_client = Valkey(host=VALKEY_HOST, port=VALKEY_PORT, decode_responses=False, ssl=True)
def initialize_hnsw_index():
"""Configures the structural HNSW vector search graph space inside Valkey."""
try:
valkey_client.ft(INDEX_NAME).info()
print("HNSW Vector cache index is active.")
except Exception:
print("Creating fresh HNSW index layout inside ElastiCache cluster...")
schema = (
TextField("\$.query", as_name="query"),
TextField("\$.response", as_name="response"),
VectorField(
"\$.embedding",
"HNSW",
{
"TYPE": "FLOAT32",
"DIM": DIMENSIONS,
"DISTANCE_METRIC": "COSINE",
"M": 16,
"EF_CONSTRUCTION": 200
},
as_name="embedding"
)
)
valkey_client.ft(INDEX_NAME).create_index(
fields=schema,
definition=IndexDefinition(prefix=["cache:"], index_type=IndexType.JSON)
)
def get_titan_v2_embedding(text: str) -> list:
"""Extracts a structural 256-dimensional unit vector embedding payload from Bedrock."""
body = json.dumps({
"inputText": text,
"dimensions": DIMENSIONS,
"normalize": True
})
response = bedrock_client.invoke_model(
body=body,
modelId="amazon.titan-embed-text-v2:0",
accept="application/json",
contentType="application/json"
)
response_body = json.loads(response.get("body").read())
return response_body.get("embedding")
def check_semantic_cache(vector_bytes: bytes):
"""Executes a Dialect 2 HNSW query to identify matches within a 90% similarity bounds."""
query_str = "(*)=>[KNN 1 @embedding \$vec_param AS vector_distance]"
q = (
Query(query_str)
.sort_by("vector_distance")
.paging(0, 1)
.return_fields("query", "response", "vector_distance")
.dialect(2)
)
results = valkey_client.ft(INDEX_NAME).search(q, query_params={"vec_param": vector_bytes})
if results.docs:
match = results.docs[0]
distance = float(match.vector_distance)
# Validate if match meets the minimum 90% requirement
if distance <= DISTANCE_THRESHOLD:
similarity = (1 - distance) * 100
print(f"🔥 Cache Hit! Target intent similarity: {similarity:.2f}%")
doc_data = json.loads(match.json)
return doc_data["response"], distance
print("❄️ Cache Miss. Proceeding downstream...")
return None, None
def write_to_cache(query_text: str, response_text: str, embedding: list, cache_key: str):
"""Saves transaction states downstream with an architectural TTL limit constraint."""
cache_data = {
"query": query_text,
"response": response_text,
"embedding": embedding
}
pipe = valkey_client.pipeline()
pipe.json().set(f"cache:{cache_key}", "\$", cache_data)
pipe.expire(f"cache:{cache_key}", CACHE_TTL_SECONDS)
pipe.execute()
def execute_workflow_pipeline(user_query: str, chat_history: list) -> str:
"""Master workflow orchestrating Intent analysis, Caching logic, and Generator steps."""
# 1. Intent Node Evaluation (Simulated payload containing pre-determined routing checks)
# prompt instructions: set should_check_semantic_cache=False for "yes", "no", conversions etc.
intent_payload = {"intent": "billing", "should_check_semantic_cache": True, "detected_language": "en"}
# 2. Vector Validation Routing
if intent_payload.get("should_check_semantic_cache", False):
query_embedding = get_titan_v2_embedding(user_query)
# Serialize list floats cleanly to binary bytes using struct.pack
vector_bytes = struct.pack(f"{len(query_embedding)}f", *query_embedding)
cached_answer, distance = check_semantic_cache(vector_bytes)
if cached_answer:
return cached_answer
# 3. Classic RAG Execution Block (Bypassed if cache hits successfully)
llm_response = litellm.completion(
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
messages=[{"role": "user", "content": user_query}]
)
final_response = llm_response.choices.message.content
# 4. Populate cache index for future iterations
if intent_payload.get("should_check_semantic_cache", False):
query_hash = hashlib.sha256(user_query.strip().lower().encode('utf-8')).hexdigest()
write_to_cache(user_query, final_response, query_embedding, query_hash)
return final_response
Now semantic caching becomes a downstream optimization rather than a separate intelligence layer.
Final Architecture
The resulting architecture is much cleaner.
User Query
│
▼
Intent Node
│
┌─────────────┴─────────────┐
│ │
▼ ▼
should_check_cache=true should_check_cache=false
│ │
▼ │
Titan Embedding │
│ │
▼ │
Valkey Semantic Cache │
│ │
Hit? │ │
┌──────┴─────┐ │
▼ ▼ │
Return Retrieval ◄─────────────┘
Cache │
▼
Generator
│
▼
Cache ResponseThe Intent Node effectively acts as the gatekeeper.
Only standalone support requests reach the semantic cache.
Context-dependent conversational replies skip it entirely.
Lessons Learned
A few conclusions after designing this system:
1. Semantic caching is mostly a routing problem
Vector search is easy.
Determining when vector search is appropriate is the real challenge.
2. 256 dimensions are often enough
For customer support workloads, 256-dimensional Titan embeddings offer an excellent balance between cost, speed, and accuracy.
3. Don't over-optimize for exact matches
Exact string matches rarely happen in consumer applications.
Users naturally express the same intent in different ways.
4. Context matters more than similarity
A perfectly similar vector is still wrong if the query depends on previous conversation turns.
5. Your Intent Node should own routing decisions
If an LLM is already analyzing intent, language, and context, let it decide whether semantic caching is even applicable.
Adding another classifier usually increases complexity without adding much value.
Closing Thoughts
When I first started exploring semantic caching, I thought the important questions would be:
- Which vector database should I use?
- What embedding model should I pick?
- What similarity threshold should I configure?
Those questions matter.
But the more important question turned out to be:
"Should this request even be eligible for semantic caching?"
Once that decision moved into the Intent Node, the entire architecture became simpler, faster, and easier to reason about.
The semantic cache stopped acting like a separate subsystem and instead became what it should be:
A fast optimization layer that sits behind intelligent routing.