Menu

Cache Stampedes in Node.js: Request Coalescing, Redis Locks, and Stale-While-Revalidate for Hot Keys — Field Notes
📰

Cache Stampedes in Node.js: Request Coalescing, Redis Locks, and Stale-While-Revalidate for Hot Keys — Field Notes

DEV Community: redis·Ahmed Mahmoud·7 days ago
#jPQglwhF
#devtoredis#devto#dev#cache#redis
Long article (2578 words) — no AI summary yet.
Reading 0:00
15s threshold

Headline: A cache stampede happens when a popular cache key expires and every concurrent request misses at the same moment and recomputes the same value against the database. In Node.js I prevent it in layers: coalesce identical in-flight loads inside each process, take a short Redis SET NX PX lock so only one instance recomputes, and keep a soft expiry so readers get the stale value while a single worker refreshes it in the background.

The cache-aside code I used to write looked correct and passed every test: read from Redis, query Postgres on a miss, write the result back with a TTL. It only failed under real concurrency, when an expensive key — a homepage feed, a pricing table, a dashboard aggregate — expired while many requests were reading it.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.