← All lessons

Core concepts

Partitioning and sharding

Splitting data across machines is easy to say and hard to undo. The partition key you pick on the whiteboard decides which queries are cheap, where the hot spots land, and what a resize costs.

18 min readUpdated November 2026Free

“We’ll shard the database” is the second most common sentence in system design interviews, right after “we’ll put a cache in front of it”. It is usually said as if it were the end of a thought. It is the start of three harder ones: sharded by what, what happens to the queries that don’t have that key, and what happens when you need more shards.

This lesson is those three questions. Everything else is vocabulary.

Words first, because interviewers mix them up

The point

Sharding exists to scale writes and storage. Reads can be scaled with replicas and caches long before you need it. If your design shards a 50 GB, read-heavy dataset, the interviewer will ask why, and “for scale” is not an answer. A single modern Postgres primary comfortably holds terabytes and tens of thousands of writes per second.

The three ways to assign a key to a shard

Range partitioning

Each shard owns a contiguous range of the key: A–F, G–M, or 2026-01 to 2026-03.

Buys you: range scans. “All orders for customer 42 between March and May” touches one shard, in key order. HBase, Bigtable, Spanner and CockroachDB all split this way.

Costs you: hot spots whenever writes are monotonic. Key by timestamp or by an auto-increment id and every new write lands on the last range — one shard takes all the load while the others sit idle. The fix is to put something non-monotonic first (customer_id, created_at rather than created_at alone), which trades away the global time-range scan you probably did not need.

Hash partitioning

Hash the key, then map the hash to a shard. Keys spread evenly regardless of their distribution.

Buys you: even load, no hot spot from sequential keys.

Costs you: range scans. Adjacent keys land on unrelated shards, so “orders between March and May” is now a query against every shard. Cassandra’s partition key, DynamoDB’s partition key, Kafka’s partitioner and Redis Cluster’s hash slots all work this way.

Directory (lookup) partitioning

A separate service stores key → shard explicitly. Vitess’s vindexes and many in-house tenant routers work like this.

Buys you: total flexibility. Move one noisy tenant to its own shard; rebalance anything without rehashing everything.

Costs you: a lookup on every request and a new critical component. The directory must be fast, highly available and cached — and a stale cache means a write to the wrong shard.

Even load Range scans Resize cost Extra moving parts
Range Only if keys are not monotonic Yes Split a hot range Split/merge logic
Hash (mod N) Yes No Moves almost every key None
Consistent hash / slots Yes No Moves ~1/N of keys Ring or slot table
Directory Whatever you decide Whatever you decide Move exactly what you choose A lookup service

Why hash(key) % N is the trap

The obvious hash scheme is shard = hash(key) % N. It works perfectly until you change N.

Go from 4 shards to 5 and a key stays put only when hash % 4 == hash % 5. For uniformly distributed hashes that is roughly one key in five — so about 80% of your data moves at once, on the day you were already short of capacity.

Where candidates lose it

“We’ll just add a shard” with modulo hashing is the answer that fails the resize follow-up. The data movement is not proportional to the capacity you added; it is nearly the whole dataset, and every cache keyed by shard goes cold at the same moment.

Consistent hashing, and what Redis and Cassandra actually do

Consistent hashing puts both keys and nodes on the same circle of hash values. A key belongs to the first node clockwise from it. Add a node and it takes over only the arc between itself and its predecessor — about 1/N of the keys move, all from one neighbour.

A hash ring with nodes A, B and C. Each key belongs to the first node clockwise from it. When node D is added between C and A, only the keys on the arc between C and D move, from A to D. Every other key stays where it was. ABCDEach key → next node clockwisekeys that stay on their nodekeys that move: C→D arc, from A to DAdd a 4th node: ~1/4 of keys move, all from one neighbour.With hash % N, going 3 → 4 moves ~3/4 of them.Real systems give each node many virtual positions(or use fixed slots) so the arcs come out even.
Adding a node takes over one arc. Nothing else moves.

