FullStack AI Hub
Studio
System Design · 03. Data & Storage
10 min
9 steps
Intermediate

Sharding

Split one overloaded database across independent partitions without creating hot spots.

System Design03. Data & StorageLesson 7 of 11
10 minIntermediate9 steps

Sharding

Split one overloaded database across independent partitions without creating hot spots.

SHARDS
1
WRITES / SHARD
40,000/s
BUSIEST SHARD
98%
DATA / SHARD
20 TB
App Fleet42%Primary DB98%20 TB · 40k w/sSingle leader saturates IOPS
write query
hot-key burst
scatter read
throttled / reshuffled
In This LessonStep 1 of 9
What You Will Master
  • ✓Recognize when vertical scaling hits a ceiling and horizontal sharding is needed
  • ✓Compare range-based sharding against hash-based sharding to avoid hot shards
  • ✓Mitigate single hot keys ("celebrity partitions") with key salting
  • ✓Handle cross-shard scatter-gather queries and resharding costs

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Range ShardingOrdered range scans (e.g. time windows or contiguous ID ranges on 1 shard)Monotonic keys (timestamps, auto-increment IDs) create a rolling hot shard
Hash Sharding (% N)Uniform write distribution across all shards for high-throughput OLTPDestroys range scan locality and reshuffles ~(N-1)/N keys on scale-out
Selective Key SaltingTaming viral single-key hot spots ("celebrity partitions") across K shardsReads for salted keys must scatter-gather and merge all K buckets
Secondary Index / Consistent RingAvoiding cross-shard scatter-gather lookups and minimizing resharding copiesAdds async index maintenance or ring-membership gossip complexity

Step-by-Step Architectural Breakdown (9 Steps)

Full architectural walkthrough transcript and state transitions for Sharding.

STEP 01 · PROBLEMJump to step →

One database hits the wall

Your primary PostgreSQL instance has grown to **20 TB** and absorbs **40,000 writes/s**. Read replicas helped offload reads, yet every single write still lands on the lone leader.

Disk IOPS are maxed out at **98%**, buffer pool hit rate is collapsing, and upgrading to an even larger machine is no longer possible.

watch:Read replicas scale reads, not writes. Once write throughput or dataset size outgrows one box, you must partition the data.

Write BottleneckVertical CeilingHorizontal Partitioning
STEP 02 · SOLUTIONJump to step →

Split by key range

We introduce a lightweight **Shard Router** and slice the user table into four independent databases by **user_id range**: Shard A holds IDs `1–25M`, Shard B holds `25M–50M`, Shard C holds `50M–75M`, and Shard D holds `75M–100M`.

Each shard owns 5 TB of data and runs its own independent write leader, quadrupling raw storage and CPU headroom.

idea:Range sharding keeps adjacent keys physically together, making range scans like "IDs 10M to 11M" fast on a single shard.

Range-Based ShardingShard KeyShard Router
STEP 03 · PROBLEMJump to step →

The newest range becomes a hot spot

In production, activity is heavily skewed toward recent sign-ups and new records. Every new user gets an auto-incrementing ID above 75M—meaning **Shard D** catches almost all fresh writes.

Shard D shoots to **89% load** absorbing **73% of writes**, while Shard A (oldest accounts) barely ticks at 11%.

watch:Sequential shard keys (timestamps, auto-increment IDs) almost always create a rolling hot spot on the newest partition.

Hot ShardMonotonic Key SkewSequential Write Hot Spot
STEP 04 · SOLUTIONJump to step →

Hash the shard key instead

Instead of raw numeric ranges, the router runs `hash(user_id) % 4`. A uniform hash scrambles consecutive IDs—so user `99,000,001` lands on Shard B while `99,000,002` lands on Shard D.

Every new sign-up burst spreads evenly across all four databases. Each shard settles cleanly near **25%** of total writes and **36%** load.

idea:Hash-based sharding trades away fast range queries in exchange for uniform write distribution across every partition.

Hash-Based ShardingModulo PartitioningUniform Distribution
STEP 05 · PROBLEMJump to step →

The celebrity hot-key problem

Hashing balances *distinct* users, yet it cannot split a **single user_id**. When a celebrity with 50M followers drops a viral post, millions of likes and comments hammer the exact same key.

Because `hash(celebrity_id) % 4` always evaluates to **Shard 1**, that single database rockets to **94% load** while its three siblings stay calm.

watch:A hash function spreads many keys evenly, but all traffic for one identical key still routes to one exact shard.

Celebrity PartitionHot KeySkewed Access Pattern
STEP 06 · TECHNIQUEJump to step →

Salt hot keys across shards

For flagged celebrity accounts, we append a small random suffix—called a **key salt**—such as `celeb#0` through `celeb#3` before hashing.

Now writes for that single celebrity fan out across all four shards. Reads simply fetch and sum all four salted buckets, trading a slightly heavier read for smooth write absorption.

good:Only salt keys that exceed a traffic threshold—avoid paying the multi-shard read penalty for the 99.9% of regular users.

Key SaltingWrite ShardingSub-Partitioning
STEP 07 · TRADE-OFFJump to step →

The tax of cross-shard queries

Queries that include `user_id` hit exactly one shard. But what about `SELECT * FROM users WHERE email = ...` or "Top 20 orders across the whole company"?

Without the shard key, the router must **scatter-gather**: broadcast the query to every shard, wait for the slowest shard to answer, and merge-sort the partial results in memory.

watch:Pick your shard key around your 95% query path, and maintain a separate secondary index or search cluster for cross-shard lookups.

Scatter-Gather QuerySecondary IndexCross-Shard Join
STEP 08 · PROBLEMJump to step →

Adding a 5th shard reshuffles almost everything

A year later, traffic grows again and you add **Shard 4**. Suddenly the routing rule changes from `hash(id) % 4` to `hash(id) % 5`.

Because modulo depends on **N**, roughly **80% of existing keys** now hash to a different shard! You must migrate ~16 TB of live rows across the network just to add one machine.

watch:Modulo hashing (% N) couples every key’s home to the cluster size—making scaling out painful. Consistent Hashing solves this next.

Resharding StormModulo InstabilityData Migration
STEP 09 · RECAPJump to step →

Sharding recap

Sharding unlocks near-linear write scaling and storage capacity by dividing one dataset across independent leaders. **Hash-based sharding** prevents sequential hot spots, and **key salting** tames single celebrity keys.

The two enduring costs are **cross-shard queries** and **resharding**. In the next lesson, **Consistent Hashing**, we replace `% N` so adding a node moves only a tiny slice of keys.

good:Delay sharding until vertical scaling, indexing, caching, and read replicas are exhausted—it adds real operational complexity.

Sharding StrategyPartitioning Trade-Offs

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.