Lessons › From one user to millions
One shard on fire
Dinner rush at a food delivery app: 25,000 req/s, and 40% are new orders. Orders are already split across 4 of the biggest databases, by city. One shard is overloaded while the other three sit half idle.
Play this levelFree with an account. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
Sharding only helps when the data splits evenly. Each shard takes the writes for its own part of the data, so the key you split by decides how much each one gets.
Split by city, and the biggest city's shard takes about half of all orders. More shards won't help: that city still lives on one of them. A bigger machine won't either: these are already the biggest.
Split by order date and it gets worse. Every new order is today's, so the newest shard takes every write while the old ones sit idle.
A good key has many values, each with a little of the traffic, like user ID. Press Run to see which shard is on fire, then click Primary DB and look at Split the data by.
What you have to achieve
25,000 requests a second at the busiest hour, 40% of them writes.
- No broken or illegal connections
- No component is overloaded
- Fewer than 0.1% of requests fail
- p99 response time under 300 ms
- Machines cost at most $6,000 / month
What you learn
Same 4 machines, same bill, and now none of them is overloaded. The number of shards says how much you could take. The key decides whether you actually get it.
Check yourself
Orders are split by city and the biggest city's shard is overloaded. What fixes it?
- Add more shards
- Move to a bigger machine
- Split by a key with many small values, like user ID
Show the answer
Split by a key with many small values, like user ID. That city lives on one shard however many you add, and the machines were already the biggest. Only a key that spreads the writes fixes it.
Why is splitting orders by date a bad key?
- Dates take more space
- Every new order is today's, so one shard takes every write
- Old orders can't be read
Show the answer
Every new order is today's, so one shard takes every write. A range key puts the newest rows together. All the writes land on the newest shard while the others sit idle.