Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 22. Vector database internals
  4. 22.8

Lesson 22.8 · 8 of 8 · 8 min read · Reviewed 24 Nov 2026

Sharding, replication and scaling to billions of vectors

By the end, you can

  • Size a cluster for billions of vectors with back-of-envelope arithmetic.
  • Choose between sharding by id and sharding by tenant.
  • Explain how replicas, consistency settings and rebalancing affect reads, writes and availability.

At a few million vectors, one machine holds the whole index (49.1 covers why that index is approximate). At billions, the vectors no longer fit in one machine’s memory, and one machine cannot answer every query. You split the data into shards and copy each shard into replicas.

Sharding: split the data

A shard is a complete, independent index over part of the collection. A query works by scatter and gather:

query --> coordinator --> shard 1: local top 10
                      --> shard 2: local top 10    --> merge --> global top 10
                      --> shard 3: local top 10

Each shard must return the full k, not k divided by the number of shards: the true top 10 may all sit on one shard. And the query is only as fast as the slowest shard, so tail latencyLatency: The time from sending a request until you get the response, or until the first token arrives when streaming. grows with the number of shards.

Shard by How Good for Watch out for
Hashed id shard = hash(id) mod S One large corpus; even spread of data and load Every query hits every shard
Tenant A tenant’s points go to the shard or shards named by its key Many tenants; a query touches only its tenant’s shards; adds isolation (22.7) A huge tenant makes a hot shard; keep the key low-cardinality
Time Recent data in small hot shards, older data in archive shards Logs, news, tickets Queries over all time still fan out everywhere

A common mix: small tenants share hashed shards with a tenant filter, and the few very large tenants get shards of their own. Qdrant’s documentation, for example, warns that physical shards are expensive, so a custom shard key should have few distinct values.

Replication: copy the data

Each shard is copied onto r nodes, ideally in different zones.

  • Reads spread across replicas, so throughputThroughput: How much work a system completes per unit of time, such as requests per second or tokens per minute. grows with r.
  • Availability: lose a node and the other replicas keep serving.
  • Writes must reach every replica, so writes cost r times as much.

Two or three replicas is typical. Add more for query load, not for safety alone.

Consistency: how fresh is a read?

A write may be acknowledged before every replica has it, and a new vector may wait in a buffer before it is indexed. Stores let you choose. Milvus, for example, offers four levels: strong (always the newest data, more latency), bounded staleness (may briefly miss recent writes; its default), session (you see your own writes) and eventually (fastest, replicas converge later).

For RAGRetrieval-augmented generation (RAG): Retrieving relevant documents at request time and adding them to the prompt so the answer is grounded in them., a few seconds of staleness is usually fine for new documents. It is not fine for deletes and permission changes: a revoked document or a departed tenant must disappear now. Use stronger reads for those paths, or filter on an access list checked at query time.

Rebalancing: adding nodes

When you add nodes, whole shards move to them. Moving a shard copies its data over the network and can slow live queries, so throttle it and run it off-peak. Changing the number of shards (resharding) is much harder, and some stores need a new collection to do it. So create more shards than nodes from day one; Qdrant suggests at least two shards per node, and a shard count that is a multiple of the node count.

Memory and disk tiers

Tier Holds Speed
RAM Graph links and compressed vectors (int8, binary or PQ) Fastest
Local SSD Full-precision vectors for re-scoring, or the whole graph Fast enough for a few reads per query
Object storage Durable copies, cold segments, snapshots Slow; for loading and recovery

The DiskANN paper showed a graph index stored on SSD serving a billion-point dataset on a single workstation with 64 GB of RAM. Disk-based indexes are why billion-scale search does not need terabytes of RAM.

Back-of-envelope sizing

2 billion vectors, 768 dimensions, 2 replicas, about 128 bytes of graph links per vector, nodes with 400 GB of RAM for the index. All figures are illustrative.

Design Bytes in RAM per vector RAM, one copy RAM, 2 replicas Nodes
float32 in RAM 3,072 + 128 6.4 TB 12.8 TB 32
int8 in RAM, float32 on SSD 768 + 128 1.8 TB 3.6 TB 9
64-byte PQ codes in RAM, float32 on SSD 64 + 128 0.38 TB 0.77 TB 2

Then check throughput: if each replica handles a few hundred queries per second at your recall target, the query rate may demand more replicas than memory does. ChunkChunking: Splitting documents into smaller passages before embedding and indexing them. text and metadata usually live in a separate document store, so add that too.

Common mistakes

  • Asking each shard for k / S results, which silently cuts recall.
  • One shard per node, which leaves nothing to move when you add nodes.
  • Sharding by a high-cardinality key, such as user id, into physical shards.
  • Ignoring stale replicas on delete, so removed documents keep appearing in answers.

Key points

  • A shard is an independent index over part of the data. A query fans out to the shards, each returns its local top k, and a coordinator merges them.
  • Shard by hashed id for an even spread across one big corpus; shard by tenant so a query touches only that tenant's shards.
  • Replicas add read throughput and survive node loss, but every write must reach them, and a lagging replica can serve stale or deleted data.
  • Size it: vectors × dimensions × bytes per value, plus graph links, times replicas. Compression in RAM with full vectors on SSD usually cuts the node count several times.
Hands-on labRuns in the Playground

Scatter and gather across shards

Split vectors across shards by hashed id, merge each shard's local results into a global top k, and size a cluster for billions of vectors.

You will have: A sharded search that matches exact search, a recall comparison for two per-shard settings, and a node count for three storage designs.

