Before you shard
Sharding is a one-way door with permanent costs. First try: a bigger machine, read replicas, caching, archiving old data, and splitting by function (orders vs users in separate databases). Shard when write throughput or data size exceeds what one well-tuned primary can handle.
Sharding strategies
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Range | Key ranges per shard (A–F, G–M…) | Efficient range scans | Hot spots on popular or sequential ranges (e.g. timestamps) |
| Hash | hash(key) picks the shard | Even distribution | Range queries hit every shard |
| Directory | Lookup table: key → shard | Flexible moves, tenant placement | The directory is critical infrastructure |
| Geo | By region/country | Data residency, locality | Uneven region sizes |
Choosing a shard key
A good shard key has:
- High cardinality: many distinct values.
- Even load: no single value gets a large share of traffic.
- Query locality: the most common queries include the key, so they hit one shard.
| System | Good key | Why | Bad key |
|---|---|---|---|
| Chat | conversation_id |
Messages read per conversation | sender_id (conversation scattered) |
| E-commerce orders | user_id |
"My orders" on one shard | created_at (all writes hit the newest shard) |
| Multi-tenant SaaS | tenant_id |
Isolation per customer | tenant_id if one tenant is huge: split it further |
| Ride-hailing | city_id + geo cell |
Matching is local | driver_id (a matching query spans shards) |
The celebrity problem. Even with a perfect hash, one key (a superstar account, a viral product) can overwhelm its shard. Mitigations: cache that key aggressively, split it into sub-keys (product_42#0…#9), or give it dedicated capacity.
Consistent hashing
With hash(key) % N, adding one server changes N, and almost every key moves. Consistent hashing places both servers and keys on a ring; each key belongs to the first server clockwise. Adding or removing a server moves only the keys in one arc.
Virtual nodes fix uneven arcs: each physical server is placed at 100–200 positions on the ring. Load evens out, and when a server leaves, its keys spread across many servers rather than flooding one neighbour. Bigger machines simply get more virtual nodes.
Imagine seats around a round table and guests choosing the next free seat clockwise. If one waiter leaves, only the guests in that waiter's section need a new waiter, not everyone in the room.