Plain consistent hashing has a lumpiness problem: with a handful of nodes at random positions, arcs are wildly uneven. Virtual nodes fix it: each physical node appears at many points on the ring (Cassandra’s num_tokens defaults to 16 in recent versions, 256 in older ones), so each owns many small arcs and the totals even out. A bigger machine can simply take more virtual nodes.

Real systems mostly use the simpler cousin: a fixed number of slots, many more than nodes.

The point

The slot trick is worth saying out loud: choose a partition count much larger than the node count you will ever need, and never change it. Scaling then means moving whole partitions between machines, which is a copy, not a rehash. The key-to-partition mapping is frozen; only the partition-to-node mapping changes.

Choosing the partition key

This is the decision the whole lesson exists for. Three tests, in order:

  1. Does the hottest query include it? The key should be in the WHERE clause of the request you serve most. For a chat app, that is conversation_id; for a multi-tenant SaaS, tenant_id; for an order history page, customer_id.
  2. Is its cardinality high and its load even? country has two hundred values and one of them is huge. user_id has millions and, usually, no single user is a measurable fraction of traffic.
  3. Does it keep transactions on one shard? Anything you need to update atomically should share a key. A customer’s orders, line items and payments all keyed by customer_id can live in one shard and use an ordinary local transaction.
Say it like this

“I’d shard orders by customer_id, hashed, into 1,024 logical partitions mapped onto however many physical shards we need. The order-history page always has the customer, so it hits one shard; a customer’s orders and payments commit in one local transaction; and growing means moving partitions, not rehashing. The query I’ve made expensive is ‘all orders in the last hour’ — that goes to an analytics copy fed by change data capture, not to the shards.”

The queries that don’t have the key

Every partition key makes some query a scatter-gather: ask every shard, merge the results. With N shards the latency is the slowest of N responses, and one slow shard sets the pace for every request. Three honest options:

Cross-shard transactions are the same problem with higher stakes. Two-phase commit works and is slow, and a coordinator failing between phases leaves locks held. Most designs avoid them by choosing the key so that atomic units share a shard, and use a saga with compensations for the rest.

Hot keys: when even hashing isn’t even

Hashing spreads keys evenly. It does nothing for one key that gets 10% of the traffic — a celebrity’s profile, a viral post, the default tenant in a SaaS free tier. That key lives on one shard, and that shard melts.

Detecting it is half the work: track per-key request rates at the routing layer, because per-shard metrics only tell you which shard is hot, not why.

Rebalancing without an outage

Moving a partition is a copy followed by a cut-over, and the cut-over is where data is lost:

  1. Snapshot the partition onto the new node.
  2. Stream changes made since the snapshot (from the WAL, binlog or replication log) until the copy is caught up.
  3. Briefly block writes to that partition, apply the final changes, and flip the routing.
  4. Clients with stale routing get a redirect (Redis’s MOVED, Elasticsearch’s routing table) or a retryable error, and refresh.

Automatic rebalancing sounds better than it is. A node that is slow — not dead — can look failed, trigger a rebalance, and pile a full data copy onto a cluster already under stress. Many operators deliberately keep rebalancing a human decision.

Sizing it on the whiteboard

Say 500 million users, 2 KB of profile each, 20,000 writes per second at peak:

The number of logical partitions is the one you cannot change cheaply. Make it generous.

The follow-ups, and the one-line answers

  1. “Why not just use a bigger machine?” Do, until you can’t — vertical scaling is simpler, and sharding is a one-way door. Shard when writes or storage outgrow one primary.
  2. “Range or hash?” Hash for even load, range when you need ordered scans and the key is not monotonic.
  3. “What happens when you add a shard?” With fixed logical partitions, whole partitions move and nothing rehashes. With % N, almost everything moves.
  4. “How do you query by a field that isn’t the shard key?” A global secondary index kept in sync asynchronously, or a separate store fed by CDC. Scatter-gather only for rare queries.
  5. “How do you handle a celebrity?” Split the hot key, cache it, or move it to its own shard.
  6. “How do you do a transaction across shards?” Pick the key so you don’t need one; otherwise a saga with compensations. Two-phase commit only when you can afford its latency and its failure modes.