Multi-Stage Retrieval System for Document Search
Machine LearningModel answerLast updated
Design a scalable retrieval and ranking pipeline for querying 10M documents under 2s latency at 500 QPS with permission enforcement.
You're building the backend for an internal knowledge assistant that answers employee questions by searching across a large collection of company documents. The corpus contains approximately 10 million PDF and Word files covering internal policies, technical documentation, and project materials.
When an employee submits a natural language question, your system must find the most relevant passages from documents they're authorized to access, then feed those passages to a language model to generate an answer.
Constraints
- Scale: 10 million documents in the corpus; approximately 30 content segments per document on average
- Performance: p95 latency under 2 seconds from query submission to first response token; support 500 queries per second sustained load
- Security: Enforce document-level permissions—users may only see results from documents their role permits them to access
What You Need to Design
Build out the complete pipeline architecture, covering:
-
Document processing: How do you ingest, parse, segment, and index millions of documents for fast retrieval?
-
Query execution: How do you balance retrieval speed against result quality? Consider whether a single-stage or multi-stage approach makes sense.
-
Permission enforcement: How do you integrate authorization checks without adding prohibitive latency or returning empty result sets for users with limited access?
-
Quality measurement: What metrics tell you whether the retrieval stage is working well versus whether the answer generation is accurate?
Describe the key components, their responsibilities, and how they interact. You may sketch a diagram or provide a written flow.
Hints
Hint 1
Break your 2-second budget across all stages—query processing, retrieval, ranking, and generation each need their share
Hint 2
Filtering unauthorized results after retrieval can leave you with too few passages; think about where permission checks happen in the index itself
Hint 3
Keyword search and semantic search each have strengths; combining them in parallel often beats either alone
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires balancing three competing pressures: retrieval quality, latency, and security. A strong design decomposes the 2-second budget across stages, pre-filters on permissions within the index, and separates fast retrieval from expensive re-ranking.
1. Scope and Sizing
Start by confirming assumptions with the interviewer:
- Latency measurement: Are we targeting time-to-first-token with streaming, or total response time? Assume p95 time-to-first-token under 2 seconds.
- Corpus breakdown: 10M documents averaging 15 pages each, chunked into ~500-token segments, yields roughly 300 million chunks.
- Embedding storage: At 768 dimensions per vector in float32, raw storage is ~900 GB. Quantization (int8 or product quantization) reduces this to 100–250 GB, which fits in memory across a small fleet.
- Traffic patterns: 500 QPS sustained with ~2× headroom for peak load.
- Update rate: About 1% of documents change daily (~100K documents/day).
- Permission model: Users belong to groups; documents carry access-control lists referencing those groups.
Latency budget breakdown (p95):
| Stage | Allocation |
|---|---|
| Authentication + group lookup (cached) | 10 ms |
| Query processing + embedding | 30 ms |
| Parallel retrieval (keyword + vector) | 80 ms |
| Result fusion + cross-encoder re-ranking | 150 ms |
| Prompt construction | 10 ms |
| LLM time-to-first-token | 600–1000 ms |
| Total | ~1.3s with buffer |
2. High-Level Architecture
┌─────────────── Offline Indexing ───────────────┐
│ Document sources → Parser → Chunker │
│ → Embedding model (batched on GPU) │
│ → Write to: │
│ • Keyword index (BM25 + ACL metadata) │
│ • Vector index (HNSW/IVF-PQ + ACL filter) │
│ • Chunk store (text + metadata) │
└────────────────────────────────────────────────┘
User query → Auth service (expand user → groups, cached)
→ Query processor (embed query, parse intent)
→ Parallel fan-out:
├─ BM25 search (ACL pre-filter) → top ~100
└─ Vector ANN search (ACL pre-filter) → top ~100
→ Reciprocal rank fusion → ~200 candidates
→ Cross-encoder re-ranker → top 8–10 chunks
→ ACL re-check (final verification)
→ Prompt builder → LLM (stream + citations)
→ Log feedback for evaluation
3. Document Processing Pipeline
Parsing: Use layout-aware parsers that preserve structure—headings, tables, page numbers. Apply OCR to scanned PDFs. Output a structured document tree.
Chunking: Split on semantic boundaries (section breaks, paragraphs) aiming for 300–600 tokens per chunk with ~10% overlap. Prepend each chunk with document title and section context. This "contextual header" significantly improves recall for both keyword and semantic search. Keep tables intact or linearize them carefully.
Embedding: Fine-tune a bi-encoder (e.g., a sentence-transformer model) on internal query–passage pairs mined from logs or generated synthetically. Batch embed chunks on GPUs. Store embedding model version so you can rebuild indexes on model upgrades without downtime.
Storage layers:
- Vector index: HNSW for low-latency recall or IVF-PQ for memory efficiency. Shard by chunk ID hash with replicas for availability.
- Keyword index: BM25 inverted index (Elasticsearch/OpenSearch pattern) with identical sharding.
- Chunk store: Key-value store holding raw text and metadata separately from indexes to keep them lean.
4. Two-Stage Retrieval Strategy
Stage 1: High-recall retrieval (parallel execution)
Run keyword and vector search simultaneously:
- BM25 catches exact matches—product codes, acronyms, proper names.
- Dense vector search captures semantic paraphrases and conceptual matches.
Each retriever returns ~100–200 candidates per shard. Merge results using Reciprocal Rank Fusion: score = Σ 1/(k + rank) where k=60. RRF requires no score normalization and empirically outperforms simple score concatenation.
Stage 2: Precision re-ranking
Pass the fused ~200 candidates through a cross-encoder—a BERT-base or MiniLM model that scores each (query, chunk) pair jointly. This is expensive (200 pairs × 500 QPS = 100K inferences/sec) but dramatically improves precision.
- Batch inference on GPU with fp16/int8 quantization.
- Budget ~150 ms for this stage; cap candidate count dynamically if latency spikes.
Select the top 8–10 chunks. Apply diversity heuristics: deduplicate near-identical chunks and limit results per document to 2–3 to maintain coverage breadth.
Optional enhancements:
- Query rewriting for conversational follow-ups using a small LLM.
- Semantic result cache keyed by query embedding + user permission signature.
5. Access Control Strategy
Why post-filtering fails: If you retrieve top-K then discard unauthorized results, users with narrow permissions may see zero results. It also wastes compute and creates security risk if the filter fails open.
Pre-filter within the index:
-
At query time, expand the user into their full principal set (user ID + transitive group memberships). Cache this mapping with a short TTL; typical users belong to 50–500 groups.
-
Store
acl_principals(group IDs) in each chunk record as indexed metadata. Use group IDs rather than user IDs so the ACL list stays small and group membership changes don't require chunk reindexing. -
Apply the permission filter during index traversal:
- BM25: add a terms filter on the ACL field.
- Vector search: use filtered HNSW (filter-aware graph traversal) or IVF with per-partition filter bitmaps.
-
For highly selective filters (user sees <1% of corpus), switch to brute-force scoring over the permitted subset—fast because the subset is small. Most engines choose this automatically based on filter cardinality.
-
Shard by
tenant_idor business unit where possible so queries naturally skip irrelevant partitions. -
Defense in depth: Before sending the final 8–10 chunks to the LLM, re-check document IDs against the authoritative permission service. This catches ACL changes not yet reflected in the index. Never cache LLM responses across users with different permission signatures.
6. Evaluation Metrics
Retrieval quality (measured against labeled query–passage pairs from expert annotation or implicit feedback):
- Recall@K: What fraction of relevant passages appear in the top K results?
- MRR (Mean Reciprocal Rank): How quickly do we surface the first relevant result?
- NDCG@K: Position-weighted relevance score.
Build evaluation sets per business domain; performance often varies by document type.
Generation quality (measured separately):
- Faithfulness: Does the answer cite information actually present in retrieved passages? Use NLI models or human raters.
- Completeness: Does the answer address all parts of the question?
- Citation precision: Are citations linked to the correct passages?
Track these metrics independently so you can diagnose whether problems stem from poor retrieval (wrong chunks surfaced) or poor generation (LLM misinterpreting correct chunks).
System health:
- p50, p95, p99 latency by stage.
- Retrieval empty-result rate, broken down by user permission profile.
- Index freshness lag (time from document update to searchability).
Time and Space Complexity
- Indexing: O(N·D) where N = chunk count, D = embedding dimension. One-time cost plus incremental updates.
- Retrieval latency: O(log N) for HNSW vector search + O(M) for BM25 where M = posting list length. Re-ranking is O(K·L) where K = candidate count, L = cross-encoder sequence length.
- Storage: O(N·D) for vectors, quantization reduces by 4–8×; keyword index is O(N·V) where V = vocabulary size.
Common Mistakes
- Post-filtering on permissions: Leads to empty results and security risks.
- Single-stage retrieval: Pure vector or pure keyword search; hybrid consistently outperforms either alone.
- No latency budget: Treating 2 seconds as a vague goal rather than allocating time per component.
- Ignoring re-ranking: Going straight from 100+ candidates to LLM wastes context window and degrades answer quality.
- Conflating retrieval and generation metrics: A bad answer might be due to wrong chunks (retrieval) or misinterpretation (LLM); measure separately to debug effectively.
Code Sketch (Conceptual)
# Query flow pseudocode
def answer_query(user_token: str, query: str) -> Stream[str]:
# Auth + group expansion (10 ms, cached)
principal_ids = auth_service.expand_groups(user_token)
# Query processing (30 ms)
query_embedding = embed_model.encode(query)
# Parallel retrieval (80 ms)
bm25_results = bm25_index.search(
query, top_k=100, filter={"acl": principal_ids}
)
vector_results = vector_index.search(
query_embedding, top_k=100, filter={"acl": principal_ids}
)
# Fusion (5 ms)
fused = reciprocal_rank_fusion([bm25_results, vector_results])
# Re-ranking (150 ms)
candidates = fused[:200]
scores = cross_encoder.score_pairs(
[(query, c.text) for c in candidates]
)
top_chunks = select_top_k(candidates, scores, k=8,
diversity=True)
# Final ACL check (5 ms)
verify_access(user_token, [c.doc_id for c in top_chunks])
# Generation (600–1000 ms to first token)
prompt = build_prompt(query, top_chunks)
return llm.stream(prompt, citations=top_chunks)
This design scales to 500 QPS, stays under 2 seconds p95, and enforces permissions without degrading recall for users with limited access.