Lessons › From one user to millions
Pick the shard key
The app keeps growing: 40,000 req/s, and 25% are new orders. The rest open My orders, which must show an order the moment it's placed, so it reads from the primary. One database can't take it. Split it, and choose what to split by.
Play this levelFree with an account. It runs in your browser: build the design, press Run, and watch what breaks.
The lesson
Every query has to find its shard. If you split by what you look rows up by, a query goes to one shard. If not, it has to ask every shard and wait for the slowest.
Split by order ID and writes spread perfectly. But My orders asks for one user's orders, and those now sit on every shard. Each page view becomes a query on every shard, so more shards add no read capacity at all.
City and date bunch the writes onto one shard, as you saw. User ID spreads the writes and keeps each user's orders together, so My orders reads one shard.
No key is perfect. Split by user ID, and a question like "every order in Mumbai today" has to ask every shard. Choose the key for the questions you ask most.
What you have to achieve
40,000 requests a second at the busiest hour, 25% of them writes.
- No broken or illegal connections
- No component is overloaded
- Fewer than 0.1% of requests fail
- p99 response time under 250 ms
- Machines cost at most $6,000 / month
What you learn
You chose the key from how the data is read, not only how it's written. That choice is hard to undo: changing it later means moving every row to a new shard while the app keeps running.
Check yourself
Orders are split by order ID. Why does My orders get slower and more expensive?
- Order IDs are too long
- One user's orders sit on every shard, so each page asks all of them
- Writes go to one shard
Show the answer
One user's orders sit on every shard, so each page asks all of them. Writes spread perfectly, but a read by user has to visit every shard and wait for the slowest. More shards add no read capacity.
How should you choose a shard key?
- By the column with the most values
- By the questions you ask most, so each one reads one shard
- By whatever the primary key is
Show the answer
By the questions you ask most, so each one reads one shard. A key needs to spread writes, and it should match how the busiest queries look rows up, so they each touch one shard.
You split orders by user ID. A support screen lists every order placed in one city today. What happens?
- It reads one shard
- It asks every shard and waits for the slowest
- It can't run on sharded data
Show the answer
It asks every shard and waits for the slowest. That city's orders belong to users on every shard. A rare screen like this can afford to ask them all. The page everyone opens can't.