Video in progress
A large share of traffic is hitting a single key (a hot key). What problem does this cause in a cluster, and what do you do?
In a cluster a key lives in one slot on one node, so adding nodes doesn't help: that node gets saturated on CPU and network. The solutions: a local cache inside the application, multiplying the key into several copies, and spreading reads across the replicas.
📖 Answer
A classic example: the "deal of the day" on the home page, or a popular product card. 40 thousand of 100 thousand RPS land on a single GET product:777. Even with 10 nodes in Redis Cluster, that key is on one node, which is at 100% CPU while the others sit idle.
How to detect it:
redis-cli --hotkeys(works only whenmaxmemory-policyis LFU);- an imbalance in CPU/ops between nodes;
- per-key metrics on the client side.
The solutions, which I usually try in this order:
- An L1 local cache: a 1-5 second cache with Caffeine. 99% of requests for the hot key never reach Redis. The cost is short staleness.
- Key replicas: you write one value as
product:777#0…product:777#7and pick a random suffix on read. Don't use a hash tag, because the goal is to land in different slots. - Reading from a replica:
ReadFrom.REPLICA_PREFERREDin Lettuce. But a replica can lag a bit.
String key = "product:777#" + ThreadLocalRandom.current().nextInt(8);
String json = redis.opsForValue().get(key);
On writes you have to update every copy, which is the awkward side of the second option. That's why in most cases an L1 cache is enough.
Sign up to mark studied questions and save your progress.