Architecture
A production RAG pipeline separates offline document normalization and parent-child hierarchical indexing cleanly from a multi-stage online retrieval funnel—executing parallel ACL-filtered dense HNSW and lexical BM25 queries fused via Reciprocal Rank Fusion (RRF), refining top candidates with cross-encoder or ColBERT rerankers, and gating generation strictly on verified source spans.
Naive single-pass vector RAG fails predictably as corpora grow past 50,000 heterogeneous enterprise documents: arbitrary fixed character chunkers shear Markdown tables and SQL snippets mid-row, pure bi-encoder cosine similarity drops exact alphanumeric error codes (ERR_OOM_NVLINK_42 or SKU identifiers), and un-reranked top-20 context dumps flood frontier attention with conflicting or middle-buried filler passages. Staging ingestion, hybrid recall fusion, precision reranking, and deterministic citation checks keeps precision high at bounded sub-80 ms retrieval tail latency.
Hybrid Search: Dense Vector vs BM25 Sparse (RRF)
1. Structure-Aware Chunking & Mathematical Score Normalization (RRF)
Effective production pipelines decouple retrieval unit size from generation context size:
- Search Granularity (
250–400tokens): Small cohesive subsections (prepend H1 > H2 > H3 breadcrumb headers) yield sharp vector representations with low topical dilution. - Generation Granularity (
900–1,200tokens parent): When multiple small child chunks score well inside the same section, swap in their contiguous Parent Document Section once cleanly before generation—preserving surrounding definitions, table headers, and preconditions without context duplication.
Because dense cosine similarity ( narrow cluster centered near 0.78–0.86) and unbounded BM25 lexical TF-IDF scores () follow incompatible scale distributions, Reciprocal Rank Fusion (RRF) fuses rankings strictly by ordinal rank stability without fragile min-max weight calibration:
Combines rank positions across dense vector search and sparse lexical search into a unified relevance score.
Worked Retrieval Latency & Memory Budget (10M Chunks, 1536-d Float16)
Budgeting a single 10M-chunk corpus inside PostgreSQL pgvector or Qdrant with HNSW (M=16):
- Unquantized HNSW FP16 Vectors + Links: . Applying Scalar Int8 (
SQ8) cuts vector payload in half (~16.6 GBresident in RAM) with asymmetric FP16 rescoring recovering> 99%recall@10. - Stage Latency Breakdown:
12 msHNSW +5 msparallel BM25 +< 1 msRRF merge +28 msbatched BGE cross-encoder (40candidates350tokens on L4 GPU) =~46 mstotal retrieval p95.
2. Architecture Comparison: Vector Search vs Lexical vs Hybrid Reranked
3. RRF Fusion + Cross-Encoder Fallback Pipeline in Python
pythonfrom collections import defaultdictdef reciprocal_rank_fusion(ranked_lists: list[list[str]],k: int = 60,list_weights: list[float] | None = None,) -> list[tuple[str, float]]:"""Fuse arbitrary ranked document ID lists smoothly using weighted RRF."""weights = list_weights or [1.0] * len(ranked_lists)scores: dict[str, float] = defaultdict(float)for weight, doc_ids in zip(weights, ranked_lists):seen: set[str] = set()for rank_idx, doc_id in enumerate(doc_ids, start=1):if doc_id in seen:continueseen.add(doc_id)scores[doc_id] += weight * (1.0 / (k + rank_idx))return sorted(scores.items(), key=lambda kv: kv[1], reverse=True)def retrieve_with_rerank_degrade(dense_hits: list[str],bm25_hits: list[str],reranker_fn,top_k_final: int = 8,) -> list[str]:"""Combine RRF candidates and degrade gracefully to raw RRF if GPU reranker stalls."""fused = [doc_id for doc_id, _ in reciprocal_rank_fusion([dense_hits, bm25_hits], k=60)][:40]try:reranked = reranker_fn(fused, timeout_ms=45)return reranked[:top_k_final]except TimeoutError:return fused[:top_k_final] # Bounded non-fatal degradation keeps P99 fastfused_ids = retrieve_with_rerank_degrade(dense_hits=["doc_a", "doc_b", "doc_c"],bm25_hits=["doc_b", "doc_d", "doc_a"],reranker_fn=lambda ids, timeout_ms: list(ids),top_k_final=3,)assert fused_ids[:2] == ["doc_b", "doc_a"]
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
Index cohesive 300-token breadcrumb child chunks mapped to 1,000-token parent blocks. | Context recall@5 >= 92% without truncating tables or code | Ingestion parser or embedding swap |
Pair HNSW + BM25 via RRF (k = 60), then refine top-40 candidates with GPU cross-encoder. | Ablation proving +8%–15% nDCG@5 uplift over single dense retrieval | Precision drop on jargon or high p99 latency |
| Enforce tenant ACL pre-filters & deduplicate parent chunks prior to prompt packing. | Zero unauthorized cross-tenant leakage tests + context budget <= threshold | New tenant isolation policy |
Alternatives and trade-offs
- Single Dense HNSW Vector Search vs. RRF Hybrid + Cross-Encoder Reranking: Pure dense retrieval minimizes latency (
< 15 ms) for paraphrased queries yet struggles on exact SKUs, UUIDs, and error codes; hybrid BM25 + HNSW + top-40 reranking maximizes recall and precision with bounded40–120 msGPU overhead and safeRRFtimeout fallback.
Failure modes
- Fixed-size naive character slicing: Cuts Markdown pipe tables, JSON blocks, and negative clauses (
"Do NOT apply when...") in half, inverting retrieved answers. - Pure dense retrieval missing exact error IDs or numbers: Bi-encoders compress syntax into smooth topics, causing
HTTP 429vsHTTP 422confusion without BM25 lexical fusion. - Unbounded reranker timeouts blowing user P99: Synchronous cross-encoder bottlenecks hang the entire chat endpoint under burst load unless backed by tight timeouts falling back cleanly to
RRFrank. - Duplicate parent chunk explosion: Returning
5adjacent250-token sub-chunks from the same single PDF page wastes80%of context slots instead of deduplicating parent spans cleanly.
Operational checklist
- Structure-aware splitter keeps tables, fenced code, and section heading breadcrumbs intact per chunk.
- Dense (
HNSW) + sparse (BM25) queries execute concurrently in parallel under ACL pre-filters. -
RRF (k=60)deduplicates candidate IDs cleanly and caps reranker pool at30–50items. - Graceful reranker timeout degradation preserves answer SLAs during GPU spikes.
Connected Practice
- Labs: /labs/rag-pipeline-visualizer
- System breakdowns: /systems/inside-vllm
Sources
- Production RAG primary references:
rag-paper,colbertv2-santhanam-2021,hnsw-malkov-yashunin-2016,pgvector-docs
Step through live KV-cache block paging
Inspect virtual-to-physical VRAM page tables, Copy-on-Write forks, and internal fragmentation in the PagedAttention simulator.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
