System Design

Patterns

Contention and Hot Keys

Adding machines divides the key space. It never divides a key. Skew comes in three forms, they have three different fixes, and hashing solves none of them.

The shape

One logical key gets more of something than one machine can handle. That is the whole pattern. It needs its own page because every way of spreading load across machines does nothing about it.

Hashing, consistent hashing, virtual nodes, more shards and bigger clusters all divide the key space, the set of all keys, across machines. A hot key is one key. It has one hash value, so it lands on one machine. If you rehash, the key moves to a different machine, and the problem moves with it. Adding machines divides the key space. It never divides a key.

Doubling the shards
Each blue bar is the load from ordinary keys on one shard, and the dashed line is what one shard can handle. On the left, one of four shards also holds the hot key, and its red load alone passes the line. On the right, with eight shards, each blue bar is half as tall. The red bar is the same height as before, and it is still on one shard.Each blue bar is the load from ordinary keys on one shard, and the dashed line is what one shard can handle. On the left, one of four shards also holds the hot key, and its red load alone passes the line. On the right, with eight shards, each blue bar is half as tall. The red bar is the same height as before, and it is still on one shard.
More shards do not divide the hot key. Each blue bar is the load from ordinary keys on one shard, and the dashed line is what one shard can handle. On the left, one of four shards also holds the hot key, and its red load alone passes the line. On the right, with eight shards, each blue bar is half as tall. The red bar is the same height as before, and it is still on one shard.

Real traffic is never spread evenly across keys. In any real system, a handful of keys carry far more data or traffic than the rest. This is not a one-off spike. It is the normal shape of the traffic. That imbalance is in your system now, whether or not you have measured it.

Three different problems with one name

"Hot key" is used for three unrelated problems. Each has its own fix, and when people mix the problems up, they apply the wrong fix.

Three problems called hot key
On the left, one tenant holds 1.6 TB against a mean of 200 MB, 8,000 times more, so its red bar is not drawn to scale. In the middle, every blue request goes to the one red key while the grey keys sit idle. On the right, each post from one account goes to every follower. The fix for each is in green. The red row at the bottom applies to all three: spreading keys over more machines does not help, because each problem sits on one key.On the left, one tenant holds 1.6 TB against a mean of 200 MB, 8,000 times more, so its red bar is not drawn to scale. In the middle, every blue request goes to the one red key while the grey keys sit idle. On the right, each post from one account goes to every follower. The fix for each is in green. The red row at the bottom applies to all three: spreading keys over more machines does not help, because each problem sits on one key.
Each problem has its own fix. On the left, one tenant holds 1.6 TB against a mean of 200 MB, 8,000 times more, so its red bar is not drawn to scale. In the middle, every blue request goes to the one red key while the grey keys sit idle. On the right, each post from one account goes to every follower. The fix for each is in green. The red row at the bottom applies to all three: spreading keys over more machines does not help, because each problem sits on one key.

Too much data. One tenant holds 1.6 TB when the mean is 200 MB. Its partition grows past the size limit for one partition, and no number of shards helps. The fix is to add a second part to the key. You shard that one oversized tenant, often called a whale, on (tenant, project), and every other tenant stays on tenant. The cost is two routing schemes in one system.

Too much traffic. One product, one video or one celebrity account gets 150,000 requests a second. The partition that holds it hits its throughput limit while the rest of the cluster sits idle. For reads, the fixes are coalescing, replicating the value and demotion. For writes, the fix is splitting the key. The moves below explain each one.

Too many edges. One account has 50 million followers. Its row is not large, and its request rate is normal. The problem is its fan-out, the number of other records that one action touches. Each post from this account has to reach 50 million followers. Changing where the key lives cannot fix this. Only a different data model can. The usual one is a hybrid: feeds for ordinary accounts are built ahead of time, and posts from the extreme accounts are added when someone reads their feed.

The table total hides the hot key
Both lines are a share of a limit. The blue line is the whole table's traffic against the whole table's capacity, and it stays near 30 percent. The red line is one hot key's traffic against the limit of the shard that holds it. Once the red line passes 100 percent, that shard rejects requests, shown by the red band, and the blue line has not moved.Both lines are a share of a limit. The blue line is the whole table's traffic against the whole table's capacity, and it stays near 30 percent. The red line is one hot key's traffic against the limit of the shard that holds it. Once the red line passes 100 percent, that shard rejects requests, shown by the red band, and the blue line has not moved.
The table looks calm while one shard rejects requests. Both lines are a share of a limit. The blue line is the whole table's traffic against the whole table's capacity, and it stays near 30 percent. The red line is one hot key's traffic against the limit of the shard that holds it. Once the red line passes 100 percent, that shard rejects requests, shown by the red band, and the blue line has not moved.

