SysDesignAtlas

Vector Databases at Scale

Sharding an ANN index, replication when the index is derived state, incremental updates, and why "just add a vector column" is often the right answer.

HLDHard11 min readaivector-databaseshardingreplication
Confidence

#What a vector database adds

Vector search is an algorithm. A vector database is that algorithm plus everything a production system needs: durability, sharding, replication, filtering, transactions against metadata, backups, and multi-tenancy.

The first design decision is whether you need a separate one at all.

OptionWhen it's right
Library in-process (FAISS, hnswlib)Small, static corpus; you own the lifecycle; lowest latency
Postgres + pgvectorYou already run Postgres; <10M vectors; you want real transactions and joins
Dedicated vector DB (Qdrant, Weaviate, Milvus, Vespa)>10M vectors, high QPS, complex filtering, or you need the operational features
Managed serviceYou'd rather not operate an index rebuild at 3am
Search engine with vectors (Elasticsearch, OpenSearch, Vespa)You need hybrid lexical+dense and already run one
Object-storage-native (turbopuffer, LanceDB, S3 Vectors)Huge, mostly cold corpora — say thousands of tenants that each query rarely. Data lives in object storage at object-storage prices; hot namespaces are cached on SSD and in memory — see databases on object storage

#Sharding

Above one machine's memory, the index must be partitioned. There are two ways, and they behave very differently.

   RANDOM / HASH SHARDING            SEMANTIC / METADATA SHARDING

   vectors spread uniformly           vectors grouped by tenant,
   across N shards                    topic, or time

   Query → ALL shards                 Query → only relevant shards
           merge top-k                        (if the filter selects them)

   ✓ perfectly balanced               ✓ query touches 1 shard, not N
   ✓ recall is predictable            ✓ per-tenant isolation for free
   ✗ every query hits every shard     ✗ skew: one huge tenant
   ✗ p99 = slowest shard's p99        ✗ cross-shard queries hit all
   ✗ cost scales with shard count     ✗ needs the filter in every query

The standard mitigations: hedged requests (send to a replica after a delay, take whichever answers first), partial results (return after 15 of 16 shards answer, accepting slight recall loss), and — best where it applies — avoid scatter-gather entirely by sharding on the dominant filter.

Shard by tenant if you can. For a multi-tenant product where every query is scoped to one tenant, tenant sharding turns a 16-shard scatter into a single-shard lookup, makes the filter free, and gives you isolation. The problem is skew: your largest tenant may be 1,000× your median. The usual fix is to give large tenants dedicated shards and pack small ones together — the same approach as sharding generally.

#Replication

Replication for vector indexes has a property that changes the design: the index is derived state. It can always be rebuilt from the source documents and the embedding model.

   REPLICATE THE INDEX               REBUILD PER REPLICA

   build once, copy the index        each replica builds its own
   file to each replica              index from the source data

   ✓ fast — file copy                ✓ no large file transfer
   ✓ replicas are bit-identical      ✗ N× the build compute
   ✗ 50-200 GB per copy              ✗ replicas may differ slightly
   ✗ must rebuild-then-redistribute    (HNSW build is order-dependent:
                                        insert order changes the graph)

   → build-once-and-copy is almost always right.
     Treat the index as an immutable artifact, exactly like
     a model checkpoint.

This framing — index as artifact — simplifies everything. Build in a batch job, version it, distribute it to replicas, and route reads to whichever replicas hold the current version. The same distribution problem as model weights, with the same solutions.

#Updates

Most approximate-nearest-neighbour indexes are built assuming the data mostly sits still: the graph of links between vectors is expensive to build and awkward to modify in place. Real document collections change constantly. The standard resolution is the same one storage engines reached — never edit the big structure, keep changes in a small one beside it, and merge periodically.

   LSM-STYLE, THE STANDARD PATTERN

     ┌─────────────────────────┐
     │  Base index (immutable) │   50M vectors, HNSW, on disk/RAM
     └─────────────────────────┘
     ┌─────────────────────────┐
     │  Delta index (mutable)  │   ~500K recent, in memory
     └─────────────────────────┘
     ┌─────────────────────────┐
     │  Tombstone set          │   deleted IDs, a bitmap or Bloom filter
     └─────────────────────────┘

   Query: search BOTH indexes, merge, drop tombstoned IDs
   Merge: periodically fold the delta into a new base,
          rebuild in the background, swap atomically

This is exactly the LSM tree design, and for the same reason. Writes go somewhere cheap (the small delta, not the big graph). Reads pay a small extra cost to search two indexes and combine the results. And the expensive merge — compaction — runs in the background, so no user request ever waits on it.

