Build a Machine Learning Document Search Engine
Machine LearningModel answerLast updated
Design a production search system that combines keyword and semantic retrieval, enforces tenant-level access control, and ranks results with learned models.
You're building a search engine for a SaaS product that indexes workplace documents—files from cloud storage, project management tools, internal wikis, and communication platforms. Users type queries in natural language or keywords and expect relevant results from only the documents they're permitted to see.
Your system must handle multiple organizations (tenants), each with its own corpus and permission rules. A typical deployment serves thousands of tenants; the largest tenant may have tens of millions of documents.
Design the end-to-end system. Cover:
- Requirements and scale assumptions: query volume, corpus size, latency targets, privacy and compliance constraints, and cost considerations.
- Indexing pipeline: how documents are ingested, parsed, chunked, and prepared for search.
- Retrieval architecture: how you find candidate results quickly—both exact keyword matches and semantically similar content.
- Ranking: how you order candidates by relevance, using features and learned models.
- Access control enforcement: how you guarantee users never see documents they lack permission to access, even under caching or partial failures.
- Evaluation and monitoring: how you measure search quality when click data is sparse and you cannot manually inspect tenant data.
- Scalability and operational concerns: caching, freshness, multilingual support, and cost trade-offs.
Be concrete: state numbers, name algorithms and data structures, explain trade-offs, and identify the failure modes that matter most in production.
Hints
Hint 1
Start with requirements—especially the difference between content freshness SLA and permission revocation SLA, and why one must be stricter.
Hint 2
Access control is the hardest part: decide whether to filter during retrieval (early binding) or after (late binding), and explain how each affects recall and security.
Hint 3
Hybrid retrieval means running keyword (BM25) and semantic (vector) search in parallel, then merging results; explain how to combine scores from different retrieval methods.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Machine Learning Document Search Engine
What makes this question hard
Many candidates sketch "BM25 plus embeddings plus a reranker" and stop. Strong answers differentiate on two dimensions:
- Access control correctness. Permission leaks are catastrophic in enterprise search. One exposed confidential file can end a contract.
- Credible evaluation strategy. You cannot read tenant data and clicks are sparse, so you need offline metrics and a sampling plan that respects privacy.
Start with requirements, then make access control and evaluation your focus areas.
1. Requirements and scale
Functional scope
- Support keyword queries, natural-language questions, and filters (date, author, document type, source).
- Return ranked results with snippets and source attribution.
- Integrate with various data sources: cloud storage, wikis, ticketing systems, chat archives, code repositories.
Non-functional targets
| Metric | Target |
|---|---|
| Tenants | 5,000 organizations; largest has ~50M documents |
| Total corpus | ~1B documents → ~8B chunks (after splitting) |
| Peak QPS | ~4,000 queries/sec |
| Latency | p95 end-to-end < 500 ms (retrieval ≤ 150 ms, ranking ≤ 250 ms) |
| Content freshness | New or updated docs searchable within 5 minutes |
| Permission freshness | Revoked access effective within 60 seconds |
| Privacy | Tenant isolation, PII tagging, regional hosting, encryption at rest, 30-day hard delete |
| Cost | Embeddings at 768-dim float32 = ~3 KB/chunk → ~24 TB. Quantize to uint8 → ~800 GB, feasible in memory. |
Why permission freshness is stricter: A user losing access to a salary spreadsheet must not see it in search results immediately, even if indexing the latest payroll doc can wait a few minutes.
2. High-level architecture
Data sources → Connectors → Ingestion queue → Parse/chunk/embed → Index (inverted + vector) + Doc store
↓
User query → Query understanding → Retrieve candidates (BM25 + ANN) → Rank → Filter & render
3. Indexing pipeline
Steps
- Connectors pull from APIs or listen to webhooks (Google Drive, Confluence, Slack, GitHub). Emit events to a partitioned queue (Kafka, one partition per tenant).
- Parser service extracts text (Apache Tika for Office/PDF; Tesseract OCR for scanned images), detects language, removes boilerplate.
- Chunking splits documents into ~400-token passages with 50-token overlap, preserving heading structure so chunks stay coherent.
- Enrichment tags PII, extracts entities, computes near-duplicate fingerprints (SimHash), and classifies sensitivity.
- Embedding runs a multilingual sentence-transformer model (e.g., multilingual-e5-large) in batched GPU inference.
- Write to inverted index (Elasticsearch/OpenSearch for BM25), vector index (HNSW in a specialized store like Weaviate or Qdrant), and document metadata store (PostgreSQL or DynamoDB).
Incremental updates
- Hash document content; re-parse and re-embed only if the hash changed.
- Permission-only changes skip parsing and embedding, update ACL fields directly, and propagate to the index within 60 seconds via a fast path.
Model versioning
- Pin the embedding model version in metadata. When upgrading, build a shadow index with the new model, validate quality, then atomically switch traffic.
4. Query understanding (runs first, ~20 ms)
- Spelling correction using a tenant-specific vocabulary, so internal names like "k8sfrontend" are preserved.
- Synonym expansion mined from tenant co-occurrence logs ("OKR" → "objective key result").
- Language detection to route queries to language-specific retrievers if needed.
- Query embedding with the same model used for documents.
5. Retrieval: hybrid approach
Run two retrieval methods in parallel, per tenant:
Lexical (BM25)
- Inverted index over title, body, author fields.
- Strong for exact entity names, error codes, identifiers ("JIRA-1234").
Semantic (dense vectors)
- Approximate nearest neighbor search (HNSW or IVF with product quantization) on the query embedding.
- Captures paraphrase and conceptual similarity.
Fusion
- Use Reciprocal Rank Fusion:
score(doc) = Σ 1/(k + rank_i)wherek=60. - This merges ranked lists without calibrating raw scores from different engines.
- Take top ~200 candidates for ranking.
6. Ranking
Stage 1: Lightweight LTR model
- Train a LambdaMART (LightGBM) model on ~150 features:
- BM25 scores per field, dense similarity
- Recency (log-scaled age)
- Popularity within tenant (prior click-through rate)
- Organizational proximity (same team as user, from the org graph)
- Source type priors
- Runs over ~200 candidates in ~10 ms CPU.
Stage 2: Neural reranker (cross-encoder)
- A small transformer (e.g., distilled MiniLM) that jointly encodes query and passage.
- Score top ~40 candidates from stage 1, batched on GPU, ~120 ms.
- This is where the biggest relevance gains come from.
Post-processing
- Collapse chunks to documents: keep the highest-scoring chunk as the snippet.
- Deduplication: use SimHash clusters to drop near-duplicates; keep the most recent or canonical version.
- Diversity: ensure results span multiple sources when possible.
Personalization (use sparingly)
- Light signals: recently viewed docs, team-level popularity.
- Avoid per-user models—data is too sparse, and they risk leaking cross-user behavior.
7. Access control enforcement (critical)
Approach: early binding (filter during retrieval)
- Store
allowed_principals[]on every chunk in both inverted and vector indexes. - At query time, expand the user ID into
{user_id, all transitive group memberships}. Cache this expansion for ~5 minutes. - Pass this set as a mandatory filter to the retrieval engines, so only authorized documents enter the candidate set.
Why not post-filtering?
- If you retrieve top-k globally, then drop unauthorized items, users with narrow permissions get almost no results.
- Aggregates (facet counts, result totals) can leak the existence of hidden documents.
Filtered ANN search
- Use vector databases that support pre-filtered HNSW (e.g., Qdrant, Weaviate).
- For very restrictive filters (user sees <1% of corpus), fall back to exact search over the permitted set.
Defense in depth
- Tenant isolation: partition data by tenant_id. Large tenants get dedicated index shards.
- Late verification: before rendering, re-check each document against a live ACL service or a recent revocation log to close the window between permission change and index update.
- Derived surfaces: autocomplete, suggestions, "related documents," snippet highlighting, and any LLM-generated answers must respect the same ACL filter. Autocomplete dictionaries are built per-user or from the filtered corpus only.
- Cache keys include ACL identity:
(tenant, query_normalized, hash(user_groups)). Never share cache entries across users with different permissions. - Fail closed: if the ACL service is unreachable, return partial results or an error, never unfiltered data.
8. Evaluation and monitoring
Offline metrics
- Recall@100 for retrieval (did the right doc appear in the candidate set?).
- NDCG@10, MRR for ranking.
- Build evaluation sets from:
- Consenting tenants who donate labeled query-document pairs.
- Synthetic queries generated by an LLM from document summaries, then human-validated.
- Public or anonymized corpora for regression testing.
- Slice metrics by language, source type, query length, and tenant size.
Online evaluation
- Interleaving experiments: mix results from two rankers and measure which items get clicked more.
- A/B testing on CTR, zero-result rate, time to first click, reformulation rate.
- Session-level metrics: successful search = click + dwell time >30s, or no reformulation.
Monitoring
- Latency (p50, p95, p99) per stage.
- Zero-result rate and very-low-CTR queries (candidates for query understanding improvements).
- Index lag (time since last document update).
- Permission cache hit rate and ACL service latency.
- Embedding model drift: periodically re-run offline eval on a frozen test set.
Guardrails
- PII/sensitivity classifiers block snippets or whole results containing SSNs, credit cards, API keys.
- Toxicity filters flag potentially harmful content in user-generated sources (chat logs).
9. Scalability and operational concerns
- Sharding: partition by tenant_id; route queries to tenant shards. Co-locate inverted and vector indexes for a tenant to minimize cross-shard joins.
- Caching: cache query embeddings (keyed by normalized query), principal expansions (keyed by user+timestamp), and result pages (keyed by tenant+query+ACL hash).
- Multilingual: use a single multilingual embedding model; BM25 analyzer per language; store language metadata to tune snippet extraction.
- Cost: embedding inference is the biggest GPU cost. Batch updates and only re-embed changed chunks. Quantize vectors to uint8 or use product quantization to cut memory 10×.
- Freshness: incremental indexing via a queue. Critical updates (permission changes) jump the queue and propagate within 60 seconds.
Common mistakes
- Post-filtering ACLs. Breaks recall for restricted users and can leak existence of hidden docs via counts.
- No distinction between content and permission SLA. Permissions must propagate faster.
- Training one model across all tenants without consent. Violates data isolation.
- Ignoring embedding model versioning. Mixing old and new embeddings in the same index breaks similarity search.
- Caching results without including ACL identity in the key. Leaks documents across users.
- No offline evaluation story. "We'll measure CTR" fails when queries are sparse and diverse.
Complexity and scale summary
- Indexing: O(D × C) where D = documents, C = chunks/doc. Embarrassingly parallel by tenant.
- Retrieval: O(log N) for inverted index, O(log N + k·d) for HNSW ANN.
- Ranking: O(k · f) for LTR with k candidates and f features; O(k · T) for transformer reranker with T layers, batched on GPU.
- Storage: ~1 TB for quantized vectors, ~2 TB for inverted index, ~500 GB for metadata, replicated 3×.
This design balances retrieval quality, security correctness, and operational cost for a production enterprise search engine.