Sharding
Split data across machines when one node can no longer hold or serve it.
Sharding in 30 seconds
- Sharding splits data into partitions across nodes, so dataset size and write load spread out.
- Why not replication? Replication copies everything everywhere — it scales reads, not writes or total size.
- The shard key is everything: pick well for even load, pick badly for a hot shard.
- Strategies: hash (even spread, bad range scans), range (good scans, hot-spots on sequential keys), directory (full control, extra SPOF).
- Resharding: modulo remaps everything; consistent hashing with virtual nodes moves only a slice.
- Hot keys beat any scheme — mitigate with key splitting, a cache, or a dedicated shard.
When the filing cabinet is full
A growing office starts with one filing cabinet. For a while you just buy a bigger cabinet. But eventually no single cabinet is tall enough, and even if it were, only so many people can crowd around one drawer at a time. The fix everyone reaches for is obvious: split the files across several cabinets — A-through-H in the first, I-through-P in the second, and so on. Now the files fit, and three people can work at three cabinets at once.
That split is sharding. Each cabinet holds a different slice of the files (not a copy of all of them), so together they store far more than one ever could, and the work spreads out. The new headache is also obvious from the analogy: you need a rule for which cabinet holds which file, and if you get that rule wrong — say everyone's files start with 'S' this year — one cabinet is mobbed while the rest sit empty. That rule, and that failure, are the whole story of sharding.
The problem it solves
Replication copies the whole dataset to every node, so it scales reads but not write throughput or total size — every machine still holds everything. Sharding splits the data into partitions, each living on a different node, so the dataset and the write load spread out. The cost is that queries spanning shards get harder, and choosing the split well is now your problem.
The gap replication leaves — why copying isn't enough
It's worth being precise about why you'd shard at all, because it's easy to confuse with replication. Replication makes copies: every node holds the entire dataset. That's wonderful for surviving failures and for serving lots of reads — but it does nothing for two problems. If your data is 50 terabytes and your biggest machine holds 10, copying doesn't help; every copy still needs 50. And if you're taking a million writes a second, every write still has to be applied by the single leader; more copies just means more machines doing that same full write load.
Sharding is the only move that attacks those two walls. Split the 50 TB into five 10 TB shards and it fits. Split the writes across five shards and each one handles a fifth. That's the reason sharding exists and replication can't substitute for it.
The core idea, plainly
Pick a shard key from each record, run it through a rule, and that rule decides which node owns the record. Get the key right and load spreads evenly and single-record lookups stay fast. Get it wrong and you create a hot shard that carries most of the traffic while the others idle.
SHARDS = ["db-0", "db-1", "db-2"]
def route(record):
key = record["user_id"] # the chosen shard key
idx = hash(key) % len(SHARDS) # hash strategy: even spread
return SHARDS[idx] # the node that owns this record
# Reads and writes for one key always land on the same shard,
# so single-record lookups stay a one-node hop.
route({"user_id": "u-42", "name": "Ada"}) # -> e.g. "db-1"Partitioning strategies
The 'rule' that maps a key to a shard comes in three common shapes, each with a different payoff and a different trap.
| Strategy | How it splits | Pros | Cons | Use when | Avoid when |
|---|---|---|---|---|---|
| Hash | hash(key) maps to a shard. | Even spread; no hotspots from skewed values. | Range scans must hit every shard. | Point lookups by key dominate. | You need efficient range queries. |
| Range | Contiguous key ranges per shard. | Range scans stay on one shard. | Sequential keys (timestamps, IDs) create hot shards. | Time-series or ordered scans. | Writes cluster at the latest range. |
| Directory | A lookup table maps key -> shard. | Full control; easy rebalancing. | The directory is a new dependency and SPOF. | Uneven tenants needing manual placement. | You want zero extra moving parts. |
The hash-vs-range choice is really a choice about what question you ask most. Hashing scrambles keys so neighbors land on different shards — perfect for even spread, terrible for 'give me everything between X and Y' since the range is scattered everywhere. Range keeps neighbors together so a range scan stays on one shard — perfect for time-series, but dangerous when your keys march forward in time, because all the newest writes pile onto the last shard.
# Each shard owns a contiguous key range.
RANGES = [
("a", "h", "db-0"), # keys a..h
("h", "p", "db-1"), # keys h..p
("p", "z", "db-2"), # keys p..z
]
def route(key):
for lo, hi, shard in RANGES:
if lo <= key < hi:
return shard
# A range scan (keys m..o) stays on db-1 only -- no fan-out.
# But sequential keys (timestamps) all hit the last shard = hot spot.The gap sharding opens — cross-shard queries
Splitting data buys scale but takes something away: queries that need data from more than one shard get expensive. A single-key lookup is still a fast one-node hop, but 'count all orders across all users' now has to ask every shard and combine the answers — a pattern called scatter-gather. The more shards you have, the more parallelism you get, but also the more fan-out every cross-shard query costs, and the query is only as fast as the slowest shard it waited on.
# "How many orders are 'paid'?" -- no single shard knows.
def count_paid():
# SCATTER: ask every shard in parallel
partials = parallel(shard.count(status="paid") for shard in SHARDS)
# GATHER: merge their answers
return sum(partials)
# Cost grows with shard count, and you wait for the SLOWEST shard.
# This is why you design the shard key so common queries stay
# on ONE shard (e.g. shard by user_id, then queries per-user are local).Resharding without downtime
Naive hashing (hash(key) % N) remaps almost every key when N changes, which means moving nearly all your data to add one node. Consistent hashing places nodes and keys on a ring so adding a node only moves the keys between it and its neighbor. Virtual nodes (many ring positions per physical node) smooth out the distribution and make rebalancing gradual.
# With 3 shards:
shard = hash(key) % 3
# Add a 4th shard -> now:
shard = hash(key) % 4
# Almost every key maps somewhere new => massive data movement.
# Consistent hashing instead moves only ~1/N of keys when a node joins.The hot key — the problem no scheme solves
There's one failure that defeats every strategy above, because it isn't about spreading keys evenly — it's about one single key getting hammered. A celebrity's account, a viral tweet, one wildly popular product: all their traffic targets one key, which lives on exactly one shard, no matter how cleverly you partitioned. That shard melts while the rest nap. You can't hash your way out, because the hash of one key is still one shard.
# Problem: like counts for ONE viral post all hit one shard.
# key = "post:viral:likes" -> single hot shard
# Fix: split the key into N sub-counters spread across shards,
# and sum them on read.
def incr_like(post_id):
bucket = random.randint(0, 15) # 16 sub-keys
shard_for(f"post:{post_id}:likes:{bucket}").incr()
def total_likes(post_id):
return sum(shard_for(f"post:{post_id}:likes:{b}").get()
for b in range(16)) # gather the 16 buckets
# Writes now spread across 16 shards instead of hammering one.Sharding is the only move that truly scales writes and storage past a single machine — which makes it the most powerful tool in the data tier and, not coincidentally, the most dangerous to reach for early.
Why it matters
- When write throughput or dataset size outgrows one node, sharding is the one technique that actually helps.
- The shard key you choose shapes performance for the life of the system — it's a hard decision to reverse.
- It's the step that forces real distributed-systems thinking: fan-out, resharding, and hot keys all appear here.
If ignored
- Sharding too early buys cross-shard joins, distributed transactions, and resharding pain you didn't need.
- A monotonically increasing shard key funnels all new writes to one node — a permanent hot shard.
- Assuming cross-shard queries are cheap leads to scatter-gather reads that quietly dominate latency.
Where it fits
- Sits at the data tier as the last and most powerful step of the scaling playbook.
- Lives in the routing layer that maps each record to the node that owns it.
- Complements replication — sharding splits for write scale, replication copies for read scale and availability.
Related topics
- Consistent hashing: the resharding-friendly way to assign keys so scaling moves little data
- Replication: the complement — each shard is usually replicated for availability
- Database scaling: sharding is the final, most complex step of the ordered playbook
- Distributed transactions: what a write spanning multiple shards now requires
Interview lens
Questions it unlocks
- Your single database can't hold the dataset anymore — what now?
- Pick a shard key for a chat app's messages. Defend it.
- How do you add capacity to a sharded store without a big migration?
60-second answer
First I confirm sharding is actually needed — that we're past what one node plus read replicas can handle on size or write throughput. Then the whole game is the shard key: I want even distribution and the ability to keep common queries on one shard. For messages I'd shard by conversation ID so a chat's history stays together. I'd use consistent hashing with virtual nodes so adding capacity moves only a slice of data, and I'd call out hot keys as the risk that beats any key choice.
Common traps
- Sharding prematurely when a bigger box or read replicas would do.
- Choosing a monotonically increasing shard key and creating a permanent hot shard.
- Forgetting that cross-shard joins and transactions are expensive or unavailable.