SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Indexing
  • Partitioning
  • Replication
  • Sharding
  • Query Optimization
  • Denormalization
  • Materialized Views
  • Connection Pooling
  • Replication Models
  • Replication Lag
  • Quorum (R + W > N)
  • Shard Keys, Hot Shards and Resharding
  • Cross-Shard Joins
  • Backups, RPO, RTO and Disaster Recovery
  • Point-in-Time Recovery
  • Data Archiving and TTL
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Scaling

Shard Keys, Hot Shards and Resharding

Pick the key that decides where data lives, avoid one overloaded shard, and grow without downtime.

⏱ 16 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The shard key is the field that decides which shard owns a row. It is the most important choice in a sharded system, and one of the hardest to change later.

  • A good key has many different values, spreads data and traffic evenly, and appears in your most common queries.
  • A bad key creates a hot shard: one machine does most of the work while the others sit idle.
  • Resharding means changing the number of shards. The way you map keys to shards decides whether that moves a little data or almost all of it.

02Concept: What is it?

The page on Sharding explained why we split data across many databases. This page goes deeper on three questions: which field should decide the split, what happens when one shard gets too busy, and how do we add shards later.

A shard key is chosen once, but it shapes everything: where each write goes, which queries are fast, and which are painful. A query that includes the shard key goes to one shard. A query that does not has to ask every shard.

Three tests for a shard key
1. Many values
🔢High cardinalitymillions of user ids
🏳️Low cardinality5 countries
2. Even spread
⚖️Equal data and traffic
🔥One celebrity, or only the newest rows
3. Matches queries
🎯Most queries carry the key
📡Most queries ask every shard
A key must pass all three. Passing two out of three still leaves you with a problem.
🧠A hot shard is a key problem, not a hardware problem
If one shard is overloaded, adding more machines does not help when the traffic is tied to one key or one range. The fix is almost always a different key, a suffix on the hot key, or caching, not more shards.

03Real-Life Example

🍵Sorting the Mail by Postcode
A post office sorts letters into 8 bins so 8 workers can deliver them in parallel. If the bins are made by first letter of the street name, a few letters are far busier than the rest. If they are made by day of posting, every new letter goes into today's bin and one worker is buried. If the bin is picked by a mix of the house number and street, the load spreads evenly, but "all letters for Main Street" are now in every bin. And when the post office adds a ninth bin, the rule decides how many letters must be moved by hand.
Post office
Shard key and resharding
A bin per worker
A shard
The rule that picks the bin
The shard key and the mapping
Bins made by posting day
Range sharding on a timestamp
One street gets most of the mail
A hot key
Adding a small tag to the busy street's mail
A salt or bucket suffix
Re-sorting letters when a new bin appears
Resharding
A rule that only moves a few letters
Consistent hashing
Two ways to hit a hot shard
Range on created_at
S1old
S2old
S3old
S4today
Share of new writes on S4
Hash with a celebrity
S1
S2star
S3
S4
Share of writes on S2illustrative
Range on a growing value, and one very popular key.

04Why Do We Need It?

⚖️Even load
A good key gives every shard a fair share of data and traffic, so no machine is the bottleneck.
🎯Fast common queries
If the main query carries the key, it touches one shard and stays fast as you grow.
🔥Avoid hot shards
One overloaded shard slows or breaks the whole feature, even if the cluster has spare capacity.
📈Room to grow
A key that works at 4 shards should still work at 40.
🚚Cheap resharding
A good mapping moves only a small share of the data when a shard is added.
🧰Simpler operations
Even shards are easier to back up, size and monitor.
You usually cannot change the shard key without moving all the data. Spend the time to choose it well, on real traffic numbers.

05Where Do We Use It?

👥SaaS by tenant
tenant_id keeps one customer together. A very large tenant can still become a hot shard.
💬Chat
conversation_id keeps one chat on one shard, so reading the history is a single-shard query.
🛒Orders
customer_id keeps a customer's orders together. order_id spreads evenly but scatters one customer's history.
📈Events and metrics
Device id plus a time bucket avoids piling all new points on one shard.
🎮Gaming
player_id for profiles, and a hash of the match for leaderboards.
🧰Managed databases
DynamoDB, MongoDB, Cassandra, Vitess and CockroachDB all ask you to think about the key (or pick one for you).

06Types / Parts / How It Works

Choosing a key

