The Hot Key Problem
When one key gets so much traffic that a single shard melts — and how to spread that heat without breaking correctness.
The hot key problem in 30 seconds
- What: one key (a celebrity's profile, a viral post, a flash-sale item) gets a wildly disproportionate share of traffic.
- Why it hurts: sharding assumes load spreads evenly — but all requests for one key land on one shard, so that shard melts while the rest sit idle.
- Read fix: cache the hot key hard (CDN / local in-process cache), and split the cache key into N replicas so load fans out across cache nodes.
- Write fix: don't fan-out-on-write for VIPs; fan-out-on-read (pull) their content at feed-build time instead.
- Counter fix: shard a hot counter into N sub-counters and sum on read, so increments don't serialize on one row.
- First ask: can I detect the hot key automatically and route it to a special path, rather than treating every key the same?
The stadium turnstile
Picture a stadium with ten turnstiles. On a normal day the crowd spreads out and every gate flows smoothly. Now a superstar walks in through gate 3, and suddenly everyone crushes toward that one gate for a photo. Nine turnstiles stand empty while gate 3 is a dangerous crush. Your database shards are those turnstiles, and a hot key is the superstar — one key that draws a crowd so large it overwhelms the single shard it lives on, no matter how many other shards sit idle.
Why sharding doesn't save you here
Sharding's whole promise is spread the load evenly. You hash a key, pick a shard, and on average every shard gets its fair slice. That average is a lie the moment traffic is skewed:
- A celebrity with 200M followers: every one of their fans reads the same profile row and the same latest posts — all on one shard.
- A viral tweet: millions of reads of a single post ID in minutes, hammering whichever shard owns it.
- A flash sale: everyone decrements the same inventory counter, so writes serialize on one row and queue up.
- A trending hashtag: one key's index grows and gets read far faster than any other.
The common thread: the access distribution is power-law, not uniform. A tiny number of keys get the overwhelming majority of the traffic. Hashing distributes keys evenly, but it can't distribute traffic evenly when the traffic itself is lopsided.
Spotting it in the wild
Before you fix a hot key you have to find it. The symptoms are distinctive:
- One shard (or one cache node) runs hot — high CPU, high latency — while its siblings are bored.
- p99 latency spikes for a subset of keys even though average load looks fine.
- A single partition's queue depth or connection count dwarfs the others.
- Tail-latency alarms that correlate suspiciously with a trending item or a known VIP.
# A lightweight 'heavy hitter' sketch: count a 1% sample of request keys.
# Cheap enough to run inline; exposes the skew without tracking every key.
from collections import Counter
hits = Counter()
def on_request(key):
if random.random() < 0.01: # sample 1% of traffic
hits[key] += 1
# Periodically inspect the top keys. If one key dwarfs the rest,
# it is hot and should be routed onto the special hot-key path.
def hottest(n=10):
return hits.most_common(n) # e.g. ('user:celebrity', 48213)Fix 1 — Cache the hot key, then split the cache key
A hot key is almost always a read problem first, and reads love caches. Step one is obvious: put the hot value in a cache so most reads never reach the database. But at celebrity scale a single cache entry has the same flaw — every read hits the one cache node that owns that key. So step two is to split the hot key into N physical copies and spread the reads across them:
# Instead of one cache entry 'user:celeb', keep N copies:
# user:celeb#0, user:celeb#1, ... user:celeb#N-1
# Each copy may live on a different cache node, so reads spread out.
N = 16
def read_hot(key):
replica = random.randint(0, N - 1) # pick a random copy
physical = f"{key}#{replica}"
val = cache.get(physical)
if val is None: # cold copy -> fill it
val = db.get(key) # the single source of truth
cache.set(physical, val, ttl=30)
return val
def invalidate_hot(key):
# A write must bust ALL N copies, not just one.
for r in range(N):
cache.delete(f"{key}#{r}")Fix 2 — VIP feeds: fan-out-on-read, not on-write
This is the classic celebrity-feed problem, and it's worth seeing why the normal approach breaks. Most social feeds use fan-out-on-write: when you post, the system pushes your post ID into every follower's inbox so their feed is pre-built and instant to read. That's great for an ordinary user with 300 followers — 300 cheap writes. For a celebrity with 200 million followers, a single post becomes 200 million writes, a thundering-herd that can stall the whole write pipeline. (See Design a News Feed for the full treatment.)
The fix is a hybrid: fan-out-on-write for normal users, but fan-out-on-read (pull) for VIPs. Don't push a celebrity's post to anyone. Instead, when a follower opens their feed, merge their pre-built inbox with a fresh pull of the few VIPs they follow:
VIP_FOLLOWER_THRESHOLD = 1_000_000 # above this, do NOT fan out on write
def on_post(author, post):
if follower_count(author) < VIP_FOLLOWER_THRESHOLD:
for follower in followers(author):
inbox.push(follower, post.id) # cheap for normal users
# VIPs: write nothing to followers. Their posts are pulled at read time.
def build_feed(user):
pushed = inbox.recent(user) # pre-built, instant
vips = [a for a in following(user) if is_vip(a)]
pulled = [p for a in vips for p in recent_posts(a)] # live pull, cached hard
return merge_by_time(pushed + pulled) # one blended timelineThis flips the celebrity from a write hot key (200M writes per post) into a read hot key on their own recent-posts list — which Fix 1 (cache + replica split) handles comfortably. You've moved the heat to where you have a good tool for it.
Fix 3 — Hot counters: shard the count
A viral post's like count, a flash-sale's inventory, a live-stream's viewer count — these are write hot keys. Every increment targets the same row, and the database must serialize those writes (a lock per update), so they queue behind each other and latency climbs. The trick is to split one counter into N sub-counters, increment a random one, and sum them only when you need the total:
// One row per counter serializes every writer. Split into N shards instead.
int N = 20;
void increment(String counterId) {
int shard = ThreadLocalRandom.current().nextInt(N); // random sub-counter
db.execute("UPDATE counters SET value = value + 1 " +
"WHERE id = ? AND shard = ?", counterId, shard);
// Writers now spread across N rows -> ~N times the write throughput.
}
long total(String counterId) {
// Reads pay a small price: add up the N shards.
return db.querySum("SELECT SUM(value) FROM counters WHERE id = ?", counterId);
}Fix 4 — Local caching and request collapsing
Two more tools that shine for hot keys:
- In-process (L1) cache: keep the hot value in each app server's own memory for a few seconds. A thousand requests on one box then cost one upstream fetch, not a thousand. The hotter the key, the better the hit rate — hot keys are the easiest things in the world to cache.
- Request collapsing (single-flight): when many requests for the same cold hot-key arrive at once, let only the first go to the database; the rest wait and share its result. This prevents a cache miss on a hot key from becoming a stampede (see Caching).
const inflight = new Map(); // key -> Promise of the value
function getHot(key) {
const cached = localCache.get(key);
if (cached) return Promise.resolve(cached); // L1 hit, no network
if (inflight.has(key)) return inflight.get(key); // join the in-flight fetch
const p = db.get(key).then(val => {
localCache.set(key, val, 5_000); // 5s L1 TTL — fine for a hot key
inflight.delete(key);
return val;
});
inflight.set(key, p); // everyone else now awaits this same promise
return p;
}Choosing a fix
| Symptom | Reach for | The catch |
|---|---|---|
| Hot read key (profile, viral post) | Cache + split key into N replicas; L1 cache | Must invalidate all N copies; brief staleness. |
| VIP / celebrity feed write storm | Hybrid fan-out: pull for VIPs, push for normals | Read path must merge pushed + pulled. |
| Hot counter (likes, views) | Sharded counter, sum on read | Total lags slightly; not for exact inventory. |
| Flash-sale inventory | Atomic decrement in fast store / reservation | Single-key throughput ceiling; needs correctness care. |
| Cache-miss stampede on a hot key | Request collapsing (single-flight) | Adds a touch of coordination latency. |
The hot key problem is where the neat theory of even sharding meets the messy reality of power-law traffic — a few keys always matter far more than the rest, and a system that ignores that will tip over at its most important moment.
Why it matters
- It's the difference between a launch, a viral moment, or a celebrity post being your proudest day or your worst outage.
- It forces you to separate distributing keys (what hashing does) from distributing traffic (what you actually need).
- The fixes — replica splitting, hybrid fan-out, sharded counters — are reusable tools that show up across caching, feeds, and counting.
If ignored
- One shard or cache node melts under a single key while the rest of a huge cluster sits idle.
- A celebrity's post triggers a write storm that stalls the feed pipeline for everyone.
- A flash sale serializes on one inventory row and times out exactly when demand is highest.
Where it fits
- Sits across the read and write paths wherever a key's popularity can spike far above the average.
- Lives in the caching layer, the feed-assembly service, and the counter/inventory design.
- Is a design-time decision (detect-and-route the hot path) as much as a runtime mitigation.
Related topics
- Sharding: the even-spread assumption that a hot key violates
- Caching: the first and best tool for a hot read key; stampede protection lives here
- Consistent hashing: how keys map to nodes, and why one node can run hot
- Design a News Feed: the full celebrity-feed fan-out problem, start to finish
Interview lens
Questions it unlocks
- A celebrity with millions of followers posts — why does fan-out-on-write fall over, and what do you do?
- One shard in your cluster is melting while the others are idle. What's happening and how do you fix it?
- How would you handle the like-count on a viral post getting millions of increments a minute?
60-second answer
A hot key is one key that takes a wildly disproportionate share of traffic, so even perfect sharding can't help — every request for that key lands on one shard. For a hot read, like a celebrity profile or viral post, I cache it hard and split the cache key into N replicas so reads fan out across cache nodes, plus an in-process L1 cache and request collapsing to kill stampedes. For a VIP feed I switch from fan-out-on-write to a hybrid: push posts for normal users but pull VIPs' posts at read time and merge, which turns a 200-million-write storm into a cacheable read. For a hot counter like likes I shard the counter into N sub-counters and sum on read. The meta-move is detecting the hot key and routing it onto a special path rather than treating every key the same.
Common traps
- Assuming sharding alone solves skew — it distributes keys, not traffic.
- Fanning out a celebrity post on write and triggering a write storm.
- Using a sharded (eventually-summed) counter for exact inventory and overselling.
- Caching a hot key on a single node so the cache node becomes the new bottleneck.