Building a Secure Enterprise Knowledge Search System
Machine LearningModel answerLast updated
Design a search system that answers questions from internal documents with citations while enforcing access permissions and preventing security exploits.
Context
Organizations accumulate vast amounts of internal knowledge across wikis, file storage, issue trackers, and code repositories. Employees waste time searching disconnected systems for information they need to do their work.
You need to design a knowledge search system that accepts natural language questions and produces answers synthesized from internal documents. The system must show where information came from, refuse to answer when evidence is insufficient, and never leak restricted content to unauthorized users.
Core Requirements
Access Control
- Users see answers derived only from documents they have permission to read
- Permission revocations must take effect within seconds
- The system handles dynamic group hierarchies and individual access lists
Answer Quality
- Responses must cite specific source passages that support each claim
- When retrieved documents don't contain sufficient information or contradict each other, the system must decline to answer instead of fabricating content
- Answers must be traceable to their supporting evidence
Security
- Malicious documents containing embedded instructions to leak data or manipulate behavior must not compromise the system
- No cross-user information leakage across permission boundaries
Performance Targets
- 800 ms to begin streaming the first part of an answer (95th percentile)
- Complete answer delivered within 2.5 seconds (95th percentile)
- Documents become searchable within 5 minutes of creation or modification
- 99.9% availability during business hours
System Scale
- 50 million documents totaling 500 GB to 1 TB of text
- Growth rate of 100,000 new documents daily
- 100,000 employees generating up to 100 queries per second at peak
- Complex access rules with group hierarchies and per-document permissions
What to Address
Design the end-to-end system covering:
- How documents are processed, chunked, and indexed while preserving permission metadata
- How queries are executed to retrieve relevant content respecting user permissions
- How answers are generated with proper citations and when the system should abstain
- How you defend against adversarial content and ensure users only see authorized information
- How you would evaluate and monitor the system in production
Hints
Hint 1
Think about whether access permissions should be checked before retrieval, after retrieval, or both—and why each stage matters for different reasons.
Hint 2
Consider what happens when most search results are documents the user can't access. How does this affect the quality of retrieved content?
Hint 3
For citations, generating an answer and verifying its claims can happen in overlapping stages to meet latency requirements while maintaining accuracy.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Secure Enterprise Knowledge Search
1. Scope Clarification and Sizing
Start by confirming assumptions: Is this conversational with follow-ups or single-shot Q&A? Are we multilingual? Does "within seconds" for revocation mean under 5 seconds?
Assume: multi-turn conversations, English-primary, revocation within 2-3 seconds.
Capacity estimates:
- Average document: ~20 KB (5,000 tokens)
- Chunk size: 512 tokens with 50-token overlap → ~10 chunks per document
- Total chunks: 500 million
- Embedding storage: 768-dimensional float16 vectors → ~750 GB raw, compressed to 200-300 GB with quantization
- Vector database: shard across 20-30 nodes with replication
Latency breakdown to 800 ms first token:
- Query preprocessing: 40 ms
- Permission lookup: 25 ms
- Parallel retrieval: 90 ms
- Reranking: 130 ms
- Authorization verification: 35 ms
- LLM first token: 450 ms
- Overhead: 30 ms
2. Architecture Overview
Ingestion Pipeline:
Documents flow from source systems (file storage, wikis, ticketing) through:
- Change detection via webhooks or polling
- Content extraction and structural parsing
- Intelligent chunking preserving document structure
- Embedding generation
- Index updates with permission metadata
- Content safety screening
Query Pipeline:
- Query reformulation using conversation context
- User permission resolution
- Hybrid search (semantic + keyword)
- Multi-stage ranking
- Permission verification
- Context construction
- Supervised answer generation
- Citation validation
- Response streaming
3. Permission-Aware Retrieval
The Dual-Gate Approach:
Use both pre-filtering and post-filtering because each solves different problems.
Pre-filtering at index time: Store permission principals (users and groups) as filterable attributes. During retrieval, filter to chunks where chunk.allowed_principals ∩ user.principals ≠ ∅. This ensures good recall—if a user can access only 5% of documents, post-filtering alone would retrieve mostly inaccessible content.
Post-filtering with authoritative check: After reranking, verify the top documents against the live authorization service. This handles the lag between permission changes and index updates, providing correctness guarantees.
Why both? Pre-filtering maintains recall efficiency. Post-filtering ensures security—nothing reaches the LLM prompt unless it passes this gate.
Permission propagation:
- Store group membership in a graph database
- Cache expanded user principals (transitive group closure) for 30-60 seconds
- Invalidate cache entries on membership changes
- Never store expanded user lists in document metadata (would require reindexing millions of chunks on every group change)
4. Hybrid Retrieval Strategy
Execute dense semantic search and sparse keyword search in parallel:
Dense retrieval: Approximate nearest neighbor search using HNSW or IVF indexes. Essential for semantic similarity and synonym handling. Returns top 200 candidates.
Sparse retrieval: BM25 for exact matches on identifiers, error codes, product names. Returns top 200 candidates.
Merge with reciprocal rank fusion: score(item) = Σ(1/(k + rank_in_list)) where k=60. This balances both signals without tuning weights.
Reranking: Pass the top 100 merged results through a cross-encoder model (BERT-based) trained on query-passage relevance. This is expensive but highly accurate. Keep top 20.
5. Grounded Generation with Citations
Context assembly:
- Deduplicate near-identical chunks
- Expand context by including adjacent chunks when a hit is mid-document
- Prefer recent documents and authoritative sources
- Assemble 6-8K tokens of context
Two-stage generation:
Stage 1—Synthesis: Structure the prompt with numbered passages. Instruct the model to cite passage numbers inline: "According to [P3], the policy requires..." Generate with high temperature for natural language.
Stage 2—Verification: For each generated claim, run entailment checking against cited passages using a specialized NLI model. Extract the specific supporting span for precise citation linking.
Streaming with verification: Generate sentence-by-sentence, verify sentence N while generating sentence N+1. Buffer one sentence to hide verification latency. If a claim fails verification, attempt re-attribution to another passage or drop it.
6. Calibrated Abstention
Build a confidence model using multiple signals:
- Top reranker scores and score distribution
- Number of passages exceeding relevance threshold
- Percentage of claims passing entailment checks
- Token-level confidence from the generation model
- Contradiction detection across top passages (compare dates, policies, facts)
Train a logistic classifier on labeled examples of answerable vs. unanswerable queries. Set the threshold for high precision on answered queries—false confidence is worse than abstention.
When abstaining, still show the closest matching documents as suggestions.
7. Security Defenses
Prompt injection mitigation:
Architectural isolation: Treat all document content as untrusted data. Use structured prompts where retrieved passages go into clearly delimited data sections, never mixed with instructions.
Least privilege: The system operates with the querying user's identity, not elevated permissions. The context contains only documents the user already has access to.
Output filtering:
- Strip markdown images and links to external domains
- Detect and block attempts to exfiltrate data in responses
- Run a separate classifier to detect instruction-following in generated output
- Validate that citations reference actual retrieved passages
Input monitoring: During ingestion, flag suspicious patterns (instruction-like phrases, exfiltration attempts). Human review high-risk documents before they're searchable.
Audit logging: Record every query, retrieved documents, and generated answers with user identity for security investigations.
8. Evaluation and Monitoring
Offline metrics:
- Retrieval recall@k using human-labeled query-document pairs
- Citation precision (do cited passages actually support claims?)
- Abstention calibration curve (confidence vs. actual correctness)
Online monitoring:
- p50/p95/p99 latency for each pipeline stage
- Abstention rate (should be 10-20%; too low suggests overconfidence)
- User engagement: answer upvotes, source clicks, reformulations
- Permission check latency and failure rate
- Index freshness lag
A/B testing framework for ranking improvements, new models, and abstention thresholds.
9. Common Pitfalls
- Post-filtering only: Works for admins with broad access, collapses for users with narrow permissions
- Expanded user lists in metadata: Requires massive reindexing on group changes
- Citations without verification: Models hallucinate sources and supporting evidence
- Single relevance threshold: Different queries need different confidence levels
- Ignoring latency monitoring: Reranker and verification can blow latency budgets
10. Extensions
For follow-up discussion:
- Multi-turn conversation with query disambiguation
- Document editing or action-taking capabilities
- Federated search across external knowledge bases
- Multilingual support with cross-lingual retrieval
- Personalization based on user role and past queries