Design an Enterprise Knowledge Base RAG Platform
System DesignModel answerLast updated
Architect an end-to-end Retrieval-Augmented Generation system handling millions of internal documents, low latency, real-time updates, and strict document-level security.
Enterprise Knowledge Base Retrieval-Augmented Generation (RAG) System
Design a high-throughput, enterprise-grade RAG platform that empowers employees to query a corporate knowledge repository (PDFs, Confluence pages, internal chat logs, Notion documents).
Functional Requirements
- Grounded Question Answering: Provide precise answers based strictly on internal company sources, complete with traceable inline citations (document title, section, link).
- Near-Real-Time Ingestion: Document additions, modifications, or deletions must be indexed and searchable within 5 minutes.
- Strict Document-Level Authorization (ACLs): Users must only retrieve information from files or messages they have explicit read permissions to access.
Non-Functional Requirements
- Latency Target: Time-To-First-Token (TTFT) must be strictly under 2.0 seconds at the 95th percentile ($p_{95}$).
- Scale: Support 10 million source documents (~100 million chunks) and handle a peak query throughput of 1,000 requests per second (RPS).
- Reliability & Resilience: Robust handling of corrupt file processing, third-party LLM rate limits/outages, and ingestion retries without data corruption.
Key Discussion Points
- High-Level System Architecture: Diagram and walk through both the asynchronous document ingestion pipeline and the synchronous query/generation flow.
- Chunking & Embedding Strategy: Detailed approach to structure-aware parsing, chunk metadata enrichment, and vector space design.
- Hybrid Retrieval & Reranking: How to balance semantic search with exact-match keyword retrieval (BM25/sparse vectors) and cross-encoder rescoring.
- Enforcing Authorization at Scale: Propose a deterministic, low-latency method to apply document Access Control Lists (ACLs) without breaking Approximate Nearest Neighbor (ANN) vector search.
- Observability & Evaluation Framework: Techniques for continuous online monitoring and offline evaluation of retrieval recall and generation hallucination rates.
Hints
Hint 1
Quantify latency budgets early: Break down the 2-second TTFT target into query processing, hybrid search, reranking, and LLM prefill steps.
Hint 2
Address the ACL filtering bottleneck explicitly: Post-filtering top-K results after vector search breaks down when a user has highly restrictive permissions; pre-filtering or payload-indexed search is necessary.
Hint 3
Separate asynchronous document processing from synchronous query paths using message queues to keep ingestion spikes from impacting search latency.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Capacity Estimations & Performance Budgets
Scale & Storage
- Corpus Size: 10 million documents.
- Chunk Count: Assuming an average of 10 chunks per document $\rightarrow$ 100 million total chunks.
- Vector Index Storage: Using a 1024-dimensional floating-point model (
float32), each raw vector requires 4 KB. $$\text{Raw Vectors} = 100 \times 10^6 \times 4\text{ KB} = 400\text{ GB}$$ With Product Quantization (PQ) or Scalar Quantization (int8), this shrinks to $\sim 100\text{ GB}$ of RAM, making it easily manageable across a small sharded cluster. - Ingestion Velocity: Assuming a 1% daily mutation rate $\rightarrow$ 100,000 documents updated per day ($\sim 1.15$ docs/sec base, with burst capacity targets up to 100 docs/sec during batch syncs).
Latency Budget (Target: TTFT < 2,000 ms at $p_{95}$)
| Stage | Component / Action | Latency Target |
|---|---|---|
| 1. Auth & Context | Validate JWT + Fetch user group memberships from Redis | ~20 ms |
| 2. Query Transformation | Small, fast model rewrites query (history resolution, multi-query) | ~120 ms |
| 3. Hybrid Search | Parallel execution: Dense Vector (ANN) + Sparse (BM25) with ACL filter | ~80 ms |
| 4. Fusion & Rerank | Reciprocal Rank Fusion (RRF) + Cross-Encoder rescoring (top-150 to top-10) | ~150 ms |
| 5. LLM Prefill | Prompt compilation + First-token generation (6K token context) | ~900–1,200 ms |
| Headroom | Network round-trips and buffer | ~400 ms |
2. API Design
Query Endpoint (Streaming)
POST /v1/chat/completions
// Request Payload
{
"messages": [
{"role": "user", "content": "What is our policy for remote equipment expenditure?"}
],
"conversation_id": "conv_98765",
"stream": true,
"filters": {
"created_after": "2023-01-01"
}
}
// Server-Sent Events (SSE) Response Stream
event: citation
data: {"citation_id": "cite_1", "doc_id": "doc_442", "title": "IT Equipment Policy 2024", "url": "https://wiki.corp/pages/442", "snippet": "Employees receive up to $1,000..."}
event: token
data: {"text": "According"}
event: token
data: {"text": " to"}
Ingestion API (Webhooks / Change Data Capture)
POST /v1/documents/sync
{
"source_system": "confluence",
"doc_id": "conf_8819",
"uri": "https://confluence.internal/display/HR/Policy",
"acl_groups": ["group:all_employees", "group:hr_staff"],
"content": "# Remote Work Policy\n...",
"updated_at": "2024-10-24T14:32:00Z"
}
3. Data Models & Schemas
Chunk Store Metadata (PostgreSQL / Elasticsearch / Vector DB)
CREATE TABLE document_chunks (
chunk_id UUID PRIMARY KEY,
doc_id VARCHAR(128) NOT NULL,
chunk_index INT NOT NULL,
content TEXT NOT NULL,
header_path TEXT, -- e.g., "HR Policy > Equipment > Reimbursement"
embedding VECTOR(1024), -- pgvector or specialized vector engine
acl_principals TEXT[], -- e.g., ["user:123", "group:eng", "group:all"]
content_hash VARCHAR(64) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT unique_doc_chunk UNIQUE(doc_id, chunk_index)
);
CREATE INDEX idx_acl_principals ON document_chunks USING GIN(acl_principals);
4. End-to-End System Architecture
INGESTION PIPELINE (Async)
[Connectors: Slack, Wiki, Drive]
│
▼
[Ingestion Gateway] ────> [ Kafka / RabbitMQ ]
│
▼
[ Parse & Chunk Workers ] ──> [ Contextual Enrichment ]
│
▼
[ Batch Embedding GPU ]
│
▼
[ Storage Layer: Vector DB + BM25 ]
──────────────────────────────────────────────────────────────────────────────────
QUERY PIPELINE (Sync)
[ Client Request ]
│
▼
[ API Gateway ] ── (Validate JWT & Extract User ID)
│
▼
[ Permission Service ] ── (Fetch User Groups from Redis)
│
▼
[ Query Orchestrator ] ──> [ Query Rewriter LLM ] (Expand acronyms, resolve history)
│
├────────────────────────┬────────────────────────┐
▼ ▼ ▼
[ Vector Search ] [ BM25 Search ] [ ACL Filter ]
(Filtered ANN) (Keyword Matching) (user_id ∈ acl_principals)
│ │ │
└────────────────────────┴────────────────────────┘
│
▼
[ Reciprocal Rank Fusion ]
│
▼
[ Cross-Encoder Reranker ] (Top-150 ──> Top-10)
│
▼
[ LLM Router / Generator ] ──> [ Stream SSE to Client ]
5. Ingestion Pipeline & Chunking Strategy
Structure-Aware Chunking & Document Processing
- Parsing by Format:
- PDFs: Use layout-aware models (e.g., Unstructured or LayoutLM) to extract structural components (headings, text blocks, tables). Convert tabular structures directly into Markdown tables.
- Slack / Communications: Group by thread context rather than raw individual messages. A chunk should comprise an entire question-answer thread bounded by a maximum time window (e.g., 4 hours).
- Chunking Technique:
- Use a Recursive Character/Token Splitter targeted at $300 - 500$ tokens with a $15%$ overlap ($45 - 75$ tokens).
- Enforce splits exclusively along structural boundaries: Document Headings (
#,##) $\rightarrow$ Paragraphs (\n\n) $\rightarrow$ Sentences (.).
- Contextual Metadata Injection (Document-to-Chunk Prepending):
- Isolated chunks lose macro context (e.g., a chunk stating "The reimbursement limit is $500" lacks context on what item or who qualifies).
- Solution: Prepend document path and structural parent headers directly into the chunk text before embedding: $$\text{Chunk Text} = \text{"[Source: HR Policy | Section: Remote Work > Equipment]\n" } + \text{Raw Chunk Content}$$
Embedding & Versioning Strategy
- Deploy a dual-encoder model optimized for retrieval quality and speed (e.g.,
bge-large-en-v1.5ore5-mistral-7b-instruct). - Index Migration Strategy: When updating embedding models, avoid in-place index overwrites. Maintain versioned index aliases (e.g.,
index_v1,index_v2). Build the new vector space in background workers, test precision/recall, and perform zero-downtime blue/green alias swaps.
6. Hybrid Retrieval & Reranking Strategy
Query: "How do I report a lost laptop?"
│
┌───────────────────────┴───────────────────────┐
▼ ▼
[ Vector Search (Dense) ] [ BM25 Search (Sparse) ]
Captures semantic intent Matches exact tokens: "laptop", "lost"
Top 100 Candidates Top 100 Candidates
│ │
└───────────────────────┬───────────────────────┘
▼
[ Reciprocal Rank Fusion ]
Combines lists into Top 150
│
▼
[ Cross-Encoder Reranker ]
Computes deep attention query-chunk pairs
│
▼
Top 10 Chunks to LLM
1. Hybrid Search
- Dense Vector Search: Captures high-level semantic intent, conceptual matches, and synonyms.
- Sparse Keyword Search (BM25 / SPLADE): Captures precise entity codes, employee IDs, software error strings, and niche internal jargon that semantic vectors frequently miss.
2. Reciprocal Rank Fusion (RRF)
Score candidates without relying on raw score normalization across disparate engines: $$RRF_Score(d \in D) = \sum_{m \in M} \frac{1}{k + r_m(d)}$$ Where $M$ is the set of retrievers (Dense and Sparse), $r_m(d)$ is the rank of document $d$ in retriever $m$, and $k$ is a smoothing constant (typically $k=60$).
3. High-Precision Reranking
- Send the top 150 candidates from RRF to a lightweight GPU-hosted Cross-Encoder model (e.g.,
bge-reranker-large). - Cross-encoders perform joint cross-attention over the query and passage simultaneously, producing significantly higher precision than bi-encoders.
- Select the top 8–10 highest scoring candidates for final prompt injection.
7. Enterprise Access Control List (ACL) Filtering
Enforcing document security is a critical requirement. Filter execution must never be delegated to the generative LLM via system prompts, as context windows are susceptible to prompt injection.
[ Incoming Query + Auth Context ]
│
▼
[ Resolve Principal Set (Redis) ]
Returns: ["user:402", "group:eng", "group:all"]
│
▼
[ Filtered Vector Search Engine ]
┌──────────────────────────────────────────────┐
│ Execute ANN Search ONLY over vector space │
│ where (acl_principals INTERSECT user_set) │
└──────────────────────────────────────────────┘
│
▼
[ Authorized Vector Sub-Graph ]
The Pre-Filtering Problem
- Post-filtering (retrieving top 100 vectors, then dropping items the user cannot read) fails severely for restrictive users. If a user has access to only $0.01%$ of files, a top-100 search might return 0 authorized documents.
- Naïve Pre-filtering (filtering first, then running brute-force search over allowed documents) degrades performance on broad permissions (e.g., items accessible to "all employees").
Recommended Solution: Single-Stage Payload Filtering Index
Use a vector engine (such as Qdrant, Vespa, or Milvus) that natively supports HNSW payload filtering:
- Store security principals directly within vector payload metadata fields (
acl_principals: ["user:402", "group:engineering", "group:all"]). - At search time, resolve the requesting user's full set of security identifiers from Redis (cached from Okta / Active Directory).
- Execute the HNSW graph traversal using conditional filtering: evaluate vector distances only for graph nodes where
acl_principalsintersects the user's active groups.
Defense-in-Depth Layer
Immediately prior to passing the final 8–10 chunks to the generation LLM, perform an explicit, out-of-band authorization check against the core permissions service. This catches edge-case race conditions where permissions were revoked within the vector database update window.
8. Failure Modes & System Resilience
| Failure Scenario | Mitigation Strategy |
|---|---|
| Ingestion Worker Crash / Malformed File | Wrap processing steps in idempotent transactions. Use a Dead-Letter Queue (DLQ) after 3 retries; log parsing failures to a monitoring dashboard and flag the document as STATUS_FAILED in the metadata DB. |
| Primary LLM Outage / Rate Limit | Implement a fallback router with a circuit breaker pattern (e.g., using Resilience4j or LiteLLM). Fail over seamlessly from primary API provider to an alternative provider or self-hosted backup model. |
| High Query Latency Spikes | Implement a two-tier Semantic Cache (Redis + Vector Match) keyed on (SHA256(User Principal Hash), Query Embedding). If an identical semantic query is issued by a user with matching ACLs, serve the cached response directly. |
9. Observability & Continuous Evaluation
1. RAG Triad Evaluation (Offline & Online)
[ User Query ]
/ \
/ \
▼ ▼
[ Retrieved Context ] ──> [ Generated Response ]
- Context Relevance: Measures if retrieved chunks are pertinent to the query (Evaluates retrieval precision).
- Groundedness / Faithfulness: Verifies that every claim in the generated response is strictly supported by the retrieved context (Detects hallucinations).
- Answer Relevance: Checks if the generated response directly answers the user's original request.
2. Automated Metrics Pipeline
- Use an offline evaluation suite (e.g., Ragas, TruLens) running daily over a curated Golden Dataset of test queries and ground-truth citations.
- Online Telemetry: Log query trace spans using OpenTelemetry. Track latency distributions across query rewrite, hybrid retrieval, reranking, and generation token delivery. Track click-through rate (CTR) on cited document links as an implicit signal of answer quality.