Design a Hybrid Search System for a Corporate Knowledge Base
Machine LearningModel answerLast updated
Design a scalable, low-latency search engine that combines keyword and semantic retrieval over 100M enterprise documents with personalized ranking.
Context
Your company runs an internal knowledge platform where employees publish documentation, project trackers, and support threads. With tens of millions of documents across hundreds of teams, employees routinely fail to surface the right content — especially when they use informal language, team-specific jargon, or don't recall the exact title of a page.
You've been asked to design a search system that solves this problem at scale.
Functional Requirements
- Accept free-text queries and return a ranked list of relevant documents.
- Support both exact-term matching (e.g., ticket IDs, error codes) and meaning-based similarity (e.g., paraphrases, synonyms).
- Incorporate user context — team membership, role, and recent activity — to personalize result ordering.
Non-Functional Requirements
- Latency: End-to-end search response within 200ms at the 99th percentile.
- Freshness: Newly created or edited content must appear in results within 60 seconds.
- Scale: Handle a corpus of 100 million documents and sustain 5,000 queries per second.
Your Task
Walk through the full system design. Your answer should cover:
- How documents are processed, chunked, embedded, and indexed.
- The retrieval strategy: how candidates are generated and why a single retrieval method is insufficient.
- The ranking pipeline: how you move from thousands of candidates to a final top-10 with acceptable latency.
- How personalization is incorporated without blowing the latency budget.
- How the system stays fresh — especially for vector indexes, which are expensive to update.
- What you monitor, and how you measure whether search quality is improving or degrading over time.
Be concrete. Use numbers where they matter. Call out trade-offs and failure modes.
Hints
Hint 1
Start by estimating the size of the vector index before picking an ANN algorithm — at 300M chunk embeddings, quantization and sharding are not optional.
Hint 2
Think about where ACL enforcement happens in the funnel. Post-filtering after retrieval can silently return zero results for users with narrow permissions.
Hint 3
Personalization signals should be precomputed features fed to the ranker, not online model calls — otherwise they blow the latency budget.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Estimate Scale
Before drawing any boxes, lock down the constraints that shape every decision.
Key clarifying questions:
- Is the index per-tenant (isolated per customer workspace) or global? Assume per-tenant with strict data isolation.
- What content types? Documents, tickets, comments, attachments.
- Must results respect access controls? Yes — showing a restricted page is a security incident.
Back-of-envelope numbers:
- Chunks: 100M docs × ~3 chunks each = ~300M passages to embed and index.
- Vector index size: 384-dim int8 embeddings ≈ 400 bytes each → ~120GB per tenant group. Float32 at 768-dim balloons to ~900GB. Use quantization (int8 or PQ) and shard across nodes.
- Inverted index: ~2KB average text per doc → ~200GB raw, ~80–100GB indexed.
- Write rate: 1% of docs updated per day = ~1M updates/day = ~12 writes/s average, with bursts to 100s/s. Easily handled by a streaming pipeline.
- Re-ranking cost: 5K QPS × 50 candidates = 250K cross-encoder inference pairs per second. This requires a small distilled model on a GPU fleet, plus aggressive caching of query-doc scores.
2. API Design
POST /search
{
tenant_id, user_id, query,
filters: { type, space, project, updated_after },
page_token, k=10
}
→ { results: [{ doc_id, chunk_id, title, snippet, score, url }], query_id }
POST /search/feedback
{ query_id, doc_id, event: "click"|"dwell"|"copy"|"share", position, timestamp }
The query_id is critical — it ties impressions to user interactions for training data collection, offline evaluation, and debugging.
3. Indexing Pipeline
Document representation:
- Metadata:
doc_id,tenant_id, content type, space/project, title, body, author, team, timestamps. - ACL as a list of principal IDs (users and groups, expanded at query time from a cache).
- Popularity signals: view count, inbound links, recency.
- Chunk-level text + dense embedding per chunk.
- A doc-level embedding (title + summary).
Pipeline stages:
- Change capture: Content platform emits create/update/delete/permission-change events to a message queue, partitioned by tenant.
- Enrichment: Workers parse markup, strip boilerplate, chunk on headings (~300 tokens), extract entities and acronyms, detect language.
- Embedding service: A bi-encoder fine-tuned on enterprise query–document pairs runs on GPU with micro-batching (~100ms windows for throughput).
- Dual write:
- Lexical index (e.g., OpenSearch) with BM25 fields, title and label boosting, ~1s refresh interval.
- Vector index (HNSW or IVF-PQ) storing chunk embeddings plus filterable ACL bitmaps and metadata.
- Feature store: Precomputed doc-level features (popularity, freshness score, link-graph centrality) and user features (team, recent interactions, user embedding).
4. Multi-Stage Retrieval and Ranking
The core insight is that no single retrieval method is sufficient:
- BM25 wins on exact tokens: ticket keys like
PROJ-4512, error codes, product names, acronyms. - Dense retrieval wins on meaning: "how do I request VPN access" matches "Remote network onboarding guide."
- Neither alone achieves acceptable recall at the top of the funnel.
| Stage | Candidates in → out | Approach | Latency budget |
|---|---|---|---|
| Query understanding | raw query → rewritten | Spell correction, acronym expansion, direct-lookup detection (e.g. "PROJ-123") | ~15ms |
| Candidate generation | 100M → ~1,000 | BM25 top-500 + ANN top-500, ACL + tenant pre-filtered in both | ~40ms |
| Fusion + L1 ranker | ~1,000 → ~100 | Reciprocal Rank Fusion, then GBDT (LambdaMART) on cheap features | ~20ms |
| L2 re-ranker | ~100 → top 50 | Distilled cross-encoder (6-layer BERT-size) on query + title + best chunk | ~60ms |
| Blending + rules | top 50 → top 10 | Personalization blend, dedup chunks to doc, diversity by content type | ~10ms |
This totals ~145ms, leaving ~55ms of headroom for network and p99 tail.
ACL enforcement must happen during retrieval, not after. Post-filtering top-500 results silently collapses to zero visible results for users with narrow permissions. Instead: index ACL principals, expand the user's groups once per request (cached, ~5ms), and use filtered ANN with space-level partitioning where selectivity is high.
5. Personalization
All personalization runs as feature lookups into the feature store, not online model calls. This keeps the cost under 5ms.
Features fed to L1 and L2 rankers:
- Direct affinity: Did the user author, edit, watch, or view this doc? When was the last interaction?
- Team affinity: Is this doc owned by the user's team or a known collaborating team, derived from a co-activity graph?
- User embedding similarity: A recency-weighted average of embeddings of recently viewed docs, precomputed hourly.
cosine(user_embedding, doc_embedding)is a single cheap feature. - Session context: The space or project the user is currently browsing.
Cold start handling:
- New user: Fall back to team and role priors — the most-viewed spaces for that team. Then to tenant-wide popularity.
- New document: No engagement signal yet. Use author reputation (historical doc quality), space popularity, and a time-decayed freshness boost. Reserve a small exploration slot (e.g., 1 position in 10 for fresh, under-exposed docs) to bootstrap feedback collection.
6. Freshness
The 60-second SLA requires a main + delta architecture for the vector index:
- Lexical index: Near-real-time refresh (~1s) handles freshness trivially.
- Vector index:
- New and updated chunks land in a small in-memory delta HNSW segment, queried in parallel with the main IVF-PQ segment.
- Periodic compaction (hourly or nightly) merges deltas into the main index and retrains PQ codebooks if embedding drift is detected.
- Updates are handled as tombstone + reinsert — in-place edits degrade ANN graph quality.
- Deletes and ACL changes travel a high-priority queue lane. Tombstones and permission updates are applied as query-time filters immediately, before any index rewrite completes. Correctness takes priority over latency here.
- Model upgrades: A new embedding model requires a full re-embed. Run a shadow index, backfill async, validate offline metrics, then swap via an index alias. Never mix embedding versions in the same index — scores become incomparable.
7. Monitoring and Evaluation
Offline metrics (run on a held-out labeled set):
- NDCG@10, MRR for overall ranking quality.
- Recall@500 for the retrieval funnel (measure the union of BM25 + ANN, not each retriever in isolation).
- Freshness lag p50/p99: time from event to searchable.
Online metrics (from the feedback endpoint):
- Click-through rate and mean reciprocal rank of first click.
- Dwell time and copy/share events as quality proxies.
- Zero-result rate and reformulation rate (user immediately re-queries) as failure signals.
Common mistakes to call out:
- Enforcing ACLs post-retrieval instead of during it.
- Mixing embedding model versions in one index after an upgrade.
- Treating personalization as an online model call rather than a precomputed feature.
- Ignoring position bias when collecting click data for training — clicks are a noisy, position-biased signal and need inverse propensity weighting or a counterfactual logging strategy before being used as labels.