Build a Distributed Approximate Nearest Neighbor Search Engine


databases distributed-systems scalability

AI System Design Deep Dive

Distributed ANN Search Engine

Every shard you add makes the index bigger and the median query slower.

⏱ 14 min read 📐 Advanced 🗃️ Vector Search

Each of our 48 index shards is fast. Measured on a quiet node with a warm page cache, a single shard answers a 768-dimensional top-64 query over its 258 million vectors in 7ms at p50 and 41ms at p99. Forty-eight of those, queried in parallel, with a coordinator that adds 1.4ms of measured overhead.

The median fan-out query takes 38ms.

That is not a bug and it is not coordinator overhead. It is arithmetic, and a restaurant kitchen makes it concrete: one cook plating one dish is quick, but a table of 48 covers that must all leave together waits on the one cook who dropped a pan, and the bigger the table the better the odds that somebody drops a pan. A scatter-gather query finishes when its slowest shard finishes, and the slowest of 48 independent draws from a latency distribution is not a typical draw. For the maximum of 48 samples to land below some threshold, all 48 have to land below it, so the median of the maximum sits at the quantile q where q^48 = 0.5, which is q = 0.9857. The median fan-out query is served at the p98.6 of a single shard. Our p99 is worse still: q^48 = 0.99 gives q = 0.99979, so the fleet p99 is governed by a single shard’s p99.98, which on a long-tailed distribution is 168ms, four times the single-shard p99 we were so pleased with.

You do not fix a kitchen like that by hiring faster cooks, and we could not fix this fleet by buying faster nodes. The three fixes are the ones a kitchen would reach for: send fewer plates to each table, have a second cook start the same dish when the first one is late, and let the table leave with 47 plates rather than holding all 48 hostage to the slowest one.

Key Insight

Sharding an ANN index is a capacity decision that silently becomes a latency decision. Partitioning buys you a corpus that no longer fits in one machine, and charges you the tail of every shard you have to wait for.

So the design brief is not “shard the index”. We know how to shard an index; posts in this track already covered the single-node HNSW and quantization story at a billion vectors, namespace isolation for multi-tenancy, incremental segment updates, and epoch versioning for model swaps. This post is about the four problems that only exist once the index is in pieces: how wide the fan-out has to be, how to stop waiting for the slowest shard, how to merge rankings that were produced by 48 independent approximations, and how to move a vector between shards when its graph neighbours stay behind. We need to solve for fan-out width, tail latency, merge correctness, and online rebalancing simultaneously, and three of those four trade directly against each other.

Requirements and Constraints

Functional Requirements

  • Return the global approximate top-k nearest neighbours for a query vector over the whole corpus, not per shard
  • Support metadata pre-filtering by tenant_id and created_at range, pushed down to the shard
  • Accept writes continuously: 11,000 upserts/s steady, 90,000/s during bulk ingest
  • Add, split, and drain shards without a read-path pause
  • Report per-query provenance: which shards were probed, which were missing, which replica answered

Non-Functional Requirements

  • Throughput: 9,400 QPS read, peak 14,100 QPS
  • Latency: p50 under 25ms, p99 under 90ms, p99.9 under 200ms, measured end to end at the coordinator. Fan-out latency plus a 5.6ms fixed budget (3.1ms encoder, 0.31ms centroid probe, 0.8ms re-score, 1.4ms coordinator)
  • Quality: recall@10 at or above 0.95 against exact brute-force search on a 50,000-query held-out sample
  • Capacity: 12.4 billion vectors, 1,536-dimensional from the encoder, truncated to 768 via Matryoshka before indexing
  • Availability: single-node loss invisible to queries, single-rack loss costs at most 2 recall points
  • Cost: under $0.006 per 1,000 queries all in

Constraints

  • Vectors are 768-d after MRL truncation, cosine similarity, L2-normalised at write time so cosine reduces to inner product
  • Index is HNSW with M=32 plus PQ-192 compression; the full-precision copy lives on NVMe and is never resident
  • Nodes are 16 vCPU, 128 GiB RAM, 2 TB NVMe. No GPUs on the serving path
  • Deliberately out of scope: the embedding model itself, cross-encoder re-ranking above the ANN layer, and the hybrid sparse-dense lane

