Try
↑ ↓ move↵ openesc close

Interview prep / Partitioning

Junior · Partitioning · System design interview question

You are sharding a users table of 200 million rows. Someone proposes the country as the partition key, because queries are often per country. Another proposes user id. Which would you choose and why?

Sketch your own answer first, then compare it with the one below.

A strong answer

User id, hashed. A partition key should split data and traffic into many pieces of about equal size, and country does neither. A handful of countries hold most users, so a few partitions would be huge and busy while the rest sit nearly empty. The number of countries, around two hundred, also caps how far the table can ever be spread, however many machines you buy.

Hashing the user id gives hundreds of thousands of distinct values, an even spread, and single-user reads and writes that touch one partition. That covers the most common operations.

The proposal does have a point. "All users in Germany" is now a query across every partition. Whether that matters depends on how often it runs and how fresh it must be. If it is rare, run it as a scatter and gather, or from a replica built for reporting. If it is common, keep a secondary index on country, or maintain a separate table keyed by country that is updated from the main one.

The point is to pick the key for the operations that are both frequent and latency sensitive, and to handle the rest with indexes or copies instead of bending the primary layout around them.

Sources

Learn it by running it

The partitioning lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms