APPENDIX · P13 · REDIS · CACHE · SLIDE 15
← Back to Slide 15
P13. cache stampede: TTL variance and lock
# Веб-данные; пример cache miss и двух претендентов
DEL lesson03:profile:1042 lesson03:rebuild:profile:1042
GET lesson03:profile:1042
SET lesson03:rebuild:profile:1042 worker-1 NX PX 3000
SET lesson03:rebuild:profile:1042 worker-2 NX PX 3000
# приложение выбирает TTL случайно: здесь 312 = 300 + 12
SET lesson03:profile:1042 level=14 EX 312
GET lesson03:profile:1042
# после работы: release только по токену, атомарно
What the result should be
DEL: The number of deleted keys depends
on the previous run.
GET: (nil) — cache is empty
SET NX: OK, then (nil)
SET cache: OK; GET: "level=14"
312 was chosen as an example: the block itself
does not generate random variation on its own.
TTL Range
One Reformer
The rest
In the app, when recording, select a new TTL: 300 s + random 0–60; 312 is just an example here.
If a miss occurs, only the lock owner builds the cache. NX does not prevent the old result from being written after PX expires.
The rest either wait or submit an acceptable older version. The lock is released atomically per token; the version and record freshness check are required.
A miss on a popular key = thousands of identical queries in PostgreSQL. Limit the reorganization, not just the lifetime. Alternative: Update the key in advance, before it expires.