FullStack AI Hub
Studio
Reference architecture

Production RAG Reference Architecture & Retrieval Pipeline Guide

Production RAG architecture covering structure-aware parent-child chunking, HNSW + BM25 hybrid retrieval, Reciprocal Rank Fusion (RRF), cross-encoder reranking, and grounding checks.

18 minVerified 2026-11-254 primary sources
Production RAG Reference Architecture & Retrieval Pipeline Guide
On This Page

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.

Document ingestion & semantic chunking
Dual embedding (Dense HNSW + Sparse BM25)
Hybrid retrieval execution
Reciprocal Rank Fusion (RRF) score normalization
Cross-encoder re-ranking top-K filter
Context injection into LLM generation prompt
Conceptual teaching model synthesized from:Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksColBERTv2: Effective and Efficient Retrieval via Lightweight Late InteractionEfficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphspgvector Documentation

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)

Mode: HYBRID (α = 0.50)
BM25 Sparse (Exact) · 0.50Dense Vector (Semantic) · 0.50
α = 0.0 (Pure BM25)α = 0.5 (Balanced RRF)α = 1.0 (Pure Dense)
Query: "CUDA_ERROR_OUT_OF_MEMORY"Dynamically Re-Ranked by RRF Score
#1
CUDA Stream Synchronization and Memory Pool CompactionDense Rank: #3 · Sparse Rank: #2
16.001
#2
vLLM PagedAttention Kernel Performance Optimization GuideDense Rank: #2 · Sparse Rank: #4
15.877
#3
Understanding GPU Memory Leaks & VRAM Paging in LLMsDense Rank: #1 · Sparse Rank: #7
15.6594
#4
Error Symbol: "CUDA_ERROR_OUT_OF_MEMORY" in allocator.cppDense Rank: #8 · Sparse Rank: #1
15.5497Exact Symbol
Top RankedSemantic Doc
RRF Constant kk = 60
Dense Weight α0.50
Sparse Weight0.50

1. Structure-Aware Chunking & Mathematical Score Normalization (RRF)

Effective production pipelines decouple retrieval unit size from generation context size:

  • Search Granularity (250–400 tokens): Small cohesive subsections (prepend H1 > H2 > H3 breadcrumb headers) yield sharp vector representations with low topical dilution.
  • Generation Granularity (900–1,200 tokens 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 ([0,1][0, 1] narrow cluster centered near 0.78–0.86) and unbounded BM25 lexical TF-IDF scores ([0,35+][0, 35+]) follow incompatible scale distributions, Reciprocal Rank Fusion (RRF) fuses rankings strictly by ordinal rank stability without fragile min-max weight calibration:

Reciprocal Rank Fusion (RRF) Score Equation
Mathematical Formulation
RRF_Score(d∈D)=∑m∈M1k+rm(d)RRF\_Score(d \in D) = \sum_{m \in M} \frac{1}{k + r_m(d)}

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: 107×(1536×2 B+16×2×4 B)≈32.0 GB RAM10^7 \times (1536 \times 2\text{ B} + 16 \times 2 \times 4\text{ B}) \approx 32.0\text{ GB RAM}. Applying Scalar Int8 (SQ8) cuts vector payload in half (~16.6 GB resident in RAM) with asymmetric FP16 rescoring recovering > 99% recall@10.
  • Stage Latency Breakdown: 12 ms HNSW + 5 ms parallel BM25 + < 1 ms RRF merge + 28 ms batched BGE cross-encoder (40 candidates ×\times 350 tokens on L4 GPU) = ~46 ms total retrieval p95.
Submit user query to HNSW dense vector index
Submit user query to BM25 sparse keyword index
Extract top-N candidates from dense & sparse lists
Compute Reciprocal Rank Fusion (RRF) scores
Filter top-K candidates to cross-encoder re-ranker
Conceptual teaching model synthesized from:Retrieval-Augmented Generation for Knowledge-Intensive NLP TasksColBERTv2: Effective and Efficient Retrieval via Lightweight Late InteractionEfficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphspgvector Documentation

2. Architecture Comparison: Vector Search vs Lexical vs Hybrid Reranked

Retrieval Indexing Architecture Trade-Off Matrix
No matching records

3. RRF Fusion + Cross-Encoder Fallback Pipeline in Python

python
from collections import defaultdict
​
​
def 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:
continue
seen.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 fast
​
​
fused_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

DecisionRequired evidenceReview trigger
Index cohesive 300-token breadcrumb child chunks mapped to 1,000-token parent blocks.Context recall@5 >= 92% without truncating tables or codeIngestion 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 retrievalPrecision 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 <= thresholdNew 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 bounded 40–120 ms GPU overhead and safe RRF timeout 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 429 vs HTTP 422 confusion 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 RRF rank.
  • Duplicate parent chunk explosion: Returning 5 adjacent 250-token sub-chunks from the same single PDF page wastes 80% 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 at 30–50 items.
  • Graceful reranker timeout degradation preserves answer SLAs during GPU spikes.

Connected Practice

Sources

  • Production RAG primary references: rag-paper, colbertv2-santhanam-2021, hnsw-malkov-yashunin-2016, pgvector-docs
Interactive Simulator

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.

Weekly Engineering Dispatch

Subscribe to Engineering Briefings

Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.