The moves

There are four moves, and you can use more than one at a time. Try them in this order, cheapest first. Demotion comes last even though it is cheap to build, because it needs a product decision.

Coalesce. If 1,000 requests for the same key arrive at the same time, one of them fetches it and the rest wait for that fetch. This is request coalescing, also called single-flight or thundering-herd suppression. It is usually about a dozen lines of code in front of a cache. The 1,000 cache misses become one fetch to the origin server, the server behind the cache that holds the real data. Without coalescing, a hot key sends 1,000 requests to the origin server at once, which is called a stampede. With it, the origin server sees one request. This is the cheapest fix. It needs no change to the data model, and for values that never change it has no consistency cost.

Replicate the value. Store k full copies of the hot key, for example hotkey:0 through hotkey:k-1, each holding the same value. A read picks one copy at random, so each copy sees only 1/k of the read traffic. A write has to update all k copies, so each write costs k writes. If a read reaches a copy before the write has updated it, the read gets a stale value. This is fine for data that is read often and never changes after it is written. It is bad for a counter that changes all the time, because a stale copy gives a wrong number.

Split the key. Turn one hot key into k physical keys by adding a short suffix, called a salt, to the key name, for example hotkey:0 through hotkey:k-1. Each write goes to just one of them. This is the only move that helps a key with too many writes. Instead of one key taking every write, each of the k keys takes about 1/k of them. A counter split this way is called a sharded counter, and a read has to fetch all k keys and add them up to get the true total. So every read now costs k lookups. That is why k should be the smallest number that brings each key's writes under the per-key limit, not the largest number you can manage.

Copies or split keys
Both drawings use k = 4. On the left, a write updates all four copies, and a read picks one copy at random. On the right, each write lands on one key, and a read fetches all four and adds them up: 3 + 5 + 2 + 4 = 14.Both drawings use k = 4. On the left, a write updates all four copies, and a read picks one copy at random. On the right, each write lands on one key, and a read fetches all four and adds them up: 3 + 5 + 2 + 4 = 14.
Copies make writes cost more, and split keys make reads cost more. Both drawings use k = 4. On the left, a write updates all four copies, and a read picks one copy at random. On the right, each write lands on one key, and a read fetches all four and adds them up: 3 + 5 + 2 + 4 = 14.

Demote. Serve the hot key from a cheaper source that may be a little out of date. The source can be a cache inside the application's own process that refreshes every few seconds, an edge server of a content delivery network (CDN), or a snapshot that is rebuilt on a schedule. This move needs a product decision, because you are choosing to answer with data that might be a few seconds or minutes old. Once that decision is made, demotion is often the cheapest of the four.

Back of envelopeWhy coalescing comes first
Step 1: how many requests arrive while the cache is empty?
  one key, 150,000 requests/s, refill takes 50 ms after expiry
  150,000 req/s x 0.05 s refill window = 7,500 requests

Step 2: without coalescing, what happens to those 7,500?
  every one of them sees a cache miss and independently
  fetches the same bytes from the origin server
  origin server fetches = 7,500

Step 3: with coalescing, what happens instead?
  only the first request fetches from the origin server
  the other 7,499 just wait on that one fetch to finish
  origin server fetches = 1, done in the same 50 ms

Step 4: what did that buy you?
  7,500 origin server fetches -> 1, a 7,500x reduction in load
  and it costs nothing: no schema change, no new placement,
  no new consistency guarantee

Splitting the key would also have worked, but it costs k
lookups on every read, forever. Coalescing costs nothing
after this one fix. Do the free one first.

How to tell you have this problem

Do not wait for an incident to find out. Three queries answer the question.

  1. Sort your keys by how much data each one holds, in bytes, and look at the top 0.1 percent. This finds the too-much-data case: the whale tenant at 1.6 TB when the mean is 200 MB.
  2. Separately, sort your keys by request rate and look at the top 0.1 percent again. This finds the too-much-traffic case: the celebrity key that gets 150,000 requests a second.
  3. Sort your accounts by follower count, or by however many records one of their actions touches, and look at the top 0.1 percent. This finds the too-many-edges case: the account whose single post has to reach 50 million followers.

These are three different lists, and they point to three different fixes. If you have only ever looked at averages, you know nothing about either. When the mean is 200 MB and the largest key is 1.6 TB, the mean still looks normal.

Four signs in production, roughly in the order they show up:

  • One key's p99 latency, the time within which 99 percent of its requests finish, is much worse than the whole table's.
  • One partition is being throttled while the system as a whole is lightly used.
  • One replica or partition is always busier than the others, and no difference in configuration explains it.
  • The cache hit rate drops sharply for a short time, again and again, instead of falling slowly.

What it costs

