Shard Key Selection
You'll learn how to choose the attribute that determines which shard stores each piece of data—the most critical decision in any sharding strategy.
What Is a Shard Key?
The shard key (or partition key) is the database column or attribute you use to decide which shard will store each row. When you insert data, the system applies a function to the shard key value—often hashing or range-based routing—to determine the destination shard.
Think of it like sorting mail: the shard key is like a ZIP code. The postal service uses it to route each letter to the right regional office. Choose the wrong "ZIP code," and letters pile up unevenly or get sent to the wrong place.
Why Shard Key Selection Is Critical
A poor shard key creates unbalanced shards (some overloaded, others idle), hotspots (one shard handling most traffic), and inefficient queries (needing to check every shard). A good shard key distributes data and load evenly while keeping related data together when possible.
Key Characteristics of a Good Shard Key
- High cardinality: Many distinct values to spread data widely (e.g.,
user_idwith millions of users, notcountrywith 200 values) - Even distribution: Values appear with similar frequency
- Query-aligned: Matches your most common query patterns to minimize cross-shard lookups
Example Comparison
- Bad shard key:
created_date— recent dates create hotspots as all new writes go to one shard - Good shard key:
user_id— distributes users evenly and queries for one user hit one shard
Key Takeaway:
The shard key determines data distribution and query efficiency; choose an attribute with high cardinality, even distribution, and alignment with your query patterns.