Build a RAG-powered enterprise document search platform
Machine LearningModel answerLast updated
Design the end-to-end architecture for a production retrieval-augmented generation system serving internal knowledge search at scale.
You're tasked with building a machine learning system that lets employees search through their organization's internal knowledge base and receive generated answers grounded in retrieved documents.
System requirements:
- Document collection: 5 million documents averaging 2 KB each, sourced from PDFs, web pages, and support tickets
- Update latency: New or modified content must become searchable within 5 minutes
- Query load: Handle 300 queries per second
- Multi-tenancy: Support multiple organizations with document-level access control lists (ACLs)
- Performance targets: 95th percentile end-to-end latency under 1.2 seconds, cost per query under $0.002
What you need to design:
-
Document processing pipeline: How will you parse heterogeneous formats, extract metadata, handle duplicates, split documents into chunks, generate embeddings, and support versioning with incremental updates?
-
Search and retrieval layer: Explain your indexing strategy, including sparse and dense retrieval methods, how you'll enforce tenant boundaries and ACLs, query preprocessing, candidate selection, and reranking.
-
Answer generation: Describe prompt engineering, how you'll ground answers in retrieved content with citations, handle streaming responses, and support multiple languages.
-
Safety and correctness: What mechanisms will you use to reduce hallucinations, enforce citation accuracy, handle sensitive content, prevent prompt injection, and ensure ACL compliance throughout the pipeline?
-
Measurement and observability: Define offline evaluation metrics, online experimentation approaches, feedback collection, and monitoring dashboards for latency, cost, quality drift, and ingestion health.
-
Production architecture: Break down the system into services, explain scaling strategies for each component, model hosting and batching decisions, caching layers, vector database selection, and failure handling.
-
Capacity planning: Estimate per-stage latency and cost, calculate embedding storage requirements, index memory footprint, and compute capacity needed to meet the SLOs.
Walk through your design decisions, justify trade-offs, and show how you'd validate that the system meets requirements.
Hints
Hint 1
Start by calculating corpus scale: total text volume, number of chunks after splitting, daily query volume, and budget per component.
Hint 2
Consider running keyword-based and embedding-based retrieval in parallel, then merging results before reranking.
Hint 3
ACL enforcement needs defense in depth: filter at retrieval time and revalidate right before generation to catch revocations.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: RAG-Powered Enterprise Search
1. Establish Scale and Constraints
Begin by converting requirements into concrete numbers that will inform every design choice.
Corpus math:
- 5M documents × 2 KB = 10 GB of raw text
- Assuming ~500 tokens per document, splitting into ~300-token chunks with 15% overlap yields roughly 12-13 million chunks (about 2.6 chunks per document)
Traffic and budget:
- 300 QPS = ~26 million queries per day
- At $0.002 per query, daily budget is ~$52,000
- This budget must cover embeddings, retrieval infrastructure, reranking, and LLM generation
Latency breakdown:
- 1.2 second p95 end-to-end budget
- Rough allocation: retrieval 200ms, reranking 150ms, generation 700ms, network/overhead 150ms
- Confirm with the interviewer whether this means time-to-first-token or complete answer delivery
Freshness:
- Content updates searchable in 5 minutes
- ACL revocations must be enforced immediately (stricter requirement)
2. Overall Architecture
Document Sources
↓
Connectors & Change Detection
↓
Message Queue (Kafka)
↓
Processing Pipeline: Parse → Deduplicate → Chunk → Extract Metadata
↓
Embedding Generation (batch workers)
↓
Index Writers (BM25 + Vector DB)
Query Flow:
User → API Gateway (auth, rate limiting)
↓
Query Service (rewrite, classification)
↓
Parallel Retrieval: [BM25 Index] + [Vector Index] with ACL filters
↓
Result Fusion
↓
Cross-Encoder Reranker
↓
ACL Revalidation
↓
LLM Generator (streaming)
↓
Citation Verification
↓
Response to User
Each component is independently scalable. Retrieval is CPU/memory intensive, while reranking and generation require GPU resources.
3. Document Processing Pipeline
Parsing heterogeneous formats:
- PDF: Layout-aware extraction preserving structure (headings, tables), OCR for scanned documents
- HTML: Remove boilerplate, preserve semantic structure
- Tickets: Flatten threads chronologically, preserve metadata (status, priority, author)
- Retain structural markers (section headers, page numbers) for better citation quality
Deduplication:
- Exact duplicates: SHA-256 content hashing
- Near-duplicates: MinHash or SimHash with LSH for ~90%+ similarity detection
- Store single canonical copy but merge ACLs and maintain source references
Chunking strategy:
- Target 256-400 tokens per chunk with ~50 token overlap
- Split at structural boundaries (paragraphs, sections) when possible
- Prepend document title and section hierarchy to each chunk for context
- Trade-off: smaller chunks improve precision, larger chunks preserve context but dilute embeddings
Metadata extraction:
- Required: tenant_id, ACL principals, source URL, author, timestamps, document type
- Derived: language detection (fastText), extracted title, document classification
- All metadata indexed as filters for retrieval
Versioning and incremental updates:
- Chunks keyed as
(document_id, version, chunk_index) - New versions written atomically, alias pointer updated, old version marked for deletion
- Change detection via content hashing skips unchanged chunks (~99% of corpus stable daily)
- ACL-only changes update filter metadata without re-embedding
- Processing pipeline can handle ~1% daily churn (~125K chunks) easily within 5-minute window
4. Retrieval Architecture
Hybrid retrieval approach:
Run two retrievers in parallel:
- BM25 (sparse): Elasticsearch or Vespa, returns top 100 candidates. Excellent for exact matches, IDs, error codes, rare terms
- ANN (dense): HNSW index over embeddings (e.g., bge-large-en-v1.5 or multilingual-e5-large), returns top 100 candidates
Result fusion:
- Use Reciprocal Rank Fusion: score = Σ 1/(k + rank_i) for each retriever
- No score normalization needed, handles scale differences automatically
- Keep top 40-50 after fusion for reranking
Tenant isolation and ACL enforcement:
Critical security requirement needing multiple layers:
tenant_idis server-side injected, never from client input- Large tenants (>1M docs) get dedicated index shards
- Small tenants share shards with partition key on tenant_id
- User's ACL principals (user ID + expanded group memberships) pushed as pre-filters into both BM25 and ANN search
- Use filter-aware HNSW navigation to avoid post-filtering starvation
- Cache ACL group expansions (TTL: 5 minutes)
Query understanding:
- Classify query type (keyword lookup vs. question vs. conversational)
- LLM-based query rewriting for follow-ups, acronym expansion, typo correction (~100ms, use selectively)
- Extract structured filters from natural language (date ranges, document types)
Reranking:
- Cross-encoder model (e.g., MiniLM-based) scores top 40 (query, chunk) pairs
- Rerank based on semantic relevance, takes ~150ms for 40 pairs on GPU
- Select top 6-8 chunks for context window (balance between coverage and cost)
5. Answer Generation
Prompt engineering:
System: You are a search assistant. Answer only using the provided sources.
Cite sources as [n] after each claim. Say "I don't have information about that"
if sources don't contain the answer.
Sources:
[1] Title: ... | Date: ... | URL: ...
Content: ...
[2] Title: ... | Date: ... | URL: ...
Content: ...
...
Question: {user_query}
Grounding techniques:
- Constrained decoding using JSON schema:
{answer_segments: [{text: str, citations: [int]}]} - Citation IDs restricted to valid source range via grammar constraints
- Temperature 0.3-0.5 to reduce creativity
Streaming:
- Stream tokens via Server-Sent Events
- Send retrieved sources immediately while generation proceeds
- Progressive rendering improves perceived latency
Multilingual support:
- Use multilingual embedding model (bge-m3 or multilingual-e5)
- Language-specific BM25 analyzers (tokenization, stemming)
- Detect query language, respond in same language
- Cross-lingual retrieval works automatically with shared embedding space
Tool integration:
- Narrow, scoped tools: ticket status lookup, calendar search, policy version lookup
- All tools respect ACLs and tenant boundaries
- Timeout each tool call at 200ms
6. Safety and Guardrails
Hallucination reduction:
- Abstain when top reranking score below threshold (indicates poor retrieval)
- Natural Language Inference model post-processes answer: verify each sentence is entailed by cited chunks
- Drop or flag unsupported claims
- Log abstention rate; investigate spikes
Citation enforcement:
- Reject answers with uncited claims
- Validate all citation IDs exist in retrieved set
- Regenerate with stronger constraints if violations occur
Prompt injection defense:
- Treat document content as data, not instructions
- Delimiter-wrapped retrieved text
- Never execute commands or tools based solely on document content
- Input classifier catches jailbreak attempts
PII and compliance:
- PII detection at ingestion (regex + NER models)
- Tag and optionally redact sensitive fields
- Encryption at rest and in transit
- Per-tenant KMS keys for large customers
- Strict no-training policy on customer data
ACL defense in depth:
- Pre-filter at index level (performance)
- Re-validate each final chunk against authoritative ACL service right before generation (correctness)
- Cache keys include tenant + ACL group hash to prevent cross-tenant leaks
- Monitor ACL check failures and alert on anomalies
7. Evaluation and Monitoring
Offline evaluation:
Build golden test set per tenant type:
- Human-labeled (query, relevant_docs, ideal_answer) tuples
- LLM-generated queries validated by domain experts
Metrics:
- Retrieval: Recall@50 (pre-rerank), NDCG@10 (post-rerank)
- Generation: Answer faithfulness (NLI-based), citation precision/recall, correctness (LLM-as-judge calibrated with human ratings)
- Abstention accuracy (did system correctly refuse when answer not in sources?)
Online evaluation:
- A/B tests with interleaving for ranking changes
- Track: click-through rate on citations, thumbs up/down, answer copy rate, query reformulation rate (negative signal)
- Time-to-success: did user stop searching after this answer?
Continuous improvement:
- Mine hard negatives from user clicks and downvotes
- Fine-tune reranker and embedding model (requires full index rebuild for embeddings)
- Shadow deployment for new index versions before traffic switch
Production monitoring:
Dashboards:
- Latency: p50/p95/p99 per stage (retrieval, rerank, generation)
- Cost: per-query breakdown, daily budget burn rate
- Quality: abstention rate, citation accuracy, user satisfaction scores
- Freshness: ingestion lag (alert if >3 minutes), ACL propagation delay
- Infrastructure: cache hit rates, GPU utilization, index memory usage
- Drift: query distribution shifts, embedding space coverage, out-of-vocabulary rate
8. Scalability and Architecture
Service decomposition:
- Query service (stateless, CPU): 50 instances for 300 QPS
- BM25 search: 10 shards × 3 replicas (Elasticsearch/Vespa)
- Vector search: 10 shards × 3 replicas (custom HNSW or Vespa)
- Reranking service (GPU): batch up to 8 requests, ~20 GPU instances
- Generation service (GPU): streaming inference, ~40 instances with vLLM or TGI
Model hosting:
- Embeddings: batch generation during ingestion, async workers
- Reranker: online batching (wait up to 20ms to fill batch), throughput-optimized
- LLM: streaming inference, latency-optimized with tensor parallelism
Caching strategy:
- L1: Recent identical queries (5min TTL), ~15% hit rate
- L2: Retrieval results per (query_embedding, filters) (1hr TTL)
- L3: ACL group expansions (5min TTL)
- Warm popular queries daily
Vector store selection:
- Use unified platform (Vespa or OpenSearch) for BM25 + filtered ANN to avoid drift
- Shard by tenant, replicate 3× across availability zones
- Index size: 12M chunks × 1024-dim embeddings × 4 bytes = ~48 GB (fits in memory with compression)
Failure handling:
- Graceful degradation: fall back to BM25-only if vector search fails
- Circuit breakers on reranker and LLM (return top retrieval results unranked/raw if downstream fails)
- Multi-region deployment with cross-region failover (RPO: 5 min, RTO: 2 min)
9. Capacity Planning
Latency budget validation:
- Retrieval (parallel): 180ms p95 (including ACL filter)
- Reranking (batched): 120ms p95
- ACL revalidation: 30ms p95 (cached)
- LLM generation (streaming): 600ms p95 to first token, 200 tokens at ~3 tokens/ms
- Total: ~1.13s p95 ✓
Cost breakdown (per query):
- Embedding (cached, amortized): $0.0001
- Retrieval infrastructure (BM25 + vector): $0.0003
- Reranking (GPU): $0.0002
- LLM generation (assuming 1500 input + 150 output tokens at ~$0.60/1M): $0.0010
- Total: ~$0.0016 per query, under $0.002 budget ✓
Compute requirements:
- Embedding workers: 125K chunks/day ÷ (3600s × 24) × 100ms ≈ 0.15 GPUs sustained
- Reranking: 300 QPS × 40 pairs × 150ms ÷ (batch_size 320) ≈ 6 GPUs
- Generation: 300 QPS × 700ms ≈ 210 concurrent, ~40 GPUs with batching and optimized inference
Storage:
- Raw documents: 10 GB
- Embeddings (FP16 compressed): ~48 GB
- BM25 index: ~30 GB
- Metadata and filters: ~5 GB
- Total: ~100 GB (easily fits on modern search infrastructure)
Key Trade-offs and Validation
Chunk size: 300 tokens balances context (not too fragmented) with precision (not too diluted). Validate with NDCG@10 experiments.
Reranking depth: Top 40 is sweet spot between quality and cost. Diminishing returns beyond this point based on offline analysis.
Citation strictness: Enforced citations reduce hallucination but increase abstention rate. Monitor user satisfaction to tune threshold.
ACL enforcement: Two-stage checking adds latency but is mandatory for security. Optimize with aggressive caching and batch validation.
Cost vs. quality: Using larger LLM or deeper reranking improves quality but risks budget overrun. Start with efficient models, upgrade selectively based on impact analysis.
Validate the design through shadow deployment, gradual rollout with metrics monitoring, and continuous A/B testing of each component.