Every move here adds complexity, and the options that look cheap are not always the cheap ones.

Coalesce. It needs a shared data structure that tracks which fetches are in progress. When a new request finds a fetch already running, it waits on that fetch instead of starting its own. This structure needs care when things fail. If the one fetch in progress fails, every request waiting on it has to be told, or those requests wait forever.

Replicate the value. Every write has to reach all k copies before the copies agree with each other. Until it does, a read can pick a copy that still holds the old value.

Split the key. Every read becomes k reads, permanently, for every key that uses the scheme. That includes the 99.9 percent of keys that were never hot and never needed the extra lookups.

Demote. This is the cheapest of the four to build and the hardest to agree to. Someone on the team has to approve serving an answer that might already be out of date.

Where it shows up in the course

articlethe form it takes there
Back-of-Envelope Estimationwhy an average tells you nothing, and total capacity does not help a single key
Caching Strategies and Invalidationthe stale-set race and the thundering herd, which are both one key being asked for by everybody at once
Capacity Planning and Autoscalinga hot key is load more nodes can't spread, so autoscaling the tier does nothing for it; splitting or copying the key does
CDNs and Edge Computea single popular object at one PoP, where the edge absorbs the read hotspot the origin server could not
Consistent Hashingvirtual nodes fix uneven arc lengths and cannot touch one popular key
Design a Distributed Message Queuea key's records stay in one partition to stay in order, so the busiest key must fit inside one partition's rate
Design a Leaderboard / Ranking Servicean event board taking 167,000 writes a second is one key a cluster can't divide, so it's split by player into 8 keys
Design a Payment Systemevery capture posts to the processor's receivable and the commission account: 2 rows each in one region, 15 across regions, or fold balances in batches
Design an Ad Click Aggregatormore subtasks never divide one key; summing locally first cuts the busy ad's writes, which works because counts add in any order
Design Google Docs (Collaborative Editing)a hot document is one key that can't be split, so the live session is capped and everyone else reads a published copy
Distributed Cachea one-second copy in each router demotes the hot key, and a copied pool replicates small multi-get sets
Distributed Rate Limitera single principal generating enough traffic to saturate the shard holding its counter
Distributed Transactions and Sagasa hot row inside a two-phase commit, where locks held across the round trips cap its writes
Dropbox and Google Drivea namespace is one key, one lock and one journal; coalescing lists and a tail cache are the moves that help
Geospatial Indexingone Redis GEO key per city puts the largest city on one shard, and indexing by cell is the split that fixes it
Instagrama single post's like counter taking six figures a second of increments against one row
Key-Value Storea split divides the key space, never one key: replicas and a cache for reads, the leader for read-modify-write, sub-keys last
Message Queues vs Event Streamsthe one case where hashing cannot help at all, because ordering per key is what forbids spreading the key
News Feed and Timelinethe celebrity post, where the hot key on the read side is what rescues you from the hot write
Notification Servicea viral post makes its author a hot recipient, fixed by merging on that key rather than splitting it
Partitioning and Shardingthe whale tenant, and the fact that shard count cannot divide a key
Push Notification Deliverya broadcast to 10 million devices, and the taps a minute later that all ask for the same article
Ticketmaster Bookingan on-sale is a hot key with a date on it: the line caps traffic and server-side allocation stops fights over single seats
Uber Ride-Hailinga busy dispatch area is a hot key one level up, safe to split because the claim keeps a driver to one rider
URL Shortenerone link going viral, which the code scheme does nothing about, fixed by coalescing plus edge replication
Web Crawlerevery host is a key with a rate limit someone else sets, so more fetchers raise the total rate and never one host's
WhatsApp and Chat Systemsa large group where every message multiplies into one write per member
YouTubea trending video's view counter, taking six figures a second against one key
Live Comments and Reactionsone heart counter per stream would take 500,000 increments a second, so the taps are added up on the phone and on the gateway before any shared key

Getting it wrong

Reaching for a bigger cluster. Total capacity is not the limit. The limit is what one partition can handle, and adding machines does not raise it.

Splitting when coalescing would have been enough. Splitting is permanent and adds cost to every read. Try the free move first.

Choosing k too large on a split. For a key with too many writes, k should be the smallest number that brings each key under the write limit. Each extra key adds a lookup to every read.

Fixing the traffic problem and ignoring the size problem. The two are unrelated. A key can be hot and small, or huge and idle. The same key can also be both, and then it needs both fixes.

Letting a hot key take a node down. In any tier that routes by hash, a failed node's keys move to a neighbour, and the hot key's load moves with them. That makes the neighbour more likely to fail next. A node at its limit should shed load, refusing the excess or sending it to a fallback, and not crash. Otherwise one hot key causes a chain of failures.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.