What You'll Learn
- 1Compute exact-search time and memory for a vector corpus and show why flat search stops scaling
- 2Estimate HNSW probe counts from N, M, and ef_search and read the recall-latency curve
- 3Size an IVF-PQ index in bytes per vector and pick the compression level from a recall target
- 4Broadcast, merge, and price a sharded query path in queries per second and cost per query
Why This Matters
Vector databases are the backbone of RAG, recommendation systems, image search, and semantic matching. Choosing the right indexing strategy, understanding distance metrics, and optimizing for scale directly impacts search quality, latency, and cost.
Scale makes the choice forced rather than stylistic. Exact search over 100 million 768 dimension float32 vectors must stream 307 GB of memory, which at 2.0 TB/s is 154 ms before a single comparison is finished. An HNSW index answers the same query after probing roughly 425 vectors, in single-digit milliseconds, at the price of 1 to 10 percent recall. This lesson derives both numbers and shows where the crossover sits.
System Architecture Overview
HNSW Implementation
HNSW (Hierarchical Navigable Small World) builds a multi-layer graph where each node contains a vector and connections to neighbors at multiple levels. Insertion assigns a random level to each node, then connects it to its M nearest neighbors at each level. Search traverses from the top level down, using greedy beam search with an ef parameter to control search width. Key parameters are M (max neighbors per node, typically 16), ef_construction (build-time search width, typically 200), and ef_search (query-time search width, typically 64). The algorithm achieves O(log N) search time with high recall.
Vector DB Operations
Vector database clients provide CRUD operations on collections with configurable index types and distance metrics. Collections are created with a specified dimension and index configuration (HNSW with M/ef_construction or IVF-PQ with nlist/m/nprobe). The write path supports upsert operations for inserting and updating vectors with metadata. The search path accepts query vectors with optional metadata filters and returns the top-k nearest neighbors ranked by distance.
Scaling Strategies
Sharded vector databases distribute vectors across multiple shards using hash-based partitioning. Search queries are broadcast to all shards in parallel, each returning top-k results, then results are merged and re-ranked globally to produce the final top-k. This enables horizontal scaling of both storage and query throughput.
Memory and Exact Search Cost
The floor for any index is the raw payload. For vectors of dimension at bytes per element:
At , , and , the payload is 307 GB, which is 286 GiB of float32. An exact (flat) search must touch all of it, so the wall-clock floor is set by memory bandwidth rather than by arithmetic:
The comparison work is 76.8 billion multiply-accumulates, roughly 15 ms on a modern CPU, so more than 90 percent of an exact query is spent waiting on DRAM. That is the wall every approximate index exists to go around.
HNSW Probe Estimate
HNSW walks a hierarchical graph, entering at the sparse top layer and descending. The layer count is logarithmic in with base , and each layer probes roughly neighbours:
For and that gives 6.6 layers, so costs about 425 distance evaluations instead of 100,000,000: a 235,000x reduction in work. Each probe reads a random 3,072 byte vector, so the working set is 1.3 MB scattered across a 320 GB index and latency is governed by DRAM row misses at 60 to 90 ns each, which is why p99 lands near 9 ms.
| ef_search | Distance evaluations | Recall@10 | p99 latency |
|---|---|---|---|
| 32 | 212 | 0.86 | 6 ms |
| 64 | 425 | 0.93 | 9 ms |
| 128 | 850 | 0.97 | 15 ms |
| 256 | 1,700 | 0.985 | 27 ms |
ef_search is therefore your quality dial: doubling it buys about 4 recall points past 0.93 and doubles latency. Measure the curve on your own query set, because it shifts with dimensionality and data distribution.
Compression: IVF-PQ
Product quantization splits each vector into subvectors and replaces each with a one byte codebook index, so the stored code is exactly bytes:
With 768 dimensions split into 96 groups of 8, bytes, a 32x reduction from 3,072. The whole 100 million vector corpus then fits in:
Adding the 4 byte row id brings it to 10 GB, small enough to hold in RAM on a single modest instance instead of a sharded fleet. The cost is asymmetric distance estimation error, typically 3 to 8 recall points at k = 10, recoverable in part by re-ranking the PQ candidates against stored float16 copies of the top 100.
Sharded Query Path and Cost
Because shards answer in parallel, latency is the slowest shard plus the merge, not the sum:
Eight shards at 9 ms p99 with a 2 ms global merge give 11 ms, whereas naive addition would have predicted 74 ms. This is why adding shards raises capacity without raising latency, until the merge or the coordinator becomes the new tail.
Pricing follows queries rather than storage:
A node at USD 1.50 per hour sustaining 4,000 queries per second costs USD 0.10 per million queries, so at 100 million queries per month search is USD 10 of infrastructure while the embedding calls beside it are typically 20x that.
| Index | Bytes per vector | Total at 100M | Recall@10 | p99 latency |
|---|---|---|---|---|
| Flat float32 | 3,072 | 307 GB | 1.000 | 154 ms |
| HNSW M=16 float32 | 3,200 | 320 GB | 0.93 | 9 ms |
| IVF nlist=4096, PQ 96B | 100 | 10 GB | 0.90 | 4 ms |
| Binary 768 bit | 100 | 10 GB | 0.78 | 3 ms |
Common Mistakes
Running flat search past a few million vectors
Fix: 100M float32 vectors is 307 GB, and streaming it costs 154 ms at 2.0 TB/s regardless of how good your CPU is.
Tuning ef_search on a synthetic recall number
Fix: Measure the recall-latency curve on your own queries: moving ef_search from 64 to 128 buys about 4 recall points and doubles p99.
Mixing vectors from two embedding models in one index
Fix: Neighbour relationships assume one vector space, so re-embed everything and swap indexes atomically instead.
Best Practices
- Store float16 or float32 originals for the top 100 PQ candidates and re-rank, recovering most of the lost recall for 6 percent extra memory
- Broadcast to all shards, take max latency plus merge, and alert on the slowest shard rather than the average
- Pin the distance metric to the embedding model's training objective, since cosine on a dot-product model loses recall
Key Takeaways
- Exact search over 100M x 768 float32 is 307 GB and 154 ms at 2.0 TB/s, which is why approximate indexes exist
- HNSW probes about ef_search x ln(N)/ln(M) = 425 vectors at ef_search 64, a 235,000x cut versus flat search
- PQ at 96 groups stores 96 bytes per vector, taking the 100M corpus from 307 GB to 10 GB
- Sharded latency is max(L_i) plus merge, so 8 shards at 9 ms plus 2 ms merge is 11 ms, not 74 ms
Frequently Asked Questions
How do I choose between HNSW and IVF-PQ?
Decide from memory first, then recall. If the float32 payload fits in RAM with room for the graph, HNSW gives 0.93 to 0.97 recall@10 at 9 to 15 ms and is the simplest thing that works. If 320 GB does not fit, IVF-PQ brings the same corpus to 10 GB at 0.90 recall and 4 ms, at the cost of a re-ranking pass. Most teams run HNSW for the hot partition and IVF-PQ for the long tail.
Why does recall fall when I add metadata filters?
HNSW cannot skip a node it has not visited, so a filter applied after traversal throws away good candidates that the graph never reached. With a filter that keeps only 1 percent of the corpus, unfiltered traversal may return mostly filtered-out neighbours and recall collapses. Push the filter into the traversal with a skip-list or bitset per node, over-probe with a higher ef_search, or partition the index by the coarsest filter you use.
How should I shard a 100 million vector index?
Hash-partition by vector id so every shard holds roughly the same count, keep the full payload on each shard rather than splitting dimensions, and broadcast every query. Eight shards of 40 GB each fit on standard instances and give 8x the ingest throughput; the merge stage only sorts 8 x k candidates, which is microseconds. Re-shard by consistent hashing so a split moves one eighth of the data instead of half.
Interview Questions
Q1: Compare HNSW, IVF-PQ, and flat index for 100 million vectors.
Flat is exact but needs 307 GB and 154 ms of streaming. HNSW needs about 320 GB, answers in 9 ms, and holds 0.93 recall at ef_search 64. IVF-PQ needs 10 GB, answers in 4 ms, and holds 0.90 recall with a re-rank. Flat is only viable under a few million vectors; pick HNSW when RAM allows and IVF-PQ when it does not.
Q2: How does product quantization work?
Split the 768 dimensions into 96 groups of 8, cluster each group into 256 centroids offline, and store one byte per group. Distance to a query is then estimated with 96 lookup tables instead of a 768 dimension subtraction, cutting 3,072 bytes to 96 bytes, a 32x reduction, at a cost of 3 to 8 recall points.
Q3: When would you choose pgvector over a dedicated vector database?
Choose pgvector when you already run PostgreSQL, need transactions and vector search in the same commit, or have fewer than 10 million vectors. Move to a dedicated store past roughly 10 million vectors or 10,000 queries per second, or when you need hybrid search, PQ compression, or cross-region replication built in.