Hot keys

Why you need it

Data is usually spread over many servers by key, so each holds a share. But traffic is not shared fairly: one celebrity, one viral post, one sale item can get more requests than everything else together. The single server holding that key drowns while the others sit idle.

Think of it like this

A supermarket where every customer wants the same cake, and only one till sells it. That till has a queue out the door while the others wait for customers. Put the cake at every till and the queue disappears.

Where you’ll find it

  • Facebook: Copies its most-read items to many cache servers so no single one takes all the traffic, as its memcache paper describes.
  • Discord: Wrote about hot partitions in huge servers flooding one database node.
  • Redis: Can show which keys are hottest with redis-cli --hotkeys.

What to know first

Key. The name a piece of data is stored under, like user:taylor.

Partition. Splitting data across servers by key, so each server holds part of it. See Sharding and shard keys.

How it works

  1. Spot it. One server is busy while its neighbours are quiet. Count requests per key for a few seconds and the culprit usually stands out at once.
  2. Copy the hot key to more servers. Keep copies of that one key on several servers and spread reads across them. This is the fix in the animation.
  3. Keep a tiny cache in each app server. Each app server keeps the very hottest keys in its own memory for a second or two. Thousands of reads become one per server per second.
  4. Split hot writes. If the hot key is written a lot, like a like counter, split it into many sub-counters (likes:1 to likes:10), write to a random one, and add them up when reading.

An example

A cache has 10 servers sharing 1 million keys. Normally each takes about 10,000 requests a second.

A star posts a photo. Its key gets 200,000 requests a second, all on server 4. Server 4 maxes out and slows everything stored on it.

Copy that key to all 10 servers: each takes 20,000 more a second, which they can handle. The crowd splits, and nobody waits.

Further reading