Design a Production RAG Engine with Citations and Strict Access Control
Machine LearningModel answerLast updated
Design, optimize, and systematically evaluate an enterprise RAG system that processes heterogeneous documents, handles ACLs, and guarantees zero stale citations under high query throughput.
You are tasked with designing an enterprise-grade Retrieval-Augmented Generation (RAG) engine for high-reliability question answering over internal corporate document ecosystems (PDFs, Markdown, wiki pages, ticket history, and API specifications). Users submit natural-language queries via an interactive interface and expect grounded responses containing verifiable citations to source passages.
Design the end-to-end platform, detail key architectural choices for low-latency high-precision serving, and define a comprehensive evaluation framework covering every pipeline component.
Key Requirements
- Architecture & Pipeline split: Define the asynchronous ingestion/indexing pipeline and the synchronous real-time inference loop.
- Ingestion & Parsing: Explain layout-aware document extraction (handling tables, multi-column PDFs, code blocks, and change detection).
- Chunking Strategy: Detail structural and sliding-window strategies, contextual metadata enrichment, and parent-child document strategies.
- Retrieval & Indexing: Cover dense embeddings, BM25 lexical indexing, dynamic hybrid search, and Reciprocal Rank Fusion (RRF).
- Reranking: Discuss cross-encoder post-processing, latency trade-offs, and scoring calibration.
- Generation & Grounding: Construct the prompt framing, context ordering ("lost-in-the-middle" mitigation), citation generation, and hallucination guardrails (e.g., NLI checks, confidence gating).
- Freshness & Life Cycle: Explain mutation handling (updates, deletes, versioning) to guarantee zero post-deletion retrieval leaks.
- Security & Access Control: Enforce granular access control lists (ACLs) within search without exposing forbidden document metadata or existence.
- Evaluation Plan: Detail offline and online evaluation metrics (Hit@K, Recall@K, nDCG, Faithfulness, Citation Recall/Precision) per pipeline component, along with synthetic label bootstrapping techniques.
Constraints & Operational Bounds
- Corpus Scale: 5 to 10 million text chunks (~500 tokens each).
- Latency SLA: p95 $< 2.0\text{ seconds}$ to first stream token.
- Freshness SLA: Document edits and soft-deletes reflected in retrieval within $< 3\text{ minutes}$.
- Security: Hard tenant and document-level ACL isolation; no leak of unpermitted titles or metadata.
- Safety: Mandatory citations; graceful abstention ("I cannot answer based on available documentation") when evidence is insufficient.
Hints
Hint 1
Establish clear system parameters up front: QPS, chunk index sizing, and GPU/CPU latency budgets for vector search vs cross-encoder reranking.
Hint 2
Address the security constraint early: push ACL filtering into the vector/lexical index execution plan rather than applying post-retrieval filters to prevent empty candidate pools.
Hint 3
For evaluation, separate component-level retrieval metrics (Hit-Rate, nDCG) from end-to-end generation quality metrics (Faithfulness, Citation Precision) and describe how to bootstrap synthetic query-chunk-answer triplets using an LLM.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Scale and Latency Budget
To anchor the system design, we assume the following operational numbers:
- Corpus Size: $5 \times 10^6$ chunks ($\approx 2.5 \times 10^9$ total tokens).
- Dense Vector Footprint: 1024-dimensional
fp32embeddings $\approx 20\text{ GB}$. Withint8scalar quantization, memory drops to $\approx 5\text{ GB}$ per index replica, fitting easily in RAM. - Throughput: 50 Peak Query QPS; ~25,000 document mutations daily.
- P95 Latency SLA (< 2.0s to first token):
- Query Processing & Context Expansion: $100\text{ ms}$
- Hybrid Retrieval (BM25 + Dense ANN): $80\text{ ms}$
- Cross-Encoder Reranking (top-50 candidates): $150\text{ ms}$
- Document Store Retrieval + Prompt Framing: $70\text{ ms}$
- Initial LLM Token Generation (TTFT): $1,000\text{ ms}$
- Reserve Buffer: $600\text{ ms}$
2. High-Level System Architecture
The architecture is divided into two distinct planes: an Asynchronous Ingestion Plane (optimizing freshness and metadata extraction) and a Synchronous Query Plane (optimizing latency, precision, and security).
[ ASYNCHRONOUS INGESTION PLANE ]
Source Docs ──> Event Bus ──> Layout Parser ──> Structural Chunker ──> Batch Embedder
(Wiki, PDF) (Kafka) (LayoutLMv3) (Parent-Child) (GPU Cluster)
│
┌────────────────────────────────────────┴──────────────────────────────────────┐
▼ ▼ ▼
[ Vector Index (HNSW) ] [ Lexical Index (BM25) ] [ Document & ACL Store ]
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
[ SYNCHRONOUS QUERY PLANE ]
User Query ──> Query Engine ──> ACL Filter Engine ──> Hybrid Search ──> RRF Fusion ──> Cross-Encoder ──> Context Assembly ──> Streaming LLM
(HyDE/Rewrite) (User Token) (Dense + BM25) (k=60) (Reranker) (Attribution Map) (Grounded Gen)
Ingestion Plane (Async)
- Connectors & Change Data Capture (CDC): Webhooks and polling track document diffs via SHA-256 hashes.
- Layout Parsing: Structural segmentation via vision-text layout models converts visual positioning into unified Markdown ASTs.
- Chunking & Context Injection: Structural splitting appends ancestor hierarchy headers to each node.
- Embedding Generation: Batched processing populates both vector and lexical indices.
- Transactional Persistence: Updates atomic pointers across indices and metadata stores.
Query Plane (Sync)
- Query Processing: Resolves chat history references and rewrites queries; generates synthetic expansions.
- Filtered Hybrid Retrieval: Concurrently queries HNSW vector search and BM25 lexical search with single-stage metadata/ACL filtering.
- Fusion & Reranking: Applies Reciprocal Rank Fusion (RRF) to merge candidate lists, then scores the top-50 items via a cross-encoder model.
- Security & Liveness Verification: Validates that candidates remain live in the transactional store.
- Context Assembly & Generation: Constructs structured prompts with context compression and streams answers with verified citations.
3. Ingestion, Parsing, and Chunking Strategies
Parsing Heterogeneous Formats
Unstructured documents present structural loss risks when flattened to raw string buffers:
- PDFs & Scanned Documents: Utilizes a visual layout model (e.g.,
LayoutLMv3) to parse columns, headers, and footers correctly. OCR outputs capture bounding boxes alongside text confidence scores. - Tables: Serialized into Markdown or HTML structures. Each table row is prepended with its column schema (
[Table: Spec_Sheet | Row: 4 | Field: Max_Payload = 50kg]) to preserve semantic meaning when chunked independently. - Code & API Specs: Parsed via abstract syntax tree (AST) splitters to preserve function definitions, type signatures, and docstrings intact.
Structural Chunking with Parent-Child Hierarchy
Fixed-size token windowing frequently breaks semantic units. Instead, we use a hybrid structural strategy:
- Primary Split: Split on DOM or AST boundaries (e.g., Markdown headers
#,##,###). - Secondary Split: If a section exceeds 500 tokens, apply a overlapping sliding window (400 tokens with a 50-token stride).
[ Parent Context: Section "3.1 Database Migration Protocols" ] <-- Sent to LLM Context
├── [ Child Chunk 1: Step 1 & 2 (150 tokens) ] <-- Embedded for Search
└── [ Child Chunk 2: Step 3 & 4 (180 tokens) ] <-- Embedded for Search
To counter retrieval context fragmentation, we use Parent-Child Chunking:
- Search Target: Embed fine-grained Child Chunks (150–250 tokens) for high retrieval precision.
- Generation Payload: Map retrieved child hits to their Parent Blocks (800–1200 tokens) before assembling the LLM context.
Contextual Header Injection
To prevent orphan chunks (e.g., a chunk containing only "Step 3: Run kubectl apply"), every chunk's text representation is prepended with its structural genealogy:
$$\text{Chunk Text} = \text{Document Title} \gg \text{Section Path} \gg \text{Raw Text}$$
$$\text{Example: } \text{"Kafka Operations Guide} \gg \text{Cluster Recovery} \gg \text{Broker Failure} \gg \text{Run script A"}$$
4. Hybrid Retrieval, Reranking, and ACL Filtering
Hybrid Retrieval Pipeline
Dense retrieval excels at semantic mapping but misses exact alphanumerics (e.g., ERR_8091, v4.12.0). BM25 complements vector search by matching precise lexical tokens.
Query ──┬──> Dense Search (HNSW + Quantized Vectors) ──> Top-100 Candidates ──┐
│ ├──> RRF Fusion (k=60) ──> Top-50 ──> Cross-Encoder
└──> Sparse Search (BM25 Index) ─────────────> Top-100 Candidates ──┘
-
Reciprocal Rank Fusion (RRF): Merges vector and BM25 candidate sets ($R_{\text{dense}}$ and $R_{\text{sparse}}$) without requiring score normalization:
$$S_{\text{RRF}}(d \in D) = \sum_{m \in {\text{dense}, \text{sparse}}} \frac{1}{k + r_m(d)}$$
where $k=60$ dampens the impact of top-ranked outliers.
-
Cross-Encoder Reranking: Passes the merged top-50 candidates through a high-capacity cross-encoder (e.g.,
bge-reranker-large). Cross-encoders process query-document pairs simultaneously, capturing full cross-attention dependencies:$$\text{Score}(Q, D_i) = \text{Sigmoid}\left(\text{Transformer}_{\text{cls}}(Q \oplus D_i)\right)$$
Only candidates scoring above a tuned relevance threshold ($\tau \ge 0.45$) proceed to context generation.
Zero-Leak Access Control (ACL) Enforcement
Applying security filters after retrieval can lead to empty candidate sets if the top hits are disallowed. Conversely, leaking document titles in responses violates data boundaries.
[ Filtered Vector Search Plan ]
User Context: {User: "alice@co", Groups: ["engineering", "ops-team"]}
│
▼
[ HNSW Index Node Traversal ] ──> Check Bitset Array ──> [ Allow Access? ]
│
┌─────────────────┴─────────────────┐
▼ ▼
(Yes: Evaluate Vector Dist) (No: Prune Branch)
-
Single-Stage In-Index Filtering: User identity tokens are resolved to permission bitsets (e.g.,
groups: ["eng-core", "sec-ops"]). Vector and BM25 search engines enforce these bitsets directly during index traversal:$$\text{Target Set} = { d \in \text{Index} \mid \text{ACL}(d) \cap \text{UserGroups} \neq \emptyset }$$
-
Metadata Redaction: Document titles, headers, and paths are stripped from error logs and diagnostic steps whenever access checks fail.
5. Freshness and Lifecycle Management
To maintain a strict updates SLA ($<3\text{ minutes}$) and prevent deleted data from being cited:
[ Doc Delete Event ] ──> Document Store (Set Tombstone status=deleted)
│
├──> Query Time Check (Validates document status before LLM prompt)
│
└──> Async Index Worker (Deletes vectors from HNSW and BM25 indices)
- Soft Delete Tombstoning: When a document is marked for deletion, an atomic update sets
status: deletedin the primary key-value storage engine within milliseconds. - Dual-Gate Liveness Validation:
- Index Gate: Async background tasks sweep and remove vectors from HNSW and BM25 indices.
- Query Gate: The query pipeline checks every candidate's key against the primary store before assembling the prompt context. If a chunk's tombstone is active, it is discarded immediately.
- Version Superceding: Edits assign an incremented
doc_version. Upon successful insertion of new chunks, the system updatescurrent_version_idpointers, making older chunk embeddings un-retrievable.
6. Grounded Generation, Guardrails, and Fallback
Retrieved Chunks ──> Context Compressor ──> Prompt Assembly ──> LLM Generation Stream
│
┌───────────────────────────────────────────────────────────────────┘
▼
[ Post-Generation Verification ]
├── Citation Verification: Validate [n] spans against source text
├── Entailment Guardrail: Run NLI model over (Claim, Context)
└── Confidence Evaluator: If Score < Tau ──> Trigger Fallback / Abstention
System Prompt Architecture
SYSTEM INSTRUCTION:
You are an enterprise knowledge assistant. Answer the user's question using ONLY the provided source context blocks.
CONSTRAINTS:
1. Every factual statement MUST end with an inline citation bracket referencing the Source ID (e.g., [1]).
2. Do NOT extrapolate or introduce external facts.
3. If the provided context lacks sufficient evidence to answer fully, state: "I am unable to answer based on the available documentation."
SOURCE CONTEXT:
[1] Title: Kafka Failover Procedure (Version: 3)
Path: Infrastructure > Messaging > Recovery
Text: Step 1: Scale down deployment via `kubectl scale deployment/kafka --replicas=0`.
[2] Title: DB Migration Policy (Version: 1)
Path: Infrastructure > Database
Text: All schema alterations require DBA approval via ticket.
Grounding & Citation Mechanisms
-
Direct Span Mapping: The LLM is restricted to generating numerical tokens (e.g.,
[1]). The application layer maps these indices back to metadata structures containing document IDs, versions, and deep-link targets. -
Entailment Verification: An lightweight NLI cross-encoder runs concurrently over the output stream, checking candidate claims against source context segments:
$$\text{Entailment Check}(C_i, S_j) \rightarrow {\text{Entailment}, \text{Neutral}, \text{Contradiction}}$$
Claims marked as
NeutralorContradictionare stripped from the response or trigger an abstention message.
Fallback Cascade
- Low Retrieval Score ($\text{Rerank Score} < 0.45$): Skip generation entirely and return an abstention response along with suggested alternative topics.
- Ambiguous Context Hits: If retrieved results match distinct entities (e.g., two projects named "Atlas"), the system prompts the user to select the intended scope before generating an answer.
7. End-to-End Evaluation Framework
Evaluating a production RAG system requires measuring each component independently to isolate failure modes, alongside end-to-end user evaluation.
+-----------------------------------------------+
| Evaluation Framework Architecture |
+-----------------------------------------------+
|
+-----------------------------------------+-----------------------------------------+
| | |
v v v
+------------------+ +------------------+ +------------------+
| Component Evals | | End-to-End Evals | | Label Bootstrapping|
+------------------+ +------------------+ +------------------+
| * Parsing | | * Answer Correct | | * LLM Generation |
| * Chunking | | * Faithfulness | | * Filtering |
| * Retrieval | | * Citation Prec/ | | * Heuristic Eval |
| * Reranking | | Recall | +------------------+
+------------------+ +------------------+
Stage-by-Stage Evaluation Plan
| Stage | Evaluated Component | Core Metrics | Primary Failure Modes | Label Generation Methodology |
|---|---|---|---|---|
| Stage 1 | Parsing & Layout | Text Extraction Precision, Table Structure Alignment Score | Loss of multi-column order, broken visual context | Human annotation on 200 benchmark PDF/Image samples |
| Stage 2 | Chunking | Chunk Answerability Ratio, Structural Boundary Integrity | Mid-sentence truncations, split tables/code blocks | Rule-based semantic structural linting |
| Stage 3 | Retrieval | Hit@K, Recall@K, Mean Reciprocal Rank (MRR) | Dense model vocabulary drift, exact keyword misses | Bootstrapped query-chunk pairs from synthetic pipelines |
| Stage 4 | Reranking | Normalized Discounted Cumulative Gain (nDCG@10) | Misordering irrelevant context ahead of true answers | Human relevance judgments (0-3 rating scale) |
| Stage 5 | Generation & Faithfulness | Faithfulness Rate, Answer Relevance, Citation Precision/Recall | Hallucinations, unsourced statements, inaccurate citations | Auto-eval using LLM-as-a-Judge with NLI confirmation |
| Stage 6 | End-to-End System | Task Completion Success Rate, Abstention Accuracy | Premature abstentions, answering out-of-scope queries | Human feedback logs (Thumbs up/down, user flags) |
Metric Formulations
$$\text{Recall@K} = \frac{|\text{Retrieved Chunks@K} \cap \text{Relevant Chunks}|}{|\text{Relevant Chunks}|}$$
$$\text{nDCG@K} = \frac{\text{DCG@K}}{\text{iDCG@K}}, \quad \text{where } \text{DCG@K} = \sum_{i=1}^{K} \frac{2^{\text{rel}_i} - 1}{\log_2(i + 1)}$$
$$\text{Citation Precision} = \frac{|\text{Citations Supporting Generated Claim}|}{|\text{Total Generated Citations}|}$$
$$\text{Faithfulness Rate} = \frac{|\text{Claims Entailed by Cited Passage}|}{|\text{Total Generated Claims}|}$$
Bootstrapping Evaluation Labels (Without Golden Sets)
When gold-standard reference datasets are unavailable, generate synthetic evaluations using a strong model (e.g., GPT-4o):
[ Synthetic Data Generator ]
│
┌──────────────────────────────────────┴──────────────────────────────────────┐
▼ ▼
[ Single-Chunk Questions ] [ Multi-Chunk Questions ]
(Extract key facts -> Generate queries) (Link related documents -> Generate queries)
│ │
└──────────────────────────────────────┬──────────────────────────────────────┘
▼
[ Query Filtering & Deduplication ]
(Validate answerability against context)
│
▼
[ Golden Eval Dataset ]
- Fact-To-Query Generation: Sample source chunks, prompt the LLM to extract factual propositions, and formulate corresponding natural language queries:
Prompt: "Given the chunk below, generate 3 user queries that can be answered entirely by this text." - Multi-Hop Query Generation: Link structurally related chunks (e.g., Parent section + Child node) to build queries requiring multi-document synthesis.
- Automated Verification: Cross-validate generated pairs by running them through an isolated instance of the RAG system. Reject generated queries where the reference chunk is missing from top candidates or the generation step fails validation.
8. Concrete Scenarios & Architecture Trade-offs
Follow-up 1: Upgrading Embedding Models Without Downtime
Problem: Replacing the active embedding model requires re-indexing millions of documents, which can disrupt active searches.
Solution: Dual-Index Blue-Green Migration
- Provision Green Index: Instantiate a parallel index schema configured for the new embedding dimensionality.
- Dual Ingestion: Route incoming CDC document modifications to both the active (Blue) and new (Green) ingestion queues.
- Historical Backfill: Run GPU batch jobs to re-embed the historical corpus into the Green Index.
- Validation: Run offline evaluation benchmarks (Hit@K, MRR) against the Green Index.
- Traffic Cutover: Atomically switch query-plane reading flags to point to the Green Index, then decommission the Blue Index.
Incoming Writes ──> Splitter ──┬──> Active Index (Blue) <── Read Queries (Before Cutover)
└──> Target Index (Green) <── Read Queries (After Cutover)
Follow-up 2: Optimizing Latency for Multi-Hop vs. Single-Fact Queries
Problem: Multi-hop queries require retrieving diverse context paths, whereas simple lookup queries prioritize low latency and precise keyword matching.
Solution: Adaptive Query Routing A low-latency query classifier assesses intent before execution:
User Query ──> Intent Classifier (10ms)
│
├──> Single-Fact Lookup ──> Hybrid Search (Top-20) ──> Rerank ──> Stream Answer
│
└──> Multi-Hop/Synthesize ──> Query Decomposition ──> Parallel Sub-Retrievals ──> Fusion ──> Stream Answer
- Path A (Single-Fact): Targets narrow candidate pools ($K=20$), skips query expansion, and uses light reranking to keep latency under $800\text{ ms}$.
- Path B (Multi-Hop / Complex): Decomposes queries into sub-queries, executes parallel vector retrievals, and aggregates results via RRF before context assembly.
Follow-up 3: Validating and Calibrating an LLM-as-a-Judge
Problem: LLM-based evaluators can introduce position bias, verbosity bias, and scoring drift.
Solution: Alignment and Calibration Protocol
- Human Benchmark Set: Annotate a representative sample ($N=500$) of response-context pairs with human relevance ratings.
- Bias Mitigation:
- Position Bias: Swap context ordering during verification rounds to check for position-based preference changes.
- Verbosity Bias: Normalize scores against response length metrics.
- Correlation Tracking: Compute Cohen’s Kappa ($\kappa$) or Pearson’s $r$ between human labels and LLM judge ratings. Require $\kappa \ge 0.75$ before deploying an LLM evaluator to production monitoring pipelines.
Raw Response + Context ──> [ Original Order Pass ] ──┐
├──> Cohen's Kappa (κ) Check vs Human Labels
Raw Response + Context ──> [ Reversed Order Pass ] ──┘
9. Operational Summary Checklist
| Operational Dimension | Strategy / Implementation | Target Metric |
|---|---|---|
| Ingestion Pipeline | Structural AST Parsing + Metadata Lineage Prefixing | Document ingestion lag $< 3\text{ minutes}$ |
| Security Layer | Single-Stage Bitset Authorization Filtering | Zero cross-tenant data exposure |
| Search Engine | Hybrid BM25 + HNSW Quantized Vector Search with RRF | Hit@10 $\ge 88%$ |
| Post-Processing | Cross-Encoder Reranking + Score Thresholding ($\tau \ge 0.45$) | nDCG@10 $\ge 0.82$ |
| Generation Engine | Structural Prompting + Concurrent Entailment Verification | Faithfulness Rate $\ge 98%$ |
| System Reliability | Automated Abstention + Blue-Green Re-indexing | P95 Latency $< 2.0\text{ seconds}$ |