Module 3 · Database designLesson 26 of 888 minIntermediate
Sharding
When one database can't hold all the data or take all the writes, split the data across several databases by a key.
Compare "hash mod N" and "Hash ring" while changing the shard count, and watch how many users move. Then turn on the hot key and see one shard take most of the traffic.
Replication copies all the data to every machine. That helps reads, but every machine still holds everything and every write still goes to one primary. When the data or the write load outgrows one machine, you shard: split the data so each machine holds only part of it.
The shard key
Every row gets a shard key, often user_id. A rule maps each key to a shard:
- Range: users 1 to 1M on shard 1, 1M to 2M on shard 2. Simple, good for range queries, but new users all land on the last shard.
- Hash:
hash(user_id) mod N. Spreads keys evenly, but changing N reshuffles almost everything. - Consistent hashing: shards and keys are placed on a ring; each key belongs to the next shard clockwise. Adding a shard only takes keys from its neighbours. Used by Cassandra and DynamoDB.
- Directory: a lookup table says where each key lives. Most flexible, but the directory is one more thing to run.
Choosing a good key
A good shard key:
- spreads data and traffic evenly,
- keeps data that's read together on the same shard (a user's orders with the user),
- appears in most queries, so the router knows where to go.
What gets harder
- Cross-shard queries: "top 10 products across all users" must ask every shard and combine.
- Cross-shard transactions: moving money between users on different shards needs distributed transactions or sagas (module 5).
- Hot keys: one celebrity user can overload their shard, no matter how even the rest is.
- Resharding: moving data between shards while the system runs is delicate work.
Because of these costs, shard last: after indexes, caching, read replicas and a bigger machine. Many managed databases (Vitess, CockroachDB, DynamoDB, Spanner) do the sharding for you.