Sharding in system design: choosing a shard key, four case studies and resharding
When you really need to shard, range vs hash vs consistent hashing, the three properties of a good shard key, four case studies (orders, payment transactions, device metrics, Discord messages), global IDs, cross-shard queries, and resharding without downtime using logical shards.
On this page
1. The problem
The order table is sharded by hash(user_id) % 4. Adding a fifth DB: % 5 moves about 80% of keys. The "shop's orders" page has no user_id, so it queries all 5 shards; and two shards accept the same email because uniqueness is only checked per shard.
2. Key idea
Sharding is like splitting a library across buildings; shelve books by the wrong key and readers run through every building for one book. Shard when indexes, caches, replicas and partitions still can't handle the write load or the data size. The price: global unique constraints, foreign keys, transactions and joins are gone. Once you shard, use logical shards (a fixed hash % 1024, changing only the logical → physical map).
| Strategy | Use when | Don't use when |
|---|---|---|
| Hash (default) | spreading keys evenly | you need cheap range queries |
Range (created_at, id) |
range queries, dropping old data by range | new data takes most of the load: hot spots |
Directory (a key → shard table) |
moving individual keys, isolating big tenants | the lookup table can't be cached and becomes a bottleneck |
2.1 How do you choose a shard key?
Pick a key your most common queries always carry. A good key is the root entity (orders by user_id), small, high-cardinality (country_code with ~200 values is bad) and stable. Hash spreads keys evenly, not load: an account with 100 million followers still lands on one shard; split it into sub-keys (celeb:42#0..#15).
| System / table | Key | Notes |
|---|---|---|
E-commerce order |
HASH(user_id) |
embed the logical shard in order_id so detail lookups go straight there |
Payments transaction |
don't shard until forced | a transaction belongs to two accounts; when forced, double-entry rows each sharded by account_id |
Chat message |
HASH(channel_id) |
key (channel_id, message_id), ordered by Snowflake ID |
3. In Java
// Snowflake ID with an embedded logical shard: 41 bits ms | 10 bits logical shard | 12 bits sequence
long nextId(long logicalShard) { // 0..1023
long now = System.currentTimeMillis() - EPOCH;
synchronized (this) {
if (now == lastMs) {
seq = (seq + 1) & 0xFFF;
if (seq == 0) now = waitNextMs(lastMs); // 4,096 IDs used up in this ms
} else {
seq = 0;
}
lastMs = now;
return (now << 22) | (logicalShard << 12) | seq;
}
}
long shardOf(long orderId) { return (orderId >> 12) & 0x3FF; } // detail lookups need no lookup tableIDs grow with time, so an index on (channel_id, message_id) both locates and paginates. A clock moving backwards (NTP correction) can create duplicates: wait or refuse when you detect it.
Cross-shard queries and zero-downtime resharding
- Missing shard key: for orders by
shop_id, add anorder_by_shoptable sharded byshop_idand fed by outbox/CDC; replicate small, rarely changing tables (catalogues) to every shard; for a global top 20, merge each shard's top 20 or use an analytics store. Scatter-gather is only for rare admin tasks. - Global uniqueness: a lookup table
email → user_idsharded byemail, written first, with a unique constraint. - Resharding: 1,024 logical shards on 16 DBs (64 each). When one DB is overloaded, move half its logical shards to a new DB: bulk copy via snapshot + CDC → compare row counts and checksums → block writes for a few seconds, lag to 0, switch the map → keep the old data for rollback, then delete it.
- Double-writes from the app are easy to understand but not atomic and easy to miss a write path; CDC (Debezium, VReplication) misses nothing. If you have tooling (Vitess
Reshard, Citusrebalance_table_shards), use it. - Consistent hashing (Cassandra, DynamoDB): a hash ring where adding a server moves only ~1/N of keys, with many virtual nodes per server.
- Each physical shard still has a primary + replicas, with the same replication-lag issues.
4. Working with AI
Delegate to AI: estimating shard counts from TPS and data size, a router choosing the DataSource, scripts checking key distribution across shards.
Check yourself:
- There's a measured write or size bottleneck; replicas, caches and partitions were tried.
- The most common queries always carry the shard key.
- Logical shards (or consistent hashing), not
hash % number_of_DBs. - Global uniqueness has its own lookup table; no cross-shard joins.
5. Exercises
Exercise 1: Shard a ride-hailing trips table
trip has 2 billion rows and 4,000 new trips/s at peak. Queries: (a) drivers view their current trip and history, (b) riders view their history, (c) operations view every active trip in a city, (d) look up a trip by trip_id. AI proposes HASH(city_id). What do you choose?
Solution to Exercise 1
city_idhas few values and big cities become hot spots: reject it.- The main table uses
HASH(rider_id): many riders, an even spread, and rider history is the most common query. Primary key(rider_id, trip_id). trip_idis a Snowflake with the rider's logical shard embedded → (d) goes straight to the shard.- (a) A side table
trip_by_driversharded bydriver_id, fed by an outbox; the current trip lives in Redis. - (c) Hot, small data: Redis/streams by
city_id, no DB scatter-gather. - 1,024 logical shards on 8 DBs to start: 500 write TPS per DB, 2–3x headroom for growth.
Exercise 2: Review a "shard from day one, just in case" proposal
A startup with 50,000 users, the largest table at 3 million rows, 40 write TPS. AI proposes "shard across 8 PostgreSQL instances by user_id % 8 now, so it won't hurt later". Assess it.
Solution to Exercise 2
- There's no bottleneck: 3 million rows and 40 TPS is a job for one small PostgreSQL. Sharding early pays the full price (no transactions, joins or global uniqueness; every query carries the key) for no benefit.
user_id % 8is also the most painful scheme to reshard: going to 9 DBs moves almost everything.- Proposal: one DB, the right indexes, replicas when reads grow, partitions at tens of millions of rows. Cheap preparation: every user table carries
user_id, IDs don't depend on one DB's auto-increment. When forced to shard, do it once with logical shards.
Summary
- Shard for write load or data size; for read-heavy load, replicas and caches come first.
- Hash is the default; range creates hot spots; hash still has hot keys.
- Shard keys: root entity, small, high-cardinality, stable.
hash % Nmakes resharding painful; use logical shards.- Queries without the key need side tables via CDC; global uniqueness needs a lookup table.
Further reading: Primary-replica replication and read/write splitting.
Practice interview questions on this topic
- Multi-tenant data design: shared tables with tenant_id, a schema per tenant, or a database per tenant?
- How does partitioning differ from sharding, and when are replicas not enough so you must shard?
- How do you choose a shard key, and handle queries that don't follow it?
- How do you reshard when adding shards, and how do consistent hashing and virtual nodes help?
Comments
Community rules