AI Hints
System Design · Lesson 44 of 120

Choosing a Shard Key

Even and useful.

⏱ 2 min read▶ Video at 51:51🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

The shard key is the most important choice in sharding. A good key spreads data evenly, and keeps related data together. A bad key can ruin everything.

Choosing a Shard Key
From the video: Choosing a Shard Key
  • The key decision
  • Even spread
  • Related data together

Good and bad keys

Let's judge some keys for Shoply's orders. Order date is bad, because all of today's orders hit one shard. Country is bad, because one country can be far bigger than the rest. Order ID spreads evenly, but one customer's orders end up everywhere. Customer ID spreads well, and keeps each customer's orders together. That's usually the best choice.

Shard keyVerdict
Order datebad: today's shard is hot
Countrybad: very uneven
Order IDeven, but scattered
Customer IDeven and together

Questions to ask

To pick a key, ask these questions. Does it have many different values? Does it spread the load, today and in future? Do my most common queries include it, so they hit just one shard? And will it stay the same for each row?

keyvalue
Many valuesnot just a few
Even loadnow and later
Common querieshit one shard
Never changesno moving rows

Summary

A good shard key has many values, spreads load evenly, and matches your most common queries. For a shop, customer ID is often best. Next, a clever way to add shards without moving everything.

Key takeaways
  • Spread evenly
  • Match your queries
  • Customer ID for shops
Next up: Consistent Hashing — moving less data