Sharding & Hotkeys
Horizontal partitioning from first principles: range vs hash sharding, why cross-shard joins hurt, and mitigating celebrity hotkeys with key salting.
Replication scales reads and survives failures, but every write still lands on the same leader. Eventually a growing system hits vertical hardware ceilings: either the write QPS saturates one machine’s CPU/disk, or the working set no longer fits in memory and disk indexes bloat.
Sharding (horizontal partitioning) splits one logical table into smaller disjoint subsets stored on independent database nodes, each owning a slice of the keyspace.
1 shard
single-key lookup · O(1) routing
K shards
scatter-gather when shard key is missing
90%+
traffic a single celebrity key can draw
Two ways to split the keyspace
1. Range sharding
Assign contiguous key ranges to each shard (e.g. A–F on Shard 0, G–M on
Shard 1, or timestamps by month).
- Win: range queries (
WHERE created_at BETWEEN t1 AND t2) hit only 1 or 2 shards sequentially and stay B-Tree-friendly. - Trap: time-based keys send 100% of new writes to the newest shard while older shards sit completely idle.
2. Hash sharding
Compute hash(shard_key) % N (or use consistent hashing with virtual nodes so
adding a shard moves only 1/N of keys).
- Win: uniform key distribution across all shards even when keys are sequential timestamps or auto-incrementing IDs.
- Trap: adjacent keys live on different machines, so range scans must scatter-gather across every shard in the cluster.
The real cost of sharding: joins and secondary indexes
Once data lives on separate machines, features you took for granted on a single SQL database become expensive:
- Cross-shard joins: joining
orders(sharded byorder_id) withusers(sharded byuser_id) requires network round-trips across shards. Production teams co-locate related tables by the same shard key (e.g. shard both byuser_id) or denormalize. - Local vs global secondary indexes:
- Local index: each shard indexes only its own rows. Writes stay fast (1
shard), but querying by a non-shard column must scatter-gather all
Kshards. - Global index: partitioned separately by the indexed column. Reads hit 1 index shard, but every write must update multiple shards asynchronously.
- Local index: each shard indexes only its own rows. Writes stay fast (1
shard), but querying by a non-shard column must scatter-gather all
Break it: the celebrity hotkey problem
Even a perfect cryptographic hash function has one blind spot: it always
hashes the exact same key to the exact same shard. When a celebrity with 100
million followers posts a photo, 90% of incoming likes target celeb:taylor
and hammer a single shard into red overload while the rest of the cluster sits
idle.
Interactive lab: melt a shard and fix it with key salting
Below, a celebrity spike is saturating Shard 2 at 148% capacity. Compare it
with normal uniform traffic, then toggle key salting (N=4) to
append #0..#3 to the hot key and watch write load balance immediately — at
the cost of a 4-way read fan-out.
interactive · trigger a celebrity spike on Shard 2, then toggle key salting (N=4)
peak load: 148% · read fan-out: 1 shardShard 2 saturated at 148% capacity while 3 shards sit at 4% idle
Three production defenses against hotkeys
- Key salting (split hot keys): append a random suffix
0..(N-1)to known hot keys (celeb:taylor#0..celeb:taylor#3) so writes distribute acrossNshards. Readers query allNsalted keys and sum/merge them. Tip: salt only detected hot keys (tracked via a small config/hot-key detector), not every normal user! - Write buffering / aggregation: for counters (likes, views), accumulate
increments in memory or Redis/Kafka for 1–5 seconds and flush one batched
+4,200update to the shard instead of 4,200 individual row locks. - Dedicated read cache: if the hotkey is read-heavy (a viral tweet payload), serve reads from multi-node Redis replicas or CDN edge caches so the shard only handles writes.
note
Do not shard prematurely. A single well-indexed PostgreSQL primary with read replicas and Redis caching comfortably handles tens of thousands of QPS and terabytes of data. Shard only when single-node write throughput or storage limits are genuinely in sight.
Where this shows up in system design
- Instagram Celebrity LikesSalted counter keys and buffered aggregation stop a single viral post from melting the shard that owns its media_id.
- Uber Geo-ShardingSpatial indexes (H3 hexagons) partition driver locations by city/cell so nearby-driver queries hit local shards instead of the whole planet.
- Multi-Tenant SaaS DatabasesSharding by tenant_id keeps joins local per customer, while enterprise whales get isolated onto dedicated shards.
- YouTube View CountersSharded write-ahead counters absorb viral spikes per video and periodically roll up totals for display.
Check yourself: system design scenarios
interactive · choose the right sharding design for each bottleneck
1. Sharding a multi-tenant B2B analytics app
always filters by org_id · joins within org · 16 shards
Every query in your SaaS product filters by `org_id` and joins `events`, `users`, and `projects` belonging to that organization. You need to shard across 16 PostgreSQL instances.
Select an option to check the trade-off.
2. Viral product counter melts one shard
hash sharding · 1 hot key · write saturation
Your e-commerce app hashes `product_id` across 8 shards. During a sneaker drop, 95% of inventory/like writes target `product:air-99`, saturating Shard 5 while the other 7 shards sit at 3% CPU.
Select an option to check the trade-off.
3. Avoiding unnecessary read fan-out with key salting
N=10 salting · normal users slowed · reduce fan-out
After enabling `N=10` key salting on your likes table, writes are balanced — but read latency for normal users with 5 likes jumped 4x because every read queries 10 shards.
Select an option to check the trade-off.
B-Treestorage
A self-balancing sorted tree stored in fixed-size disk pages, used by relational databases for primary and secondary indexes.
key saltingsharding
Appending a small random suffix (e.g. 0–9) to a hot partition key to spread writes across shards, at the cost of fan-out reads.