Hot Partitions - Complete Deep Dive
Prerequisites: Database Sharding, Consistent Hashing, Caching Used in: BookMyShow, Trending Topics, Leaderboard
What is a Hot Partition?
A partition (also called a shard) is one slice of a dataset, living on one machine, that gets its own share of the traffic. A hot partition is a partition receiving far more requests than its siblings — so much more that it saturates while the rest of the cluster sits idle. The cluster has capacity on paper; it just happens to be on the wrong machines.
The cause is almost always key skew: the distribution of requests across keys is wildly uneven, and partitioning assigns each key to exactly one partition. Add enough traffic to a single key and you have a single-machine problem again, no matter how many machines you bought.
Real-world analogy: Picture a supermarket with twenty checkout lanes. Customers are assigned a lane by the first letter of their surname, which is a perfectly reasonable rule and gives every lane roughly equal work on an ordinary day. Then a tour bus pulls up and three hundred members of the Patel family walk in. Lane “P” now has a three-hundred-person queue while nineteen lanes stand empty. Opening a twenty-first lane does not help — the rule still sends every Patel to lane “P”. The queue is not caused by too little capacity; it is caused by the mapping from customer to lane.
Why Sharding Does Not Fix This
The instinct when a database is overloaded is “add more shards.” That works for volume skew and fails for key skew, and the distinction is the whole concept.
| Problem | What is uneven | Does adding shards help |
|---|---|---|
| Too much total traffic | Nothing — load spreads evenly | Yes. Each shard gets a smaller slice. |
| Range skew | One contiguous key range is busy | Sometimes. Split that range further. |
| Single hot key | One key takes most of the traffic | No. That key still maps to one shard. |
A good hash function does not save you either. Hashing guarantees that keys are spread evenly across partitions. It says nothing about how requests are spread across keys. If 40% of your reads ask for post:9fa31 — the one celebrity post everybody is looking at — then hash("post:9fa31") resolves to the same partition every single time, by design. That determinism is what makes lookups work, and it is also what concentrates the load.
flowchart LR
REQ["10k requests per second"] --> H["hash of key mod 4"]
H --> P0["Partition 0<br/>500 rps"]
H --> P1["Partition 1<br/>8000 rps<br/>celebrity key lives here"]
H --> P2["Partition 2<br/>900 rps"]
H --> P3["Partition 3<br/>600 rps"]
P1 --> T["Throttling and timeouts<br/>for every key on this partition"]
New components in this diagram:
- hash of key mod 4: the partitioner. It is a pure function of the key, so the same key always lands on the same partition.
- Partition 1: the hot partition. Note the collateral damage — every other key that happens to share this partition now sees timeouts too.
That last point is the part people miss. One hot key does not degrade one key; it degrades every tenant of the machine that key lives on.
The Celebrity Problem
The canonical source of key skew is a power-law distribution of popularity. 💡 A power law means a few items get an enormous share of attention and the long tail gets almost none — unlike a normal distribution, there is no meaningful “average” item.
Real examples of the shape:
| System | The hot key | Why it spikes |
|---|---|---|
| Social feed | A celebrity account with 100M followers | One post fans out to 100M timelines |
| Ticketing | One show on sale at 10:00 AM | Every buyer contends on the same row |
| Chat | One viral group with 50k members | Every message fans out inside one conversation |
| Leaderboard | The global “all players” board | Every player reads the same sorted set |
| Metrics | One misbehaving service’s error counter | A retry storm writes to the same counter |
Two properties make this hard:
- You cannot predict which key goes hot. A restaurant becomes popular because a video went viral forty minutes ago. No static configuration anticipated it.
- The skew is transient. The hot key is hot for an hour, then a different one is. A fix that requires re-sharding the dataset is far too slow to matter.
Read-Path Fixes
If the hot key is being read far more than written, you have cheap options, because reads can be served from copies. Work through them in this order.
1. Cache the hot key. An in-memory cache in front of the database absorbs repeated reads, and the hottest key is also the most cacheable one — the highest hit rate in the whole cache. A local (in-process) cache on every application server is even better for extreme keys: it removes the network hop and the cache itself cannot become the new hot partition.
2. Add read replicas and spread reads across them. 💡 A read replica is a copy of the data that receives changes from the primary and serves read queries only. Six replicas of the hot partition turn one machine’s read budget into six. The cost is replication lag — a replica may be tens of milliseconds behind, so a user who just wrote something may not see it. Route the writer’s own reads to the primary if that matters.
3. Coalesce duplicate requests. On a cache miss for a hot key, a thousand concurrent requests will all miss and all hit the database at once. Request coalescing (also called single-flight) lets the first request do the work while the other 999 wait on its result, turning 1,000 database queries into 1.
flowchart LR
C["Clients"] --> L["Local cache on app server"]
L -->|miss| SF["Single flight gate<br/>one in flight per key"]
SF --> R["Shared cache"]
R -->|miss| DB["Hot partition"]
DB --> R
R --> L
New components:
- Local cache on app server: per-process copy with a short time to live, measured in seconds. Absorbs the bulk of celebrity reads before any network call.
- Single flight gate: per-key gate ensuring only one concurrent fetch per key reaches the tier below.
- Shared cache: the cluster-wide cache (Redis / Memcached class). Still partitioned, so a hot key here can hurt too — which is exactly why the local tier sits in front of it.
Write-Path Fixes: Salting and Sub-Partitioning
Reads can be copied; writes cannot. If 50,000 writes per second target one key, no amount of replication helps — every replica would need to absorb all 50,000. The only real fix is to stop them being one key.
Salting means appending a small random or derived suffix to the key so that one logical key becomes N physical keys, which hash to N different partitions.
Before: counter:post:9fa31 -> 1 partition, 50k writes/sec
After: counter:post:9fa31#0 .. #15 -> up to 16 partitions, ~3k writes/sec each
The suffix can be chosen three ways, and the choice decides what you can read back.
| Suffix strategy | Write spread | Read cost |
|---|---|---|
Random 0..N-1 |
Even | Must read all N sub-keys |
| Hash of writer ID mod N | Even if writers are many | Must read all N sub-keys |
| Time bucket, e.g. the minute | Even over time, hot now | Read only the buckets you need |
Sub-partitioning is the same idea applied to a range rather than a counter: a key range that is too busy is split into narrower ranges that can be placed on different machines. This is what most managed stores do internally, and the reason the hot range case is often solved for you while the hot key case is not.
Write batching is the third lever and often the simplest: buffer increments in the application for 200ms and flush one write of +847 instead of 847 writes of +1. You trade a small amount of freshness, and the risk of losing the buffer if the process dies, for a roughly 850x reduction in write volume.
The Read-Modify-Write Counter Case
The worst version of a hot key is a counter updated with read-modify-write: read the current value, add one, write it back. Two things go wrong at once.
- Contention. Every writer touches the same row, so the database serialises them. Throughput is capped by one row’s lock turnaround — often a few thousand per second, regardless of cluster size.
- Lost updates. If two writers read
100before either writes, both write101and one increment vanishes. Fixing that correctly requires optimistic concurrency or a lock, and under this much contention optimistic retries make the contention worse.
Three escapes, in increasing order of effort:
-- 1. Atomic increment: one round trip, no read. Removes lost updates.
-- Still one row, so still one hot partition.
UPDATE counters SET value = value + 1 WHERE key = 'post:9fa31';
2. Sharded counter: 16 rows instead of 1. Writers pick a shard at random.
Write: UPDATE counters SET value = value + 1
WHERE key = 'post:9fa31#' || random_shard
Read: SELECT SUM(value) FROM counters WHERE key LIKE 'post:9fa31#%'
3. Stream and aggregate: writers append events to a log partitioned by
something high-cardinality, a stream processor sums them per window,
and the result is written once per second.
Exact total, no contention, a second or two of staleness.
Option 2 is the usual answer in an interview. Say out loud what it costs: the read is now a scatter-gather over 16 sub-keys. 💡 Scatter-gather means sending N parallel sub-requests and combining the answers; its latency is the slowest of the N, not the average. You have traded a cheap read for a cheap write. That is the right trade only when reads are cacheable or rarer than writes.
Detecting Skew Before It Pages You
Cluster averages hide hot partitions completely. If one of sixteen partitions is at 100% and the rest are at 10%, the dashboard says 16% — comfortable. Three signals actually find it.
| Signal | What to collect | What it tells you |
|---|---|---|
| Per-partition metrics | Request rate, latency, CPU per partition, charted as max not mean | That skew exists, within seconds |
| Top-N key sampling | Sample 1 in 1,000 requests, keep a heavy-hitters sketch per minute | Which key is hot |
| Throttling and error events | Rejected or throttled requests, tagged with partition | That skew is already costing you |
Rules that hold across every store:
- Alert on the maximum partition utilisation, never the mean. The mean is the metric that let the incident happen.
- Record the key on throttled requests. A throttle event without a key tells you that you have a problem but not where.
- Keep a top-N keys per minute board. On a power-law workload this is the single most useful panel you can build, and sampling makes it nearly free.
See Observability for how to carry the partition identifier through as a metric dimension rather than losing it in an aggregate.
Real Systems: DynamoDB and Kafka
DynamoDB adaptive capacity. DynamoDB partitions by the hash of the partition key and historically divided your provisioned throughput evenly across partitions, so one hot partition was throttled while the table as a whole was under budget. Adaptive capacity now reallocates throughput toward busy partitions automatically and will split a partition by the key range it contains when the imbalance persists. What it still cannot do is split a single partition key — one key’s traffic has a hard per-partition ceiling. The write-sharding advice in DynamoDB’s own guidance exists precisely because the platform cannot solve the single-key case for you.
Kafka partition skew. A Kafka topic’s partitions are its unit of parallelism, and a message’s partition is hash(key) mod partitions. Two failure shapes follow:
- Producer skew. If most messages carry the same key — for example
tenant_idwhere one tenant is 70% of volume — one partition takes 70% of the writes and the consumer assigned to it falls behind while its peers idle. Fix by choosing a higher-cardinality key, or by usingnullkeys where ordering does not matter so messages round-robin. - Consumer skew. One consumer owns the hot partition and its lag grows without bound. Adding consumers does nothing: a partition is consumed by exactly one member of a group, so parallelism is capped by partition count, not consumer count.
The pattern generalises. Anywhere a key deterministically selects one machine — database shard, cache slot, queue partition, stateful stream task — the same failure is available.
Comparison of Fixes and Their Costs
| Fix | Helps | Cost you are accepting |
|---|---|---|
| Cache the hot key | Reads | Staleness up to the time to live; invalidation work |
| Local in-process cache | Extreme reads | Per-server staleness; memory on every host |
| Read replicas | Reads | Replication lag; replica cost; routing complexity |
| Request coalescing | Read spikes on miss | One shared failure affects all waiters; small added latency |
| Salting the key | Writes | Reads become scatter-gather over N sub-keys |
| Write batching | Writes | Freshness delay; buffered data lost if the process dies |
| Stream and aggregate | Extreme writes | A whole pipeline to run; seconds of staleness |
| Split the partition | Range skew only | Rebalance traffic; no help for a single key |
The shape of the table is the lesson: every fix moves cost somewhere else. There is no option that makes the skew free.
When to Accept the Skew
Mitigation has real complexity, and sometimes the right engineering decision is to leave the skew alone.
✅ Accept it when:
- The hot partition is hot but not saturated. 60% utilisation on one partition and 10% on the others is skew, not an incident.
- The spike is short and rare — a weekly sale — and queueing or briefly shedding load is acceptable. See Rate Limiting and Backpressure.
- A cache already absorbs it. A 99% hit rate on the celebrity key means the database never sees the skew.
- The fix would break a guarantee you need. Salting a key destroys per-key ordering and makes single-key transactions multi-key.
❌ Fix it when:
- The hot partition throttles or times out, because other keys on that partition suffer for a problem that is not theirs.
- The hot key is write-heavy, where replication and caching give you nothing.
- The hot key is unpredictable, so no capacity plan can anticipate it and the mitigation must be structural.
- The partition is a correctness bottleneck — all contention for one entity serialising through one lock.
Common Interview Questions
Q1: We hash our keys, so the load is even. Why would we have a hot partition?
Hashing distributes keys evenly across partitions; it says nothing about how requests distribute across keys. On a power-law workload one key can take 40% of all traffic, and because hashing is deterministic that key resolves to the same partition every time. Uniform hashing prevents range hotspots, not key skew. The only structural fix is to make one logical key into several physical keys through salting or sub-partitioning.
Q2: One celebrity account’s timeline is overwhelming a shard. What do you do?
Separate the read and write paths. For reads: a local in-process cache plus request coalescing, backed by extra replicas of that shard — celebrity data is the most cacheable data you have. For writes: stop fanning out to followers at write time for that account and let its followers pull on read instead, which is the standard hybrid fan-out answer. State the trade clearly — the pull path costs more per reader and risks slightly stale timelines, and you are accepting that to keep one shard alive.
Q3: How does salting change the read path, and when is that a bad trade?
After salting, the logical key no longer exists in storage — only
key#0throughkey#N-1do. Every read becomes a scatter-gather across all N sub-keys with the latency of the slowest one, and anything that depended on reading a single row, such as a conditional write on the counter, no longer works. It is a bad trade when reads are frequent and uncacheable, when you need a single-key transaction, or when per-key ordering matters, because the sub-keys have no ordering between them.
Q4: How would you detect a hot partition in production?
Three things, none of which is a cluster average. Per-partition request rate and latency charted as the maximum across partitions, so one saturated partition out of sixteen does not hide inside a 16% mean. A sampled top-N keys per minute board, built from a heavy-hitters sketch on roughly 1 in 1,000 requests, to identify which key is hot. And throttle or rejection events tagged with both partition and key, which is your highest-severity alert because it means the skew is already costing requests.
Q5: Does DynamoDB’s adaptive capacity mean hot partitions are solved?
It solves the easier half. Adaptive capacity reallocates throughput toward busy partitions and will split a partition’s key range when imbalance persists, so a hot range is largely handled for you. A single hot partition key is not: one key cannot be split across partitions, so it has a hard per-key throughput ceiling. That is why DynamoDB’s own guidance recommends write sharding — the platform is telling you it cannot solve the single-key case and you must change the key.
Navigation
| ← Database Sharding | Database Replication → |
| All Concepts | HLD Designs |