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.
“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
- Partitioning is splitting one logical dataset into pieces. It can happen inside a single machine — Postgres declarative partitioning splits a table into child tables on the same server.
- Sharding is partitioning across machines, so each piece has its own CPU, memory and disk. Every shard is a partition; not every partition is a shard.
- Replication is the orthogonal axis: copies of the same piece on several machines. You almost always do both — each shard is a small replicated cluster. The replication lesson covers that half.
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.
“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.
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.
- Redis Cluster: 16,384 hash slots.
slot = CRC16(key) mod 16384, and a slot table maps slots to primaries. Resharding moves whole slots. - Kafka: the partition count is fixed at topic creation, and partitions are moved between brokers — but adding partitions rehashes keys, which is why it breaks per-key ordering.
- Elasticsearch: the primary shard count is fixed at index creation; growing means a split or a reindex.
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:
- Does the hottest query include it? The key should be in the
WHEREclause of the request you serve most. For a chat app, that isconversation_id; for a multi-tenant SaaS,tenant_id; for an order history page,customer_id. - Is its cardinality high and its load even?
countryhas two hundred values and one of them is huge.user_idhas millions and, usually, no single user is a measurable fraction of traffic. - 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_idcan live in one shard and use an ordinary local transaction.
“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:
- Accept the scatter for rare, admin-style queries. Fine at 16 shards, painful at 1,000.
- Maintain a global secondary index: a second table keyed by the other attribute (
email → user_id), written alongside the primary. It is itself sharded, and keeping it in sync with the primary is a distributed write — usually done asynchronously, so it can briefly be stale. - Copy the data elsewhere: an analytics store or a search index fed by CDC. The Elasticsearch lesson is this answer for text.
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.
- Split the key. Write to
post:123#0…post:123#9chosen at random and sum on read. Ten times the write capacity for that key, at the cost of a fan-out read. - Cache it. For read-hot keys, a short-lived cache in front (even in-process, for a few seconds) absorbs nearly all of it.
- Isolate it. With directory partitioning, give the whale tenant its own shard.
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:
- Snapshot the partition onto the new node.
- Stream changes made since the snapshot (from the WAL, binlog or replication log) until the copy is caught up.
- Briefly block writes to that partition, apply the final changes, and flip the routing.
- 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:
- Data: 500M × 2 KB = 1 TB, ×3 for replication = 3 TB on disk.
- Per shard: aim for something you can restore from backup in under an hour — call it 200 GB. That is 5 shards for data, before growth.
- Writes: if one primary handles ~5,000 writes/s comfortably, 20,000/s needs at least 4.
- Take the max, add headroom, and round up: 8 physical shards, on top of 1,024 logical partitions so you can go to 16 or 64 later by moving partitions.
The number of logical partitions is the one you cannot change cheaply. Make it generous.
The follow-ups, and the one-line answers
- “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.
- “Range or hash?” Hash for even load, range when you need ordered scans and the key is not monotonic.
- “What happens when you add a shard?” With fixed logical partitions, whole partitions move
and nothing rehashes. With
% N, almost everything moves. - “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.
- “How do you handle a celebrity?” Split the hot key, cache it, or move it to its own shard.
- “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.