Building a Multi-Tenant RAG System for Secure Document Search
Machine LearningModel answerLast updated
Architect a question-answering pipeline over confidential documents with strict access controls, verifiable citations, version handling, and hallucination prevention.
Context
You're designing a question-answering system for an enterprise document repository containing sensitive materials like contracts, regulatory filings, and internal communications. Users submit natural language queries and receive answers with precise source citations showing exactly where information was found (document name, section, page, and coordinates).
The system must enforce strict security boundaries—users only access documents they're authorized to see, and data from different organizations never mix. Documents are frequently updated with new versions (like contract amendments replacing original terms), and the system needs to track which version is current. When the evidence is unclear or contradictory, the system should decline to answer rather than fabricate information.
Your Task
Design the complete machine learning system architecture covering:
Core Capabilities:
- Accept documents in multiple formats (PDFs, Word files, scanned images), extract their structure, and prepare them for search
- Answer questions using retrieved context while providing exact citations with page numbers and text coordinates
- Enforce access controls so users only see results from documents they're permitted to access
- Handle document versions correctly, applying amendments that override older clauses
- Recognize when retrieved evidence is insufficient or conflicting, and abstain from answering
System Constraints:
- Scale: 500 million searchable text segments across 1,000 separate organizations; the largest single organization has 50 million segments
- Performance: 95th percentile end-to-end query time under 2.5 seconds, with retrieval completing in 300ms and answer generation starting within 800ms
- Data freshness: New documents or permission changes must be searchable within 60 seconds
- Accuracy requirements: Absolutely no cross-organization data leakage; hallucination rate (unsupported claims) below 1%
What to Address
Your design should cover:
- Architecture overview: How documents flow from upload through indexing to query serving
- Retrieval strategy: How you find relevant passages at scale while respecting access permissions
- Citation mechanism: How you ensure every answer sentence maps to actual source text
- Version management: How you handle documents that supersede or amend earlier versions
- Security model: How you prevent unauthorized access and prompt injection attacks hidden in documents
- Evaluation approach: How you measure retrieval quality, answer accuracy, and citation correctness
Discuss concrete technology choices, data models, and tradeoffs between approaches.
Hints
Hint 1
Consider how access control filtering interacts with approximate nearest neighbor search—post-filtering can leak information and hurt recall
Hint 2
Document amendments create temporal relationships between versions; you need both structural parsing to detect references and a resolution layer at query time
Hint 3
Citations must be verified programmatically against retrieved sources before returning to users; relying solely on the language model produces hallucinations
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Multi-Tenant RAG System Architecture
1. Establish Scope and Sizing
Begin by translating requirements into concrete numbers to guide technology selection.
Traffic assumptions:
- Peak query load: ~200 queries/second aggregate, with the largest tenant driving ~50 QPS
- Average query requires retrieving and ranking hundreds of candidate passages
Storage calculations:
- 500M text chunks × 1024-dimensional embeddings × 4 bytes = ~2TB for full-precision vectors
- With quantization (int8 or product quantization): 250-500GB in compressed form
- Keep full precision on SSD for final rescoring to preserve quality
Tenant partitioning:
- Largest tenant (50M chunks) gets dedicated index shards for isolation and performance
- Smaller tenants share infrastructure with
tenant_idas mandatory partition key
Latency breakdown for 2.5s budget:
- Authentication and permission resolution: 20ms
- Retrieval across index: 150ms
- Reranking with cross-encoder: 120ms
- Language model first token: 800ms
- Streaming remainder + citation verification in parallel
2. System Architecture
Ingestion Pipeline (Event-Driven)
Documents flow through an asynchronous processing chain:
- Upload & validation: Check file integrity and scan for malware
- Content extraction: PDF text layer extraction; OCR for scanned pages with coordinate mapping
- Structure parsing: Identify headings, sections, numbered clauses, defined terms using layout models
- Security scrubbing: Remove hidden text layers that could contain injection attacks
- Amendment detection: Parse cross-references ("This Section 4.2 replaces Section 4.2 of the Master Agreement dated...") to build supersession relationships
- Chunking strategy: Create 200-400 token segments with section headers prepended for context; maintain parent-child hierarchy (document → section → paragraph)
- Embedding generation: Dual encoding with dense embeddings (via bi-encoder model) and sparse term weights (BM25-style)
- Indexing: Write to vector index and metadata store
For large documents, process page-by-page so early sections become searchable quickly, meeting the 60-second freshness requirement.
Data Model
Documents table:
doc_id, tenant_id, document_family_id, version_id,
doc_type (original|amendment|supplement),
effective_date, status (active|deleted),
folder_id, content_hash
Chunks table:
chunk_id, tenant_id, version_id,
section_hierarchy ("Article_4/Subsection_4.2/Paragraph_b"),
parent_chunk_id, text_content,
page_number, character_offsets, bounding_boxes,
folder_id, access_groups[],
is_current_version (boolean),
dense_embedding, sparse_features
Version relationships:
amendment_id, original_clause_id,
operation (replace|delete|append),
effective_date
Critical security principle: Chunks store folder_id and access_groups[], never individual user IDs. Permission resolution happens at query time by mapping users to groups.
Query Pipeline
- Query preprocessing: Extract entities (dates, party names, section references), expand legal synonyms
- Permission resolution: Map authenticated user to authorized folders/groups with short-lived cache
- Hybrid retrieval: Run parallel searches:
- Dense vector similarity for semantic matching
- Sparse keyword search for exact term matches (critical for legal language)
- Apply
tenant_idand ACL filters as pre-filters during search, not after
- Fusion and ranking: Merge results using reciprocal rank fusion, then rerank top 200 with cross-encoder
- Context expansion: For top 20 chunks, retrieve parent sections for full clause context
- Temporal resolution: If multiple versions exist, apply amendment chain to identify current text
- Answer generation: Language model produces structured output with per-sentence citations
- Citation verification: Programmatically validate each citation against retrieved sources
- Streaming response: Return answer incrementally with verified citations
3. Key Technical Decisions
Hybrid Retrieval Rationale
Why not pure dense vectors? Legal queries depend heavily on exact terminology ("Section 7.3(a)", "Change of Control", specific party names). Dense embeddings sometimes miss exact matches.
Why not pure keyword search? Users ask questions like "Can the agreement be terminated early?" which require semantic understanding to match clause text about "either party may dissolve this contract with 30 days notice."
Hybrid approach: Combine both, then use a trained cross-encoder (fine-tuned on legal relevance judgments) for final reranking. Reciprocal rank fusion merges the two ranked lists without tuning weights.
Access Control as Pre-Filter (Critical)
Why ACLs must filter before search:
- Post-filtering leaks information: Unauthorized text enters logs, model memory, and reranker inputs
- Post-filtering destroys recall: If a user can access 0.1% of documents, the top-k results are almost entirely filtered out, leaving few relevant results
Implementation:
- Modern vector databases support filtered approximate nearest neighbor (ANN) search
- For highly selective filters (<50K accessible chunks), bypass ANN and use exact brute-force similarity—counterintuitively faster and more accurate
- Defense-in-depth: Re-validate chunk permissions against authoritative metadata store before adding to prompt
Citation Verification (Preventing Hallucinations)
Language models naturally fabricate plausible-sounding citations. Verification is a deterministic pipeline per sentence:
- ID validation: Confirm cited
chunk_idwas in the retrieved set for this query—blocks fabricated IDs - Quote matching: Extract the quoted text and fuzzy-match against chunk content (normalize whitespace, ligatures, hyphenation); require ≥90% token overlap
- Coordinate mapping: Map matched span to stored page numbers and bounding boxes for UI highlighting
- Semantic entailment: Run NLI model to verify the claim is actually supported by the quoted span, not just lexically similar
Failure handling:
- Reject sentences that fail verification; optionally regenerate once
- If too many sentences fail or reranker scores are uniformly low, abstain with "insufficient evidence" message and show closest passages for transparency
Version and Amendment Handling
Temporal resolver component:
- Group retrieved chunks by
document_family_id - Apply amendment operations in chronological order up to query's
as_of_date - Produce the effective text and a change timeline
Context for language model: "Section 4.2 from 2021 Master Agreement was replaced by Amendment No. 3 (effective 2024-03-15). Current text: [amended clause]"
Handling ambiguous amendments: Some references are vague ("notwithstanding anything to the contrary"). Use LLM classifier to detect potential conflicts between amendment and original, flag low-confidence resolutions, and present both versions with timeline.
Security Defenses
Prompt injection resistance:
- Strip hidden text layers during ingestion
- Treat all document content as untrusted data in prompts
- Use structured output schemas that separate instructions from content
- Validate citations prevent exfiltration of unauthorized chunks through fabricated cross-references
Tenant isolation:
tenant_idis a mandatory partition key in all queries—enforced at infrastructure level- Separate compute pools for largest tenants to prevent resource-based side channels
- Monitor for anomalous cross-tenant query patterns
4. Evaluation Framework
Offline metrics (before deployment):
- Retrieval recall@k: Are correct source passages in top-20 results? Test on labeled query-document pairs
- Citation precision: Do generated citations point to actual supporting evidence? Use human raters on sample answers
- Faithfulness: Does answer content appear in retrieved context? Use automated NLI scoring plus human review
- Injection resistance: Red-team testing with adversarial documents containing fake instructions
Online metrics (production monitoring):
- User feedback (thumbs up/down, citation helpfulness)
- Abstention rate (should be low but non-zero—indicates system recognizes uncertainty)
- Retrieval latency P50/P95/P99
- Citation verification failure rate (sudden spikes indicate quality degradation)
A/B testing strategy: Experiment with retrieval parameters (k, reranker threshold), abstention thresholds, and prompt formulations on small traffic percentage before full rollout.
5. Scaling and Operations
Sharding strategy:
- Dedicated index shards for tenants >10M chunks
- Smaller tenants bin-packed onto shared infrastructure
- Read replicas for query serving; async writes to maintain freshness
Freshness pipeline:
- Incremental indexing: New chunks insert without full rebuild
- Soft delete: Mark chunks as
is_current=falserather than immediate removal (compliance/audit trail) - Hard delete: Batch purge after retention period with full index compaction
Cost optimization:
- Use quantized vectors for initial retrieval
- Cache permission resolutions (with short TTL)
- Batch embed generation for new documents
- Serve popular queries from cache with TTL tied to document update frequency
6. Common Pitfalls
- ACL post-filtering: Seems simpler but leaks data and breaks recall
- Trusting LLM citations: Models confidently cite non-existent sources without verification
- Ignoring document structure: Flat chunking loses critical context like section headers
- Synchronous processing: Blocking uploads on full indexing violates latency SLA
- Over-abstracting answers: Legal users need exact quoted language, not paraphrases
This architecture balances accuracy, security, and performance for a production RAG system serving sensitive enterprise documents.