Vector search at billion scale
At a billion vectors, memory is the design constraint: compress the vectors, move the index to SSD or object storage, shard and replicate, and rescore a small candidate set at full precision.
Analogy: A national library can't keep every book on the reading-room shelves. It keeps a compact card catalog at hand, stores the books in the stacks, and fetches only the few you need.
How it works
- Do the arithmetic first: 1B × 768 dims × 4 bytes ≈ 3 TB of raw float32.
- Compress with int8 (4×), binary (32×) or PQ, then rescore the top few hundred with full vectors.
- DiskANN keeps compressed vectors in RAM and the graph plus full vectors on NVMe SSD.
- Hash sharding fans each query out to all shards, so p99 is the slowest one; tenant sharding hits one shard.
- Post-filtering a selective predicate empties your top-k; filter inside the index or partition on the filter.
Check yourself
Answer to mark it learned; your answers aren't scored.
A multi-tenant SaaS hash-shards 1B vectors across 16 shards. Every query is scoped to one tenant, and the largest tenant has 20M vectors. p99 is poor, and cost per query grew each time you added shards. Best change?
Go deeper
Full explanation
Start with the arithmetic: 1B × 768 dims × 4 bytes ≈ 3 TB of raw float32, before any index. Keeping that in RAM, replicated, takes a fleet of big machines. Every billion-scale design trades recall, latency and cost with four levers:
- Compress. Scalar int8 (4×, ~0.77 TB), binary quantization (32×, ~96 GB), product quantization (PQ, e.g. 96 bytes per vector) or Matryoshka truncation (store 256 of 768 dims). Search the compressed codes, then rescore the top few hundred with full vectors.
- Move off RAM. DiskANN keeps compressed vectors in RAM and the graph plus full vectors on NVMe: a billion points on one 64 GB machine. Object-storage engines (turbopuffer, Amazon S3 Vectors) are cheaper and elastic, but cold queries take hundreds of ms.
- Shard and replicate. Hash sharding fans every query out to every shard: cost grows with shard count and p99 is the slowest shard. Sharding by tenant or partition sends a query to one shard. Replicas add QPS and availability.
- Filter inside the index. Post-filtering a selective predicate empties your top-k. Use filter-aware indexes (ACORN, Filtered-DiskANN, payload indexes) or partition on the filter.
Add tiers (hot data in RAM, the long tail on SSD or object storage) and plan reindexing: a new embedding model means re-embedding everything into a new index built side by side (Index freshness & lifecycle).
Code Memory math, then IVF-PQ with full-precision rescoring
import faiss
import numpy as np
d, N = 768, 1_000_000_000
# Memory math first: it decides the architecture
for name, bytes_per_vec in [("float32", d * 4), ("int8", d), ("PQ96", 96), ("binary", d // 8)]:
print(f"{name:8s} {N * bytes_per_vec / 1e12:5.2f} TB")
# float32 3.07 TB | int8 0.77 TB | PQ96 0.10 TB | binary 0.10 TB
# One shard: IVF-PQ, 65,536 clusters, 96 sub-quantizers x 8 bits = 96 bytes/vector
quantizer = faiss.IndexFlatIP(d)
index = faiss.IndexIVFPQ(quantizer, d, 65_536, 96, 8, faiss.METRIC_INNER_PRODUCT)
index.train(sample_vectors(4_000_000)) # ~30-256 training points per cluster
for ids, vecs in stream_shard(batch=1_000_000):
index.add_with_ids(vecs, ids)
def search(q: np.ndarray, k: int = 10, candidates: int = 200, nprobe: int = 64):
index.nprobe = nprobe # recall vs latency dial
_, cand = index.search(q[None, :].astype("float32"), candidates)
full = fetch_full_vectors(cand[0]) # float32 from SSD or object storage
exact = full @ q # rescore at full precision
order = np.argsort(-exact)[:k]
return cand[0][order], exact[order]Real example
Illustrative: marketplace search over 1B listing embeddings (768-d) at 3k QPS, p99 under 100 ms. All-in-RAM HNSW needs ~3.2 TB per replica. Instead: 16 hash shards of ~64M vectors, each a DiskANN-style index with ~6 GB of PQ codes in RAM and graph plus full vectors on local NVMe, 3 replicas each. A query fans out to all 16 shards, each rescoring 100 candidates from SSD; merged p99 lands near 40–60 ms. Region filters are 1–5% selective, so region becomes a partition key, not a post-filter. A new embedding model means re-embedding 1B listings: ~100 tokens each at an assumed $0.02 per 1M tokens is only ~$2k, but index builds take days, so the new index is built side by side and swapped behind an alias.
Trade-offs +3 · −3
+ You gain
- Compression plus rescoring cuts memory 4–32× for a few points of recall you can mostly buy back.
- SSD and object-storage tiers make cost track the data you query, not all the data you store.
- Tenant or partition sharding turns one billion-vector problem into many small ones.
− You pay
- Every approximation layer costs recall, and you only know how much if you measure against exact search.
- Fan-out multiplies cost per query and makes p99 the slowest shard's p99.
- Index builds take hours to days, so embedding-model changes become multi-week migrations.
Use it when
Corpora beyond ~100M vectors, or when RAM dominates the bill: web-scale retrieval, marketplaces, large multi-tenant SaaS, dedup and recommendation candidate generation.
Avoid it when
Under ~50M vectors a single node with HNSW or pgvector is simpler and cheaper. Don't build sharding before you've tried compression and a bigger box.
Numbers to know 5
- 1B × 768 dims: float32 ≈ 3.07 TB, int8 ≈ 0.77 TB, binary or 96-byte PQ ≈ 96 GB.
- DiskANN (NeurIPS 2019): 1B SIFT points on one machine with 64 GB RAM plus SSD, >5,000 QPS, <3 ms mean latency, ≥95% 1-recall@1.
- Hugging Face (Mar 2024): binary quantization kept ~92.5% of retrieval quality, ~96% with rescoring; int8 kept ~97%.
- Amazon S3 Vectors (GA Dec 2025): up to 2B vectors per index; under 1 s for infrequent queries, ~100 ms or less for frequent ones.
- OpenAI (Jan 2024): text-embedding-3-large truncated to 256 dims still beat ada-002 at 1,536 dims on MTEB.
Common pitfalls 4
- Hash-sharding a multi-tenant corpus: every query fans out to every shard though one tenant's data would fit on one.
- Post-filtering with a selective filter: take the top 100, keep the 1% that match, return ~1 result.
- Measuring recall on the float32 index and shipping the compressed one. Measure recall@k against exact kNN in the production config.
- Reindexing in place. Build the new index side by side, dual-write, compare, then flip an alias.
Interview questions 3
Answer out loud first, then reveal.
Design vector search for 1B documents at 1k QPS with p99 under 100 ms.Show answer
I start with memory: 1B × 768 float32 is ~3 TB, so all-in-RAM is out on cost. I'd use a DiskANN-style index per shard: PQ codes in RAM, graph and full vectors on NVMe, rescoring a couple hundred candidates. Shards of ~50–100M vectors, partitioned by tenant if queries are tenant-scoped, otherwise hashed with fan-out, plus 2–3 replicas for QPS and availability. Filters become partitions or use a filter-aware index. I'd measure recall@10 against exact search on a sample, track per-shard p99, and plan blue-green reindexing for embedding-model changes.
Managed or self-hosted at this scale?Show answer
It's a question about the shape of the cost. Managed (Pinecone, turbopuffer, S3 Vectors, Vertex AI Vector Search) wins when the team is small, traffic is spiky or most data is cold, because you pay for storage and queries, not idle replicas. Self-hosting (Milvus, Vespa, Qdrant, or Faiss/DiskANN directly) wins at steady high QPS, where per-query pricing dominates, or when I need custom filtering, data residency or control over rebuilds. I'd model three numbers for both: monthly storage, cost at peak QPS, and the cost of a full reindex. The reindex is the one people forget.
Recall dropped from 0.95 to 0.80 after you added a tenant filter. Why?Show answer
Two likely causes. If we post-filter, the ANN returns its top-k first and the filter throws most of it away, so small tenants get few or wrong results. If we filter during HNSW traversal, a selective filter disconnects the graph and the search gets stuck in regions with no matching nodes. Fixes, in order: partition the index by tenant when tenants are known, use a filter-aware index like ACORN or Qdrant's payload-indexed HNSW, or fall back to exact search when the filtered set is small enough to scan.