KeySpreadWatch out for
user_id or customer_id (hashed)Even for ordinary usersOne huge customer or a celebrity can still be hot
Timestamp or auto-increment id (range)Bad: all new rows go to the newest rangeA classic hot shard on writes
Country or regionPoor: only a handful of valuesCannot use more shards than values, and sizes differ a lot
A random id (UUID, hashed)ExcellentRelated rows are scattered, and every list query must ask all shards
Composite key (tenant_id + hash of id)Good, keeps a tenant near each otherMore design and a more complex router
Key plus a salt suffix (user#0 to user#7)Spreads one hot key over several shardsReading that key means asking every bucket and merging

Choosing a mapping from key to shard

MappingHow it worksAdding a shard
hash(key) mod NThe remainder after dividing by the shard countChanges the remainder for almost every key, so most data moves
RangeEach shard owns a block of key valuesSplit one range in two: only that range moves
Consistent hashingKeys and shards share a ring. A key goes to the next shard clockwiseAbout 1 / (N + 1) of the keys move, and only to the new shard
Many small fixed partitionsCreate thousands of partitions up front and assign them to machinesMove whole partitions to the new machine, and the key mapping never changes
Directory (lookup table)A table says where each key (or tenant) livesMove one tenant at a time and update the table
Resharding with a mod rule vs a ring
hash mod N
🧮N = 4 → 5most keys change remainder
Keys that moveabout 4 out of 5 here
Consistent hashing
⭕N = 4 → 5only the new shard's slice moves
Keys that moveabout 1 out of 5
Heavy migration Light migration
Illustrative picture. The visualizer below counts the real numbers.
VisualizerWhich key spreads the load, and how many keys move when you add a shard?Try each shard key and watch the busiest shard. Add a salt to the celebrity. Then switch to resharding and compare hash mod N with consistent hashing.
What do you want to try?
Shard key
Share of the 1000 writes each shard takes (dashed line = fair share, 25%)
Shard 1
42%
Shard 2
20%
Shard 3
19%
Shard 4
19%
Busiest shard
1.7x
of its fair share
Hot shard?
Yes
hot = 1.5x or more
Shards used
4 of 4
getting any traffic
Hashing spreads ordinary users evenly, but one very popular user (a quarter of all requests) always hashes to the same shard. The busiest shard takes 1.7 times its fair share. A good hash cannot fix a single hot key. Try the salt.

A teaching model with fixed data and no random numbers. Part 1 replays 1000 writes: a quarter come from one popular user, the rest from 199 ordinary users, with 60% of users in one country. Part 2 hashes 2000 keys with FNV-1a and gives each shard 100 points on the ring. Real systems differ in the details, but the shape of the result is the same.

07How to Use It / Steps / Implementation

Choosing a shard key, step by step

  1. 1
    List your main queries
    Write down the five or ten most common reads and writes. The shard key should appear in most of them, so they touch one shard.
  2. 2
    Look at real traffic, not just row counts
    A key can split rows evenly and still be unfair if a few keys get most of the requests. Count requests per key.
  3. 3
    Check cardinality
    You need far more distinct values than shards, now and in five years. A field with five values cannot feed fifty shards.
  4. 4
    Avoid keys that only grow
    Timestamps and auto-increment ids on range sharding send every new write to the last shard. Hash them, or add a bucket in front.
  5. 5
    Plan for the biggest customer
    If one tenant or user can be a hundred times bigger than the average, decide now how to split them (a composite key, a salt, or their own shard).
  6. 6
    Use many small partitions
    Create more logical partitions than machines (for example a few thousand) and assign them to machines. Adding a machine then moves whole partitions and the key mapping stays the same.
  7. 7
    Reshard online
    Copy the data to its new home while the old one keeps serving, stream the new changes across (a change log or dual writes), check that both match, then switch the routing and delete the old copy. Throttle the copy so it does not hurt live traffic.
💡Salting a hot key
Write user_7#0 to user_7#7 at random (or by a counter) so one user's writes spread over up to 8 shards. The cost is on the read side: to read user 7 you ask all 8 buckets and merge. Salt only the few keys you know are hot.
⚠️Do not reshard during an incident
Moving data adds load. Measure first, fix the cause (often a cache or a salt), and schedule the migration for a calm time with throttling and a way to roll back.

08Key Terms to Know

TermMeaning in easy words
Shard keyThe field (or fields) that decide which shard stores a row
CardinalityHow many different values a field has
Hot shardA shard that gets far more load than the others
Hot keyOne key that gets a huge share of the requests
SkewUneven spread of data or traffic
Range shardingEach shard owns a block of key values, so range queries are easy but new rows can pile up
Hash shardingA hash of the key picks the shard, which spreads keys evenly
Salt (bucket suffix)A small extra part added to a key to spread one hot key over several shards
ReshardingChanging the number of shards and moving data to match
Virtual node or partitionA small logical slice assigned to a machine, so data moves in small pieces
Scatter-gatherAsking every shard and merging the answers

09Pros, Cons and Trade-offs

✅ Pros
  • A good key makes the common queries single-shard and fast
  • Even load, so the cluster uses all its machines
  • Small partitions make adding machines easy
  • Salting can rescue a single hot key
  • Directory mapping can move one big tenant at a time
⚠️ Cons
  • The key is hard to change once data exists
  • Hash keys give up cheap range queries
  • Range keys can create a hot last shard
  • Salted keys make reads more expensive
  • Online resharding is delicate work

Trade-offs

ChoiceWe gainWe lose
Hash the keyEven spread of keysRange scans and ordered reads must ask every shard
Range the keyFast range scans and easy range splitsA hot shard on growing keys
Co-locate related tables on one keyLocal joins and local transactionsA big entity can make one shard too big
Salt a hot keyWrites spread over several shardsReads must merge several buckets
Many small partitionsCheap rebalancingMore metadata to track, and more files or connections
Directory lookupTotal freedom to place tenantsA new component that must be fast and always up

10Common Problems and Mistakes

Common mistakes

  1. Sharding by a timestamp with ranges. Every new row lands on the newest shard.
  2. Sharding by country. Only a few values, and one country is often most of the traffic.
  3. Judging the key by row counts only. A celebrity or one huge tenant makes a shard hot even when rows are even.
  4. Using hash mod N and then growing. Changing N moves almost every key.
  5. Ignoring the queries. A perfectly even key that no query uses turns every request into scatter-gather.
  6. Salting everything. Only the hot keys need it. Salting all keys makes every read expensive.
  7. Resharding with no throttle. The migration steals capacity from live users.

Things to watch

📊Per-shard metrics
Track requests, CPU, disk and latency for each shard. A single shard that stands out is the warning sign.
🔝Top keys
Sample requests to find the few keys that get the most traffic. Cache or salt them.
⏱️Migration lag
While data moves, the copy falls behind the source. Watch the lag and switch only when it is near zero.
🧪Verify before the switch
Compare counts or checksums between old and new homes before you move traffic.

11Real-World Examples

🛒Marketplaces
Orders by customer or seller id, with a special plan for the few giant sellers.
💬Messaging
Messages by conversation, so one chat is read from one shard.
📈Time series
Series id plus a time bucket, so new data does not pile onto one shard.
☁️Managed key-value stores
Services in this family warn you about hot partitions and suggest adding a suffix to popular keys.
🔀Automatic splitting
Several distributed databases split and move ranges for you, but still depend on a sensible key.
🏢Large tenants
A directory table moves a single very large customer to its own shard.
📝Note
Product behaviour and limits change between versions. Check your database's documentation for how it chooses keys, splits partitions and handles hot ones.
Mini case: a chat app that grew
😰Hot shardsharded by day
→↓measure
🔑New keyconversation_id, hashed
→↓copy + catch up
🔁Switch routing
→↓verify
✅Even load
Illustrative flow of a safe key change.

12Related Topics to Read Next

Sharding→

The overview of why and how data is split across shards.

Partitioning→

The general idea of cutting a table into pieces.

Consistent Hashing→

The mapping that moves only a small share of keys when a shard is added.

Hot Keys→

The same skew problem, seen from the cache side.

Indexing→

Secondary indexes on a sharded table need extra thought.

Replication Models→

Each shard is usually replicated for safety.

Cross-Shard Joins→

What happens to queries that need data from several shards.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Shard key: the field that decides which shard owns a row. Hard to change later.
  • ✔Good key: many values, even data and traffic, used by the common queries.
  • ✔Bad keys: timestamps with ranges, low-cardinality fields, one dominant customer.
  • ✔Hot shard: find it with per-shard metrics and top-key sampling.
  • ✔Fixes: a better key, a salt on the hot key, a cache, or a dedicated shard.
  • ✔hash mod N: changing N moves most keys. Consistent hashing: about 1/(N+1) move.
  • ✔Resharding: copy, catch up, verify, switch, clean up, all throttled and online.
  • ✔One line: “Choose the key from your queries and your busiest users, not from the table.”
← Previous
Quorum (R + W > N)
Next →
Cross-Shard Joins