Problem Statement
Design a solution to avoid cache stampede for a popular leaderboard endpoint.
Explanation
Maintain a single-flight lock per key so only one worker recomputes on expiry. Serve stale-while-revalidate for a short window so users get a recent snapshot while refresh happens. Add jitter to TTL to spread expiries and pre-warm at scheduled times. Keep a fast fallback like a smaller top-N precompute to degrade gracefully if both cache and origin are slow.
Code Solution
SolutionRead Only
if(nearExpiry && !lock.held(k)) spawnRefresh(k); return cachedOrStale(k);