Bugpit

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 level

Free 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.

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?

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?

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?

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.

Try it yourself

More in From one user to millions

← One shard on fire Stop managing shards →