Deletion is the awkward operation. You cannot cleanly remove a node from an HNSW graph without damaging connectivity, so deleted vectors are tombstoned and filtered at query time. Over time the index fills with dead nodes: recall degrades (the graph routes through nodes that get discarded) and memory is wasted. The trigger for a rebuild is usually a tombstone ratio — commonly 10–20%.

Freshness is a real requirement to negotiate. "New documents searchable within 5 minutes" costs far less than "within 1 second." The delta index handles seconds if it's small; sub-second requires writing to the delta synchronously on the ingest path — the "save document" call doesn't return until the vector is indexed. That couples your write latency to index maintenance: when the index is slow, every save is slow.

#Multi-tenancy

Three models, with a real security dimension:

ModelIsolationCostNotes
Shared index, filter by tenantWeak — a filtering bug leaks data across tenantsLowestFilter correctness becomes a security control
Namespace per tenant, shared clusterGoodMediumCommon default; overhead per namespace limits tenant count
Index per tenantStrongHighestRight for large or regulated tenants

The shared-index model deserves caution: the filter is now the only thing preventing cross-tenant data exposure, and post-filtering strategies that over-fetch and then discard are doing the filtering after the data has left the index. The over-fetched candidates include other tenants' documents, and only that discard step keeps them out of the response — one bug there and they leak. Test this path explicitly, and prefer pre-filtering or partitioning where tenant data is sensitive.

Most products end up hybrid — shared namespaces for the long tail of small tenants, dedicated indexes for large or regulated ones.

#What to monitor

SignalWhy
Recall@k against a golden setThe only real quality signal; run it continuously, not once
p50/p99 query latency, per shardIdentifies the slow shard dragging your tail
Index size and memory headroomRebuilds need double; running out of memory (OOM) mid-rebuild is a classic outage
Tombstone ratioTriggers rebuild before recall degrades
Delta index sizeIf it grows unboundedly, merges aren't keeping up
Indexing lagTime from document write to searchable
Filter selectivity distributionA change here silently changes recall — an over-fetch tuned for filters passing 20% returns too few results when they start passing 2%

Recall monitoring is the one teams skip. Latency is easy to see and recall is invisible — an index can quietly return worse results for months. Maintain a fixed set of queries with known-correct answers, run them against production continuously, and alert on recall drift. Without it you have no idea whether your retrieval is working.

#Check yourself

When is Postgres with pgvector the right vector store?Show answer
Under ~10M vectors when you already run Postgres: competitive HNSW latency, transactional consistency with metadata (no dual write), joins, and one system to operate.
Why does scatter-gather worsen the tail as you add shards?Show answer
A query waits for the slowest shard: with 16 shards at 99% under target, only 0.99¹⁶ ≈ 85% of queries are; at 64 shards, 53%. Mitigate with hedged requests, partial results or avoiding scatter.
Why shard a vector index by tenant, and what is the catch?Show answer
Tenant-scoped queries hit one shard, the filter becomes free and tenants are isolated. The catch is skew — give huge tenants dedicated shards and pack small ones.
How should vector indexes be replicated?Show answer
The index is derived state: build it once as a versioned immutable artifact and copy it to replicas, like model weights, rather than rebuilding per replica.
How are vector index updates handled?Show answer
LSM-style: an immutable base index, a small mutable delta index and a tombstone set; queries search both and drop tombstones; merge in the background and rebuild at ~10–20% tombstones.
How do you stop the document store and vector store diverging?Show answer
An outbox row written in the same transaction as the document, consumed by an idempotent indexing worker, plus reconciliation jobs that compare the stores.
Why is filter correctness a security control?Show answer
In a shared multi-tenant index the tenant filter is all that prevents cross-tenant leaks — and post-filtering discards data after it left the index. Test it, or partition sensitive tenants.
What is the vector-DB metric teams skip?Show answer
Recall@k against a golden query set, run continuously — latency is visible but recall degrades silently.

#What to carry forward

  • Postgres + pgvector handles more than people expect — and avoids the dual-write problem entirely.
  • Scatter-gather makes the tail worse as you add shards. Shard on the dominant filter if you can.
  • The index is derived state — build once as an artifact, distribute to replicas.
  • LSM-style base + delta + tombstones is the standard update pattern; rebuild at ~10–20% tombstones.
  • Dual writes will diverge. Use an outbox and run reconciliation.
  • Filter correctness is a security control in shared multi-tenant indexes.
  • Monitor recall continuously against a golden set. Nothing else will tell you it broke.
00:00
/ 11m