How do you choose a good shard key?
A good shard key has high cardinality, spreads data and traffic evenly, and matches the most common query so requests hit one shard. Avoid keys that grow monotonically or are skewed, like timestamps or country.
Explain it simply
The shard key decides which shard stores a row. Choosing badly creates a hot shard that melts while others idle.
What to look for:
- High cardinality: many distinct values, so data can be split into many pieces. A boolean or a status column is useless as a key.
- Even distribution: no value or range gets much more traffic than others. Sharding by country would put India's load on one shard.
- Query alignment: the main queries include the key, so each query goes to one shard rather than all of them (a scatter-gather).
- Stable: the value rarely changes, since changing it means moving the row.
Bad examples: creation timestamp (all new writes hit the latest shard), or a celebrity user id when one user dominates traffic.
Techniques: hash the key to spread evenly; use a compound key; pick user_id for user data and order_id plus a salt for hot items.
Example
Food-delivery orders, 4 shards.
Shard by city: Bengaluru shard gets 40% of traffic (hot)
Shard by created_at: today's shard takes every write
Shard by hash(customer_id) % 4:
about 25% each, and "my orders" queries hit one shardWhat to say in the interview
"I pick a high-cardinality key that distributes load evenly and appears in the main queries, usually a hash of the user or entity id. I avoid timestamps and low-cardinality or skewed fields, and I plan for resharding because the first choice is hard to change."
Common mistakes
- Choosing a key that looks natural but sends most traffic to one shard.