Enterprise RAG Architecture: Vector Databases, Chunking & Semantic Caching
Production guide to Retrieval-Augmented Generation (RAG) infrastructure, covering Milvus/Qdrant vector databases, HNSW index tuning, hybrid sparse/dense retrieval, and Redis semantic caching.
Enterprise RAG Architecture: Vector Databases, Chunking & Semantic Caching
Section titled โEnterprise RAG Architecture: Vector Databases, Chunking & Semantic CachingโWhile Large Language Models demonstrate impressive reasoning capabilities, off-the-shelf models suffer from two critical enterprise flaws:
- Knowledge Cutoff & Stale Information: Models know nothing about your companyโs private confluence wikis, proprietary APIs, or internal architectural standards.
- Hallucinations: When an LLM lacks ground truth, it invents plausibly sounding but false facts.
Retrieval-Augmented Generation (RAG) solves this by retrieving precise, validated private enterprise documents from a vector database and injecting them into the LLMโs prompt context window in real time.
1. The Production RAG Pipeline
Section titled โ1. The Production RAG Pipelineโ[ Private Documentation (PDFs, Markdown, Confluence) ] โ โผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Ingestion & Indexing Pipeline โโ โโ Smart Chunking (Recursive character splitting) โโ โโ Embedding Generation (e.g. text-embedding-3-large) โโ โโ Vector Store (Milvus / Qdrant with HNSW Index) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ[ Live User Query ] โโโโโโโดโโโโโโ> [ Semantic Cache (Redis) ] โ (Cache Miss) โผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ Hybrid Retrieval & Re-Ranking Engine โโ โโ Dense Vector Search (Cosine Similarity) โโ โโ Sparse Keyword Search (BM25 for exact codes/IDs) โโ โโ Cross-Encoder Re-Ranker (Cohere / BGE-Reranker) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โผ (Top 3 Context Chunks)โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ LLM Generation (vLLM / Claude / OpenAI) โโ "Based on the provided context, answer the query..." โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ2. Choosing & Tuning Vector Databases: Milvus vs Qdrant vs pgvector
Section titled โ2. Choosing & Tuning Vector Databases: Milvus vs Qdrant vs pgvectorโ| Vector Engine | Architecture | Best Production Use Case | Index Algorithm |
|---|---|---|---|
| Qdrant | Rust-based, cloud-native container | High-speed semantic search, payload metadata filtering | HNSW (Hierarchical Navigable Small World) |
| Milvus | Distributed microservices on Kubernetes | Enterprise scale (>100M to Billions of vectors) | IVF-PQ, DiskANN, GPU-accelerated indexing |
| pgvector | PostgreSQL extension | Small to medium projects (<1M vectors) already using Postgres | HNSW / IVFFlat inside relational DB |
2.1 Qdrant Vector Search Python Implementation
Section titled โ2.1 Qdrant Vector Search Python Implementationโfrom qdrant_client import QdrantClientfrom qdrant_client.models import Distance, VectorParams, PointStruct
# Connect to production Qdrant cluster on Kubernetesclient = QdrantClient(url="http://qdrant.database.svc.cluster.local:6333")
COLLECTION_NAME = "enterprise_runbooks"
# Create collection with Cosine similarityclient.recreate_collection( collection_name=COLLECTION_NAME, vectors_config=VectorParams(size=1536, distance=Distance.COSINE))
def search_production_context(query_vector: list[float], team_tag: str, top_k: int = 5): """Performs HNSW vector search with strict metadata filtering.""" search_result = client.search( collection_name=COLLECTION_NAME, query_vector=query_vector, query_filter={ "must": [ {"key": "team", "match": {"value": team_tag}} ] }, limit=top_k ) return [hit.payload["content"] for hit in search_result]3. Cost & Latency Optimization: Semantic Caching with Redis
Section titled โ3. Cost & Latency Optimization: Semantic Caching with RedisโIn production systems, users repeatedly ask semantically identical questions (e.g., โHow do I connect to the production VPN?โ vs โSteps to access prod VPNโ).
Sending every duplicate query to external embedding models and LLM inference endpoints wastes thousands of dollars. A Semantic Cache computes query similarity and returns cached answers instantly:
import redisimport numpy as np
# Redis Enterprise / Redis Stack with vector capabilityr = redis.Redis(host="redis-cache.caching.svc", port=6379)
def get_semantic_cached_response(query_embedding: list[float], threshold: float = 0.96): """Checks Redis for previously answered queries with >96% semantic similarity.""" query_bytes = np.array(query_embedding, dtype=np.float32).tobytes()
# Query Redis vector index q = "*=>[KNN 1 @vector $vec AS score]" res = r.ft("cache_idx").search(q, query_params={"vec": query_bytes})
if res.docs: top_doc = res.docs[0] similarity = 1.0 - float(top_doc.score) if similarity >= threshold: print(f"[CACHE HIT] Returning instant 5ms cached LLM response (Similarity: {similarity:.3f})") return top_doc.answer
print("[CACHE MISS] Executing full RAG retrieval pipeline...") return None4. Production Best Practices for RAG Operations
Section titled โ4. Production Best Practices for RAG Operationsโ- Avoid Naive Fixed-Character Chunking: Chopping text arbitrarily at 500 characters breaks code blocks and sentence semantics in half. Use Semantic Chunking or recursive markdown header splitting (
MarkdownHeaderTextSplitter) so sections stay cohesive. - Always Implement Hybrid Search: Vector embeddings are great at high-level semantic meaning, but terrible at matching specific UUIDs, error codes (
ERR_CONN_REFUSED_503), or exact server hostnames. Always combine dense vector search with sparse BM25 keyword search. - Monitor Context Window Cost: Calculate and log token consumption using Prometheus. Injecting 50 documents into an LLM context window causes severe latency degradation and skyrocketing token costs.