System Designhard•DECEMBER 2026•18 MIN
Design a Billion-Scale Vector Search Index (HNSW + Sharding)
Approximate nearest neighbors with HNSW graph layers, quantization, scatter-gather sharding, and recall vs latency budgets.
graph traversalscatter-gatherquantizationhybrid searchml-systemsretrievalvector-db
1. Clarifying questions & SLO contract
- Corpus scale:
1 billionvectors,D = 768dimensions (float32),20K QPSread,2K/secstreaming upserts/deletes. - SLO:
p99 ≤ 25 ms,Recall@10 ≥ 0.95. - Filtering: Metadata filters (e.g.
tenant_id,lang = 'en') combined with vector similarity.
2. Back-of-envelope sizing
- Raw float32 vectors:
10^9 × 768 × 4 bytes ≈ 3.07 TBRAM just for vectors! - HNSW graph links (
M = 16): ~32edges ×4 bytes×1.3layer overhead≈ 166 GB. - With SQ8 / PQ compression (4×–8×):
float32→int8SQ8 drops vector RAM to~768 GB(or~192 GBwith PQ16), fitting comfortably across16–32memory-optimized nodes (64 GBRAM each) with asymmetric re-scoring of top-100 candidates from NVMe.
3. Interactive HNSW multi-layer search simulator
Step through Layer 2 → Layer 1 → Layer 0 and compare efSearch = 1 (trapped in local minimum #7) against efSearch = 2 (beam crosses bridge to true nearest neighbor #11):
LOADING HNSW GRAPH SEARCH SIM...
4. Deep dive: sharding, deletes & metadata filtering
- Scatter-gather vs IVF-routed sharding: Partition by
hash(doc_id) % Sfor uniform write/storage balance (S = 16shards). Queries scatter to allSshards in parallel (p99= slowest shard, hedged requests at p95) and merge top-k results. For multi-tenant workloads, route bytenant_idso queries touch only 1 shard. - Soft deletes + background compaction: Removing nodes from HNSW breaks graph navigability. Mark deleted IDs in a Roaring Bitmap checked during traversal, and rebuild/compact segments asynchronously when tombstones exceed
15%. - Pre-filter vs post-filter: Post-filtering (
top-kthen filter) returns empty results on selective filters (1%match). Use inline filtered HNSW (check predicate bitmap during beam expansion) or fallback to exact scan when filter selectivity is<1%.
5. Failure modes & trade-offs
| Tension | Trade-off & Mitigation |
|---|---|
Recall vs latency (efSearch) | Higher efSearch widens Layer-0 beam linearly; tune per query tier (ef=64 default, ef=128 high-precision). |
| Quantization recall loss | SQ8/PQ loses fine ordering; oversample 4× (top-400) in memory and re-score with exact float32 vectors from SSD. |
| Index build memory spike | Build immutable segments offline or on dedicated indexer workers and ship snapshots to read replicas. |