Production-grade guide to llm caching semantic covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
LLM caching semantic is a strategy to reduce latency and cost in generative AI systems by storing the results of semantic queries—typically embeddings—alongside their associated text or metadata. It matters when a large language model repeatedly processes similar or related inputs, such as in search pipelines, chatbots, or recommendation engines, where the same or semantically similar prompts appear frequently across users or sessions. Semantic caching avoids recomputing embeddings and rerunning LLMs on identical or near-identical queries by retrieving precomputed results from a fast, indexed store.
Use semantic caching when the input to your LLM is not just raw text but a query or context whose meaning matters more than its exact tokenization. For example, a query like *“What are the best practices for deploying LLMs in production?”* should match documents or prior responses about model serving, containerization, inference batching, and model versioning—even if the exact words differ.
Semantic caching is most effective when:
sentence-transformers) exceeds the cost of a single LLM inference.To cache a semantic query, compute its embedding and store it with the original input, metadata, and the corresponding LLM output.
Given a query string, generate a vector representation using a pre-trained embedding model. The embedding is used as a key to retrieve cached results.
curl -X POST http://embed-service:8080/embed \
-H "Content-Type: application/json" \
-d '{"text": "How do I optimize batch inference in LLMs?"}' \
| jq -r '.embedding'
This returns a JSON array of 768 floats (e.g., from all-MiniLM-L6-v2):
[
0.12, 0.45, -0.33, 0.87, ... , 0.01
]
Store this embedding as the primary key in a vector database (e.g., Faiss, Milvus, or Pinecone). The record includes:
query: the original textembedding: the 768-dimensional vectorllm_output: the result of applying the LLM to the querymetadata: timestamps, user IDs, session IDs, and query sourceWhen a new query arrives, compute its embedding and perform a nearest-neighbor search over the cached embeddings.
curl -X POST http://vector-db:8080/search \
-H "Content-Type: application/json" \
-d '{
"query_embedding": [0.11, 0.48, -0.31, 0.89, ...],
"k": 5,
"distance": "cosine"
}'
The response is a list of nearest matches:
[
{
"id": "q-12345",
"query": "How do I optimize batch inference in LLMs?",
"llm_output": "Use batching, dynamic batching, and model parallelism...",
"similarity": 0.98,
"metadata": { "user_id": 456, "timestamp": "2024-07-10T12:30:00Z" }
},
{
"id": "q-67890",
"query": "Best practices for scaling LLM inference",
"llm_output": "Use model serving frameworks, optimize memory, and batch requests...",
"similarity": 0.92,
"metadata": { "user_id": 456, "timestamp": "2024-07-10T11:45:00Z" }
}
]
If the top match has similarity ≥ 0.90, use it as the cached result.
A cache hit occurs when a query’s embedding matches a stored one within a threshold. A cache miss triggers recomputation and caching.
When the best match exceeds the similarity threshold (e.g., 0.90), return the stored llm_output immediately.
def semantic_cache_query(query: str, threshold: float = 0.90) -> dict:
embedding = embed(query)
results = vector_db.search(embedding, k=5, distance="cosine")
best_match = results[0]
if best_match["similarity"] >= threshold:
return {
"output": best_match["llm_output"],
"cached": True,
"source": best_match["id"],
"similarity": best_match["similarity"]
}
# Fall through to cache miss
return None
When no cached result is sufficiently similar, run the full LLM pipeline.
def compute_and_cache(query: str) -> dict:
embedding = embed(query)
llm_output = llm_infer(query)
vector_db.insert({
"query": query,
"embedding": embedding,
"llm_output": llm_output,
"metadata": {
"created_at": datetime.utcnow().isoformat(),
"source": "api/v1/query"
}
})
return {
"output": llm_output,
"cached": False,
"inserted": True
}
Cache behavior is governed by a few key parameters, each with sharp tradeoffs.
The similarity threshold determines when a query is deemed “close enough” to a cached one. A threshold of 0.90 means cosine similarity ≥ 0.90 between two embeddings.
A common failure is choosing a threshold without validating it against real query distribution. Queries with low semantic overlap (e.g., *“How to deploy LLMs”* vs. *“Scaling LLMs in cloud”*) may be missed entirely.
The choice of indexing method affects both latency and accuracy.
A common failure is using IVF without tuning nlist and nprobe. A setting of nlist=1000, nprobe=50 is a reasonable starting point, but production systems often need nprobe=100 or higher to avoid low-recall results.
The embedding model defines the semantic space. A query embedding from all-MiniLM-L6-v2 may not align well with one from paraphrase-MiniLM-L6-v2.
When changing models, ensure backward compatibility. The cache must store:
embedding_model: name or version (e.g., sentence-transformers/all-MiniLM-L6-v2:v1)model_version: the model’s version IDA silent failure occurs when a new embedding model is deployed but the cache is populated with old embeddings. The similarity scores degrade, and cache hits drop unexpectedly.
When the embedding model outputs a different number of dimensions (e.g., 384 vs. 768), the cache cannot match vectors directly.
A query embedding of 384 dimensions fails to match a stored 768-dimensional vector unless both are projected into a common space.
curl -X POST http://embed-service:8080/embed \
-d '{"text": "Query text", "normalize": true}'
The normalize: true flag ensures all embeddings are unit vectors, improving cosine similarity accuracy.
A cached result may become stale as new data arrives or the LLM model is updated.
Two common patterns:
A failure mode: a cache rebuild runs every 24 hours but does not update the model_version field in the metadata. A query is served with a result from v1 of the LLM, but the embedding was computed with v2 of the model—causing semantic drift.
Queries are often normalized before embedding: lowercase, remove punctuation, remove stop words.
def preprocess(query: str) -> str:
return re.sub(r"[^\w\s]", "", query.lower().strip())
A mismatch between preprocessing in the cache and during retrieval leads to poor matches.
For example:
The two differ in punctuation and capitalization, and their embeddings may not align well.
A system may use tiered caching:
When a query arrives:
A failure occurs when Redis does not expire old entries. A user’s query from two weeks ago is still in memory, but the underlying vector database has been updated—leading to stale results.
Monitor the cache using:
A key error message appears when the cache returns a result with similarity < threshold but cached: true:
{
"output": "Best practices for scaling LLM inference",
"cached": true,
"source": "q-67890",
"similarity": 0.87,
"reason": "Query was not close enough to threshold of 0.90"
}
This indicates a misconfiguration in the similarity threshold or a mismatch in embedding model versions.
Use a log entry to capture:
query: the input textembedding_dim: the dimension of the computed embeddingcached_query: the query text used for the cache hitsimilarity: the cosine similarity between the two embeddingscache_version: the version of the cache (e.g., v3)A common debugging step: extract the top 100 cache misses and analyze which queries are most frequently missed. Often, these reveal edge cases in query preprocessing or embedding model performance.
Semantic caching is not just about storing embeddings—it is about reusing the meaning of queries across a system. It reduces latency and cost by reusing LLM outputs computed for semantically similar inputs. The strategy depends on:
The success of the system hinges on the alignment between the embedding model, the query preprocessing, and the similarity threshold—each a silent but critical factor in the performance of the entire generative AI pipeline.
This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy