Partitioning & sharding

In one sentence

Split data across nodes by a shard key, scaling writes and storage past one machine. The key decides load balance, which queries stay on one shard, and how painful rebalancing is.

Analogy: A library spread over buildings: shelve by title range and browsing "S" is one trip, but one building gets crowded; shelve by hash and load is even, but browsing a range means visiting every building.

With the shard key, the router hits one shard. Without it, every shard is queried and results are merged, so latency follows the slowest shard.

How it works

  • Range sharding makes scans cheap, but a monotonic key like a timestamp sends every insert to the last shard.
  • Hash sharding spreads keys evenly, but range queries fan out to every shard.
  • Hotspots survive hashing: split a whale key into salted sub-keys or give it its own shard.
  • Never use hash % N: 10 → 11 nodes moves ~91% of keys; use fixed partitions or consistent hashing.
  • Pick a shard key that hot queries include, like tenant_id; a wrong key forces cross-shard joins and 2PC.

Check yourself

Answer to mark it learned; your answers aren't scored.

An LLM trace store is range-partitioned on created_at across 8 nodes. Insert throughput has plateaued: one node is at 100% CPU, the other seven are nearly idle. What's the cause, and the fix?

Go deeper

Consistent hashing ring Interactive lab
Full explanation

Partitioning (sharding) splits a dataset so each node owns a subset; Replication then copies each partition. Replication scales reads; partitioning scales writes and storage.

  • Range partitioning (Bigtable, HBase, CockroachDB): contiguous key ranges per shard. Range scans are cheap, but a monotonic key (timestamp, auto-increment ID) sends every insert to the last shard.
  • Hash partitioning (Cassandra, DynamoDB): hash(key) picks the shard. Even spread, but range queries fan out to every shard.

Hotspots survive hashing: a celebrity key or whale tenant still lands on one shard. Split it with salted sub-keys (key#0..7) and fan its reads out, or give it its own shard.

Rebalancing: never hash % node_count, since adding a node moves almost every key. Map many fixed logical partitions to nodes and move whole partitions, or use Consistent hashing.

Secondary indexes: local ones live inside each shard (cheap writes, scatter-gather reads); global ones are partitioned by the indexed value (one-shard reads, but writes touch several shards and usually update asynchronously).

Choose the shard key so hot queries include it, cardinality is high and load is even. In multi-tenant SaaS that's often tenant_id: queries and transactions stay on one shard, and a vector search never fans out across tenants. Cross-shard joins and transactions (2PC) are the price of a wrong key.

Code Fixed logical partitions, hot-key salting, rebalancing
pythonFixed logical partitions, hot-key salting, rebalancing
import hashlib

N_PARTITIONS = 1024  # fixed forever, far more than nodes; never hash % node_count

# partition -> node map lives in metadata (etcd, a config table), not in code
partition_map = {p: f"db-{p % 4}" for p in range(N_PARTITIONS)}

def partition_of(key: str) -> int:
    # Stable hash: Python's built-in hash() is randomized per process
    digest = hashlib.md5(key.encode()).digest()
    return int.from_bytes(digest[:8], "big") % N_PARTITIONS

def node_for(tenant_id: str) -> str:
    return partition_map[partition_of(tenant_id)]

def hot_write_key(tenant_id: str, seq: int, salts: int = 8) -> str:
    # A whale tenant's writes spread over 8 partitions; its reads fan out to 8, not 1024
    return f"{tenant_id}#{seq % salts}"

def add_node(new_node: str, share: float) -> int:
    # Rebalance by moving whole partitions; no key is ever rehashed
    moved = list(range(0, N_PARTITIONS, round(1 / share)))
    for p in moved:
        partition_map[p] = new_node  # copy the partition's data first, then flip the map
    return len(moved)

print(add_node("db-4", share=0.2))  # 205 of 1024 partitions move (~20%)
Real example

A B2B assistant stores 500M chunk embeddings for 5,000 tenants, sharded by tenant_id over 8 nodes. Every retrieval includes the tenant, so each ANN query hits one shard and isolation is simple. Then one enterprise customer grows to 40% of all vectors: its shard runs at 90% CPU while the others idle. Fix: move that whale to 3 dedicated shards, sub-partitioned by (tenant_id, hash(doc_id)). Its queries fan out to its own 3 shards and merge top-k; every other tenant still hits exactly one.

Trade-offs +3 · −4

+ You gain

  • Scales writes and storage horizontally, past any single machine.
  • Smaller per-shard data and indexes: faster queries, faster rebuilds and restores.
  • Tenant-keyed shards give natural isolation and per-tenant placement (region, hardware).

− You pay

  • Cross-shard queries scatter-gather, so tail latency follows the slowest shard.
  • Cross-shard transactions need 2PC or sagas; joins move into the application.
  • The shard key is close to a one-way door: changing it means migrating all the data.
  • More operations: rebalancing, hotspots, per-shard backups and schema changes.

Use it when

When one node can no longer hold the data or absorb the write rate after vertical scaling, read replicas and caching, or when tenants need physical isolation.

Avoid it when

Early: one well-sized Postgres with replicas carries a lot, and sharding adds permanent complexity. Also avoid it when most queries can't include a common shard key.

Numbers to know 4
  • Going from hash % N to % (N+1) moves ~N/(N+1) of keys (~91% at N=10); fixed partitions or consistent hashing move ~1/(N+1).
  • DynamoDB per-partition ceilings: 3,000 RCU, 1,000 WCU and 10 GB.
  • DynamoDB: 5 local and 20 global secondary indexes per table (default quota); GSIs are eventually consistent.
  • Instagram (2012) mapped several thousand logical Postgres shards onto far fewer physical servers.
Common pitfalls 4
  • A monotonic shard key on range partitioning (timestamps, auto-increment): every insert hits the last shard.
  • Using hash % node_count: adding one node reshuffles nearly all the data.
  • A shard key most queries don't include: everything becomes scatter-gather.
  • Ignoring whales: tenant_id works until one tenant holds 40% of the data. Plan how to split big tenants.
Interview questions 2

Answer out loud first, then reveal.

How do you choose a shard key for a multi-tenant SaaS?Show answer

I start from the dominant queries. If nearly every request is scoped to a tenant, tenant_id keeps queries, joins and transactions on one shard, and makes isolation and data residency easy. Then I check distribution: tenant sizes follow a power law, so I hash tenants onto many logical partitions and keep an escape hatch, moving a whale to dedicated shards with a composite key like (tenant_id, doc_id). Cross-tenant analytics go to a warehouse instead of scatter-gather on the OLTP shards.

One shard is at 90% CPU while the others are idle. What do you do?Show answer

First I find out whether it's one hot key or a hot range. A hot key, like a celebrity or a whale tenant, I cache if it's read-heavy, salt into sub-keys if it's write-heavy, or move to a dedicated shard. A hot range usually comes from a monotonic key like a timestamp, which means the key design is wrong: hash it or prefix it with a well-distributed field. Short term I split the partition and move half; long term I add per-key load metrics so the next one is caught early.