Hot keys, hot partitions and fan-out
In one line
Sharding spreads load only if traffic is spread across keys; when one key (a celebrity, a flash-sale product, a live match) gets a large share of reads or writes, its partition melts, and you fix it by caching and replicating hot reads, splitting hot writes, and choosing fan-out on write or on read per user.
What it is
Partitioning by key assumes keys get similar traffic. Real traffic follows a power law: a few keys get most of it. A hot key is one key with far more traffic than others (the score of an India vs Pakistan match, the iPhone listing at 12:00 on sale day, a celebrity's profile). A hot partition is a shard overloaded because of one hot key or many busy keys that hash to it. Adding more shards does not help, because one key always lives on one shard.
Every store has a per-partition ceiling. A single Redis node handles roughly 100,000 to a few hundred thousand simple operations per second on one main thread; a DynamoDB partition supports up to 3,000 read units and 1,000 write units per second; a Kafka partition is consumed by one consumer in a group. One key cannot exceed its partition's ceiling, however big the cluster.
Fan-out is the related problem of one action creating work for many keys. When a user with 50 million followers posts, fan-out on write (push) inserts the post into 50 million timelines; fan-out on read (pull) leaves timelines alone and merges recent posts from followed accounts at read time. Each moves cost to a different place, and big accounts break the pure push model.
Why interviewers ask
Interviewers love the celebrity problem in feed designs, the hot product in flash sales, and the hot counter for likes and views, because it tests whether you understand that sharding has limits. Strong candidates name the hot key early, estimate its peak load, and pick a targeted fix (local caching, key splitting, write buffering, hybrid fan-out) instead of saying 'add more servers'.
How it works
- 1Detect: track per-key or per-partition request rates (Redis --hotkeys or client-side sampling, DynamoDB CloudWatch Contributor Insights, Kafka per-partition lag). Alert when one partition's load is far above the average.
- 2Hot reads, first fix: cache close to the caller. A small in-process cache (Caffeine, a local LRU) with a 1 to 5 second TTL on each app server means 200 servers send at most about 200 requests per TTL window to Redis instead of hundreds of thousands per second.
- 3Hot reads, second fix: replicate the hot key. Store copies under key#1 ... key#N on different shards and let readers pick one at random; writes update all copies. Or serve it from a CDN if it is public, such as a match scorecard.
- 4Request coalescing: when many requests miss the same key at once, let one fetch it and the others wait for that result (single-flight), so a cache miss does not become a stampede on the database.
- 5Hot writes, split the key: a counter becomes N sub-counters (likes:post42:0 ... likes:post42:15), each write goes to a random one, and reads sum them. Write capacity grows N times; reads get slightly more expensive.
- 6Hot writes, buffer and batch: aggregate increments in memory or in a stream for a second, then write one combined update. Ten thousand +1s become one +10,000.
- 7Hot partitions from bad keys: avoid monotonic or low-cardinality partition keys (timestamp, date, country). Add a salt or bucket to spread load, for example (event_date, bucket 0-31), and query all buckets in parallel.
- 8Fan-out: push for normal users (precompute timelines in Redis at write time), pull for celebrities above a follower threshold (merge their recent posts at read time), and skip pushing to inactive followers. This hybrid is what most large feeds use.
- 9Protect the hot path anyway: rate-limit per key, shed low-priority work, and design queues so one hot key does not block a whole partition, for example by using a dedicated topic or partition for it.
Worked example · Live cricket score key during a big match
- Audience: 30 million concurrent app users poll the score every 10 seconds = 3 million reads per second, all on one key, score:match123.
- A single Redis shard handles maybe 150,000 to 200,000 ops per second, so one key is 15 to 20 times over the limit of its shard. Adding Redis shards does nothing, since the key lives on one shard.
- Fix 1: the score is public and the same for everyone, so serve it as a small JSON from the CDN with a 2 second cache. The CDN absorbs the 3 million per second; the origin sees about one request per edge location every 2 seconds.
- Fix 2: for app servers that need it internally, a 1 second in-process cache. 500 servers produce about 500 reads per second to Redis.
- Fix 3: the scoring service writes the new score once per ball (about every 30 to 40 seconds) to the origin; a push channel (WebSocket or SSE) can notify clients instead of polling, cutting load further.
- Result: the hot key costs Redis about 500 reads per second instead of 3 million, and the delay users see is at most 2 to 3 seconds.
Picture it
A railway station has 20 ticket counters, but everyone queues at the counter that sells Tatkal tickets, so 19 counters sit idle while one collapses. Adding a 21st counter does not help. You either open more counters that sell the same Tatkal tickets (replicate or split the key) or put the timetable on a big board so people stop asking at the counter (cache it close to them).
Reference code
# Split a hot counter across N sub-keys; read by summing
import random
N = 32
def incr_like(r, video_id: str, n: int = 1):
r.incrby(f"likes:{video_id}:{random.randrange(N)}", n)
def get_likes(r, video_id: str) -> int:
keys = [f"likes:{video_id}:{i}" for i in range(N)]
# In Redis Cluster these keys hash to different slots on purpose, so read them
# with a pipeline per node or a background job that stores the total.
return sum(int(v or 0) for v in (r.get(k) for k in keys))Key patterns
Local cache with short TTL
When: Hot reads of data that tolerates a second or two of staleness
How: In-process LRU on each app server with a 1-5 s TTL, plus single-flight to collapse concurrent misses.
Key splitting (write sharding)
When: Hot counters or hot write keys
How: Spread writes over key:0..N-1 at random; read by summing or by a periodically computed total.
Write batching
When: High-frequency increments or updates on few keys
How: Aggregate in memory or in a stream processor for a short window and apply one combined write.
Hybrid fan-out
When: Social feeds with a long tail of popular accounts
How: Push posts to followers' timelines for normal accounts; pull and merge posts from celebrity accounts at read time; skip inactive followers.
Isolate the hot key
When: A known event will create a hot key (sale, match, launch)
How: Pre-warm caches, give the key its own shard, topic or service pool, and admit traffic through a queue or rate limiter.
Real-world use
Twitter's timeline fan-out
Twitter precomputed home timelines in Redis by fanning out each tweet to followers at write time, but handled accounts with very large follower counts differently, merging their tweets at read time to avoid millions of writes per tweet.
Instagram and Facebook celebrity accounts
Facebook's memcache paper describes hot keys and uses regional replicas and leases to stop thundering herds; very popular objects are effectively replicated so no single cache server takes all their load.
Amazon DynamoDB adaptive capacity
DynamoDB automatically shifts throughput to hot partitions and can split a partition by key range, but a single partition key still has hard per-key limits (about 3,000 reads and 1,000 writes per second), so write sharding with suffixes is still recommended for very hot keys.
Flash sales in Indian e-commerce
Sale events such as Big Billion Days create extreme traffic on a few product IDs at the moment the sale opens. Common techniques are pre-warmed caches, inventory split into buckets across shards, queue-based admission ('you are in line') and rate limiting per product.
JioHotstar and live streaming
Live cricket concentrates tens of millions of viewers on one stream and one score feed, so these are served mostly from CDNs and caches at the edge rather than from origin databases.
In a project
A short-video app stores like counts in a Redis cluster keyed by video ID. When a film star posts a video, likes reach 80,000 per second on one key, that Redis shard's CPU hits 100%, and every other key on the same shard (unrelated videos) starts timing out.
- Confirm with hot-key sampling that one key accounts for over 90% of that shard's operations.
- Split writes: for videos above a likes-per-second threshold, the like service writes to likes:{id}:{0..31} chosen at random, spreading writes across shards.
- Batch upstream: like events go to Kafka; a consumer aggregates per video per second and issues one INCRBY per sub-counter per second, cutting 80,000 writes per second to at most 32 per second.
- Reads: a background job sums the 32 sub-counters every second into likes:{id}:total, which readers fetch; app servers cache it in memory for 1 second. Users see approximate counts such as '1.2M', so a second of staleness is fine.
- Store the user-to-video 'liked' relation (needed for idempotency and the red heart icon) in a separate partitioned table keyed by user, so it is spread across shards naturally.
- Alert on per-shard CPU skew and automatically promote keys to split mode when they cross the threshold.
Impact: The hottest key's write load on Redis drops from 80,000 per second to about 32, other videos on the shard stop timing out, and the like count on screen lags by about 1 to 2 seconds, which users do not notice.
Trade-offs
Use it when
- Local caching or CDN: public or shared data read by huge numbers of users (scores, prices, trending lists)
- Key splitting: counters and aggregates where reads can sum or tolerate a short delay
- Write batching: likes, views, metrics and other commutative increments
- Fan-out on write: most users have modest follower counts and reads must be fast
- Fan-out on read: accounts with millions of followers, or many inactive followers
Avoid it when
- Key splitting for data that needs strict, immediate consistency (a bank balance), unless you design a proper ledger
- Long local-cache TTLs for data that must be fresh, such as stock during checkout
- Pure fan-out on write for celebrity accounts: millions of writes per post and minutes of delay
- Pure fan-out on read for every user: each feed load queries hundreds of followees
Common mistakes
- Answering 'add more shards' to a hot key; one key always lives on one shard.
- Choosing a partition key with low cardinality or a time prefix (date, status), which sends all current traffic to one partition.
- Ignoring the celebrity case in a feed design until the interviewer brings it up.
- Splitting a counter and then reading all N sub-keys on every page view, moving the hot spot to reads.
- Letting a hot key starve unrelated keys on the same shard without isolation or alerts.
- Forgetting cache stampedes: a hot key expiring causes thousands of simultaneous misses to the database.
Interview questions
Quick revision
- Traffic follows a power law; sharding cannot split one key.
- Per-partition ceilings: one Redis shard ~100k-200k+ ops/s; DynamoDB partition 3,000 RCU / 1,000 WCU.
- Hot reads: CDN, local cache with 1-5 s TTL, replicated key copies, single-flight.
- Hot writes: split key into N sub-keys, batch increments, buffer through a stream.
- Bad partition keys: low cardinality, timestamps, dates; add salt/buckets.
- Fan-out on write: fast reads, expensive for celebrities.
- Fan-out on read: cheap writes, expensive reads.
- Hybrid: push for normal users, pull for celebrities, skip inactive followers.
- Detect skew per partition and alert before it melts down.
- Pre-warm and isolate known hot keys before sales and matches.
Check yourself
1. One key receives 2 million reads per second and its Redis shard is overloaded. Why does adding more shards not help?
2. Which technique best handles a hot like counter receiving 50,000 increments per second?
3. Why do large social networks avoid pure fan-out on write for celebrity posts?
4. A table uses the event date as its partition key. What problem does this cause?
See it in a full design
These walkthroughs use this lesson.
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.