Steps

  1. Write shard_of() to hash each id onto one of 4 shards, and check the spread is roughly even.
  2. Write scatter_gather(): ask every shard for its local top results and merge them into the global top k.
  3. Measure recall against exact search with k per shard, then with k divided by the number of shards.
  4. Write nodes_needed() and size 2 billion vectors at 768 dimensions with 2 replicas for three designs.

Done when

  • Recall with the full k from every shard is 1.00.
  • Recall with k/4 per shard is lower.
  • int8 in RAM needs 9 nodes; float32 in RAM needs 32.

Open in the Playground No API key needed.

Starter code (Python)
import hashlib
import heapq
import math
import random

rng = random.Random(7)
DIMS, N, SHARDS, K = 12, 1200, 4, 10

def unit(v):
    s = math.sqrt(sum(x * x for x in v))
    return [x / s for x in v]

VECTORS = {i: unit([rng.gauss(0, 1) for _ in range(DIMS)]) for i in range(N)}
QUERIES = [unit([rng.gauss(0, 1) for _ in range(DIMS)]) for _ in range(8)]

def shard_of(vec_id, shards=SHARDS):
    # TODO: hash the id (for example with hashlib.md5) and take it modulo the number of shards
    return 0

SHARD_DATA = [{} for _ in range(SHARDS)]
for i, v in VECTORS.items():
    SHARD_DATA[shard_of(i)][i] = v

def top_k(data, q, k):
    return heapq.nlargest(k, ((sum(a * b for a, b in zip(v, q)), i) for i, v in data.items()))

def scatter_gather(q, k, per_shard_k):
    # TODO: ask every shard for its local top per_shard_k, then merge them into the global top k
    return [i for _, i in top_k(SHARD_DATA[0], q, k)]

def recall(per_shard_k):
    hits = 0
    for q in QUERIES:
        truth = {i for _, i in top_k(VECTORS, q, K)}
        hits += len(truth & set(scatter_gather(q, K, per_shard_k)))
    return hits / (K * len(QUERIES))

print("vectors per shard:", [len(d) for d in SHARD_DATA])
print(f"recall with full k per shard: {recall(K):.2f}")
print(f"recall with k/{SHARDS} per shard: {recall(math.ceil(K / SHARDS)):.2f}")

def nodes_needed(vectors, dims, bytes_per_value, link_bytes, replicas, ram_gb):
    # TODO: bytes per vector = dims x bytes_per_value + link_bytes; multiply by vectors and replicas
    # TODO: return (nodes needed, rounded up, and total RAM in TB)
    return 0, 0.0

# Illustrative: 2 billion vectors, 768 dims, 128 bytes of graph links, 2 replicas, 400 GB RAM per node.
for name, b in [("float32 in RAM", 4), ("int8 in RAM", 1), ("64-byte PQ in RAM", 64 / 768)]:
    nodes, tb = nodes_needed(2_000_000_000, 768, b, 128, 2, 400)
    print(f"{name}: {tb:.1f} TB of RAM, {nodes} nodes")
Show a solution
import hashlib
import heapq
import math
import random

rng = random.Random(7)
DIMS, N, SHARDS, K = 12, 1200, 4, 10

def unit(v):
    s = math.sqrt(sum(x * x for x in v))
    return [x / s for x in v]

VECTORS = {i: unit([rng.gauss(0, 1) for _ in range(DIMS)]) for i in range(N)}
QUERIES = [unit([rng.gauss(0, 1) for _ in range(DIMS)]) for _ in range(8)]

def shard_of(vec_id, shards=SHARDS):
    digest = hashlib.md5(str(vec_id).encode()).hexdigest()
    return int(digest, 16) % shards                    # hash the id: an even spread

SHARD_DATA = [{} for _ in range(SHARDS)]
for i, v in VECTORS.items():
    SHARD_DATA[shard_of(i)][i] = v

def top_k(data, q, k):
    return heapq.nlargest(k, ((sum(a * b for a, b in zip(v, q)), i) for i, v in data.items()))

def scatter_gather(q, k, per_shard_k):
    gathered = []
    for data in SHARD_DATA:                            # in a real cluster these run in parallel
        gathered += top_k(data, q, per_shard_k)
    return [i for _, i in heapq.nlargest(k, gathered)]

def recall(per_shard_k):
    hits = 0
    for q in QUERIES:
        truth = {i for _, i in top_k(VECTORS, q, K)}
        hits += len(truth & set(scatter_gather(q, K, per_shard_k)))
    return hits / (K * len(QUERIES))

print("vectors per shard:", [len(d) for d in SHARD_DATA])
print(f"recall with full k per shard: {recall(K):.2f}")
print(f"recall with k/{SHARDS} per shard: {recall(math.ceil(K / SHARDS)):.2f}")

def nodes_needed(vectors, dims, bytes_per_value, link_bytes, replicas, ram_gb):
    per_vector = dims * bytes_per_value + link_bytes
    total_gb = vectors * per_vector * replicas / 1e9
    return math.ceil(total_gb / ram_gb), total_gb / 1000

# Illustrative: 2 billion vectors, 768 dims, 128 bytes of graph links, 2 replicas, 400 GB RAM per node.
for name, b in [("float32 in RAM", 4), ("int8 in RAM", 1), ("64-byte PQ in RAM", 64 / 768)]:
    nodes, tb = nodes_needed(2_000_000_000, 768, b, 128, 2, 400)
    print(f"{name}: {tb:.1f} TB of RAM, {nodes} nodes")
Quick checkYou must serve 2 billion vectors of 768 dimensions with 2 replicas. Vectors are stored as int8 in RAM, plus about 128 bytes of graph links per vector, and each node has 400 GB of RAM for the index. About how many nodes do you need?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.