The capacity number is what forces the partition. At 768-d with PQ-192, each vector costs 192 bytes of code plus 138 bytes of HNSW neighbour lists, which is 330 bytes resident. Times 12.4 billion is 4.09 TB of index. There is no single machine in our fleet that holds that, so the corpus is sharded whether or not we want the fan-out.

Watch Out

The 138 bytes of neighbour lists do not shrink when the vectors do. Links are 42% of resident footprint here, and a plan that halves the embedding dimension to halve memory delivers a 29% reduction, not 50%, and lands 42% over a halved budget. Size the graph before you size the vectors.

Key Insight

Only one requirement in that list is load-bearing. The 4.09 TB capacity number forces the partition, and every latency, recall and cost target below it is a negotiation with the fan-out that the partition created. Write the capacity line first and read the rest as consequences.

High-Level Architecture

Six components, and only three of them are on the query path.

Distributed ANN architecture: control plane with shard map and centroid registry, a query coordinator, 48 index shards with 3 replicas each of which 6 are probed, a merge heap, an exact re-scorer reading full-precision vectors from NVMe, and the response

A query arrives as text. The query encoder produces a 1,536-d embedding and truncates it to 768 dimensions, which costs 3.1ms and is the single largest fixed cost in the budget. The query coordinator takes that vector and does two cheap things: it dots it against 4,096 IVF centroids to find the six shards most likely to hold neighbours, and it reads the shard map to turn those six shard IDs into six concrete replica endpoints. It then scatters the query to those six replicas, each of which searches its local HNSW graph with efSearch=192 and returns 64 candidate IDs. The coordinator merges the 384 IDs into a bounded heap, discards the per-shard scores entirely, fetches the 384 full-precision vectors from NVMe, and re-scores them exactly to produce the final top-10.

Three things in that paragraph are the whole design. First, it probes 6 shards of 48 rather than all 48, which is what moves the median of the maximum from the p98.6 of a shard to the p89. Second, it hedges: a shard that has not answered by its own p95 gets its query sent to a second replica, which costs 4.8% extra shard load and takes p99 from 104ms to 61ms. Third, it throws away the scores the shards computed and recomputes them, because 48 independent quantizers produce 48 incomparable score scales and the merge is biased without it.

The shard map is an explicit 48-row Postgres table with a generation counter, not a hash ring. The centroid registry holds 4,096 centroid vectors and their shard bindings in 6.3 MB on disk as fp16, expanded to 12.6 MB of fp32 in the coordinator. The full-precision store is 19 TB of fp16 vectors, 396 GB of it on each shard’s own NVMe, and it exists solely to answer “what is the real distance” for the 64 candidates that shard just nominated. Neither the shard map nor the centroid registry is on the critical path in any meaningful sense: both are cached in the coordinator and refreshed on a generation bump.

Key Insight

The single most important architectural decision is that the shards are allowed to be wrong. Their job is recall, not ranking. Ranking happens once, centrally, on full-precision vectors, over 384 candidates. That separation is what lets every shard use an aggressive approximation without the approximations compounding across the merge.

The Fan-Out Arithmetic

This component does not exist. It is the constraint every other component is built around, and it is worth making precise before designing against it.

A smart engineer’s first instinct about scatter-gather is that parallelism makes it free: 48 shards searching at once should take as long as one shard searching. That is true of the mean and false of everything anyone cares about. The quantity you serve is the maximum over the shards, and the maximum of n independent draws has a distribution that shifts right as n grows, with no upper bound in sight.

If a single shard’s latency has CDF F, then the fan-out latency over n shards has CDF F(x)^n. Inverting that for a target quantile p gives the single-shard quantile you are actually serving at:

# What single-shard percentile the fan-out's p-th percentile is served at.
import numpy as np

def effective_shard_quantile(target_p: float, n_shards: int) -> float:
    """F(x)^n = target_p  =>  F(x) = target_p ** (1/n)."""
    return target_p ** (1.0 / n_shards)

