As Large Language Model (LLM) applications scale to production workloads, engineering teams routinely hit two compounding bottlenecks: latency (inference times ranging from 500ms to several seconds) and cost (token-based pricing models that explode under high-throughput concurrency).
Exact-match caching fails in generative AI architectures because users rarely submit identical prompts. A query like "How do I fix a NullPointerException in Java?" and "Java NullPointerException troubleshooting steps" are semantically identical, yet standard hash-based caches treat them as distinct cache misses.
To solve this, we must build a Semantic Caching Layer. By intercepting incoming requests, calculating embedding vectors, and performing high-speed approximate nearest neighbor (ANN) searches, we can serve historically computed responses in milliseconds without hitting downstream inference APIs.
System Architecture
The following data-flow diagram illustrates how an asynchronous FastAPI gateway coordinates semantic validation before falling back to the LLM provider.
[ Client Request ]
│
▼
┌──────────────────────────────────────────────┐
│ FastAPI Semantic Gateway │
│ ├── 1. Extract & Normalize Prompt │
│ └── 2. Generate Embedding (e.g., text-emb-3)│
└──────────────────────┬───────────────────────┘
│
▼
┌──────────────────────────────────────────────┐
│ Vector Index (Redis / NumPy In-Memory) │
│ └── 3. Cosine Similarity Search (ANN) │
└──────┬───────────────────────────────┬───────┘
│ │
│ (Similarity >= Threshold) │ (Similarity < Threshold)
▼ ▼
[ Cache HIT ] [ Cache MISS ]
Return cached response Call LLM API (e.g., OpenAI)
(~15ms latency) Update Vector Index
Return fresh response
Engineering Considerations
-
Embedding Model Latency: Generating an embedding via an external API introduces overhead. For maximum efficiency, use small, highly optimized embedding models (e.g.,
text-embedding-3-smallor locally hosted ONNX models running on CPU/GPU viafastembed). - Distance Metrics: Cosine similarity is the industry standard for normalized embedding spaces. We establish a strict threshold ($\tau \ge 0.92$) to balance recall and semantic drift.
-
Async Concurrency: The gateway must be fully asynchronous (
async/await) to prevent blocking the event loop during network I/O operations with vector stores and LLM providers.
Production-Ready Implementation
Below is a complete, runnable FastAPI implementation demonstrating an async semantic caching gateway with strict error handling, Pydantic validation, and vectorized similarity matching using NumPy (easily adaptable to Redis/Qdrant in distributed environments).
from contextlib import asynccontextmanager
import logging
import os
from typing import List, Optional, Tuple
from fastapi import FastAPI, HTTPException, status
import numpy as np
from pydantic import BaseModel, Field
# Configure structured logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("SemanticGateway")
class PromptRequest(BaseModel):
prompt: str = Field(
..., min_length=3, max_length=2000, description="User query string"
)
temperature: float = Field(0.0, ge=0.0, le=2.0)
class GatewayResponse(BaseModel):
response: str
cache_hit: bool
similarity_score: Optional[float] = None
class SemanticCacheNode:
"""In-memory vector cache node demonstrating cosine similarity indexing.
In production, replace backing store with Redis Enterprise, Qdrant, or Pinecone.
"""
def __init__(self, similarity_threshold: float = 0.92):
self.threshold = similarity_threshold
self.embeddings: List[np.ndarray] = []
self.responses: List[str] = []
async def _mock_embed(self, text: str) -> np.ndarray:
"""Simulates an embedding generation call (e.g., OpenAI API).
Returns a 1538-dimensional normalized float32 vector.
"""
# Deterministic pseudo-embedding generation for demonstration purposes
np.random.seed(abs(hash(text)) % (2**32))
vec = np.random.randn(1536).astype(np.float32)
return vec / np.linalg.norm(vec)
async def search(self, query: str) -> Tuple[bool, Optional[str], float]:
query_vec = await self._mock_embed(query)
if not self.embeddings:
return False, None, 0.0
# Vectorized cosine similarity computation
matrix = np.vstack(self.embeddings)
scores = np.dot(matrix, query_vec) # Vectors are pre-normalized
best_idx = int(np.argmax(scores))
best_score = float(scores[best_idx])
if best_score >= self.threshold:
return True, self.responses[best_idx], best_score
return False, None, best_score
async def insert(self, query: str, response: str):
vec = await self._mock_embed(query)
self.embeddings.append(vec)
self.responses.append(response)
# Global cache instance initialized at startup
cache: Optional[SemanticCacheNode] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global cache
logger.info("Initializing Semantic Cache Engine...")
cache = SemanticCacheNode(similarity_threshold=0.92)
yield
logger.info("Flushing Semantic Cache Engine...")
app = FastAPI(
title="Production Semantic Cache Gateway",
version="1.0.0",
lifespan=lifespan,
)
@app.post(
"/v1/generate",
response_model=GatewayResponse,
status_code=status.HTTP_200_OK,
)
async def generate_response(payload: PromptRequest):
try:
# 1. Check Semantic Cache
is_hit, cached_answer, score = await cache.search(payload.prompt)
if is_hit:
logger.info(f"Cache HIT | Similarity: {score:.4f}")
return GatewayResponse(
response=cached_answer, cache_hit=True, similarity_score=score
)
# 2. Cache Miss: Simulate Downstream LLM Inference (e.g., GPT-4o)
logger.info(
f"Cache MISS | Similarity: {score:.4f} -> Querying LLM Engine"
)
# TODO: Replace with actual async HTTP call to OpenAI/Anthropic SDK
simulated_llm_response = f"Synthesized answer for query: '{payload.prompt}'"
# 3. Asynchronously Populate Cache
await cache.insert(payload.prompt, simulated_llm_response)
return GatewayResponse(
response=simulated_llm_response,
cache_hit=False,
similarity_score=score,
)
except Exception as err:
logger.error(
f"Gateway processing failure: {str(err)}", exc_info=True
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal infrastructure error while evaluating semantic boundary.",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
Conclusion
By integrating a semantic caching layer into your LLM routing infrastructure, you decouple application scalability from downstream API rate limits. For deep-dives into distributed system designs, container orchestration setups, and advanced AI patterns, check out my code repositories at GitHub.
Top comments (0)