System Design
Sharding (Hash-Based Key Routing)
O(1) time to route any key to its shard — it's just a hash and a division. The tradeoff: if you later change the number of shards, most keys move to a different shard. Consistent hashing is designed to avoid that problem.
The idea, in plain English
Picture a huge pile of mail. Instead of one overflowing mailbox, you sort it into 4 mailboxes. Sharding does the same thing to your database. Instead of one giant table holding every user, you split it into several smaller tables called shards. Each user's data lives in exactly one shard. To pick the right shard for a piece of data, you turn its key (like a user ID) into a number. You use that number to pick a shard. The same key always lands in the same shard.
How it works
- 1Pick a number of shards, N — for example, 4 database instances.
- 2For any key, like a user ID, compute a hash number from it. The same key always produces the same number.
- 3Take the hash mod N. That remainder — a number from 0 to N-1 — tells you exactly which shard owns that key.
When you'd use it
Use sharding when one database server can no longer hold all your data or handle all your traffic. You split the data across several servers, so each one deals with only a fraction of it.
Common beginner mistakes
- Picking a shard count and then changing it casually. As this example shows, going from 4 shards to 5 moves most keys to a different shard. That means a painful data migration.
- Sharding by a key that isn't evenly spread out — for example, by signup date, when most users signed up in one week. This creates a 'hot shard' that gets overloaded while the others sit idle.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Routing 6 users across 4 shards:
user-1 -> shard 1
user-2 -> shard 2
user-3 -> shard 3
user-4 -> shard 0
user-5 -> shard 1
user-6 -> shard 2
Counts: shard 0=1, shard 1=2, shard 2=2, shard 3=1
Resharding 4 -> 5 moves 3 of 6 keysNot sure this is the right topic? See the learning paths → or where this leads →