# Our measured single-shard latency distribution, in milliseconds.
SHARD_LATENCY_MS = {
    0.50: 7.0, 0.75: 11.0, 0.90: 15.0, 0.95: 19.0,
    0.99: 41.0, 0.995: 62.0, 0.999: 112.0, 0.9999: 240.0,
}
_qs = np.array(sorted(SHARD_LATENCY_MS))
_ms = np.array([SHARD_LATENCY_MS[q] for q in _qs])

def fanout_latency_ms(target_p: float, n_shards: int) -> float:
    q = effective_shard_quantile(target_p, n_shards)
    # Log-linear interpolation in the tail; the tail is roughly exponential.
    return float(np.exp(np.interp(q, _qs, np.log(_ms))))

for n in (1, 6, 12, 48, 192):
    p50 = fanout_latency_ms(0.50, n)
    p99 = fanout_latency_ms(0.99, n)
    print(f"n={n:3d}  shard_q@p50={effective_shard_quantile(0.5, n):.5f}  "
          f"p50={p50:6.1f}ms  p99={p99:6.1f}ms")

# n=  1  shard_q@p50=0.50000  p50=   7.0ms  p99=  41.0ms
# n=  6  shard_q@p50=0.89090  p50=  14.6ms  p99= 103.6ms
# n= 12  shard_q@p50=0.94387  p50=  18.3ms  p99= 135.7ms
# n= 48  shard_q@p50=0.98566  p50=  37.6ms  p99= 167.9ms   <- our 48-way
# n=192  shard_q@p50=0.99640  p50=  69.1ms  p99= 231.2ms

Read the n=48 row against the n=6 row. Going from 6 probed shards to 48 costs 23ms of median latency and 64ms of p99 latency, and buys only the recall difference between probing 6 clusters and probing all of them. Read the n=192 row and notice that a plan to “just use smaller shards for better parallelism” makes the median worse by 31ms. Shard count is a latency cost, paid on every query, forever.

Two levers follow directly. Reduce n by partitioning so that most shards are provably irrelevant. Reduce the effective tail of F by sending a second copy of the request when the first is late. Everything in the next two sections is one of those two levers.

Key Insight

The quantity that governs a fan-out system is the shape of a single shard's tail, not its typical latency. Halving a shard's p50 moves the fleet p50 by almost nothing; halving its p99.9 moves everything. Optimise the part of the distribution you were previously allowed to ignore.

Real World

This is the "tail at scale" problem Dean and Barroso described from Google's serving fleets, where a 1-in-100 slow response on one leaf makes 63% of 100-leaf queries slow. Elasticsearch, Vespa, and Milvus all hit the same wall: Vespa's default is to group content nodes so a query touches one group rather than the whole fleet, which is the same `n`-reduction move by a different name.

The Partitioner

This component decides which shard a vector lives on, and in doing so decides how many shards every query has to wait for.

Random partitioning requiring a 48-way scatter with the median at the p98.6 of one shard, versus clustered IVF-centroid partitioning requiring a 6-way scatter with the median at the p89, plus a shard split that rebuilds both halves because HNSW graphs are not relocatable

There are three candidate strategies and the first one is the one everybody ships first.

Random partitioning assigns shard_id = hash(vector_id) % 48. It is trivially balanced: every shard holds 258M vectors to within 0.3%, every shard receives 1/48 of writes, and adding a shard is a rehash. It is also the worst possible choice for query latency, because a query’s true nearest neighbours are uniformly scattered across all 48 shards, so correctness requires probing all 48. You cannot skip a shard under random partitioning without skipping a random 1/48 of the candidate set.

Clustered partitioning runs k-means over a 40M-vector sample to produce 4,096 centroids, assigns each centroid to a shard, and routes each vector to its nearest centroid’s shard. Now the corpus is organised by geometry: vectors about quarterly financial reporting are physically co-located, and a query about quarterly financial reporting can probe the six shards holding the nearest centroids and ignore the rest. This is IVF, applied at the shard level rather than within a single index.

Premium Content

Unlock the full article along with everything else in the archive — all in one place.

In-depth analysis Expert insights Full archive access
Unlock Full Article