Course contentsShow
← System Design
Lesson 232 of 1,9197. Database Scaling: ShardingFree lesson

Shard Key Selection

Choosing the attribute used to determine which shard stores each row; the most critical sharding decision.

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

  1. High cardinality: Many distinct values to spread data widely (e.g., user_id with millions of users, not country with 200 values)
  2. Even distribution: Values appear with similar frequency
  3. 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.