The Real Fullstack

The Cache Stampede

The cache hit ratio is 99.9%. Why does the database spike to 100% CPU every minute?

シニアエンジニア9 分フローシミュレーターパフォーマンスラボ
redispostgresqljavanode

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Protect the database from the stampede on the hot key, then from the cold-start herd of 400 keys — without making users wait for recomputation.背景 · 学習目標 ▾

Larkspur's homepage feed is cached in Redis for 60 seconds and takes 800 ms to recompute. At 2,000 requests per second, every expiry triggers a burst of identical recomputations. After deployments, when the whole cache is cold, the database falls over completely.

ミッション: Protect the database from the stampede on the hot key, then from the cold-start herd of 400 keys — without making users wait for recomputation.

学習目標

  • Explain the thundering herd at cache expiry.
  • Use single-flight, stale-while-revalidate and early refresh.
  • Spread expirations with TTL jitter.
シミュレーションシミュレーション値
Feed APIRedisPostgreSQL
シミュレーションを実行
async function getFeed(key: string): Promise<Feed> {  const hit = await redis.get(key);  if (hit) {    const { value, softExpiry } = JSON.parse(hit);    if (Date.now() > softExpiry) refreshInBackground(key);   // stale-while-revalidate (single flight via SET NX lock)    return value;  }  return singleFlight(key, async () => {                      // one recomputation per key per instance    const value = await db.expensiveFeedQuery();    const ttl = 60 + Math.floor(Math.random() * 30);         // jitter: keys don't all expire together    await redis.set(key, JSON.stringify({ value, softExpiry: Date.now() + (ttl - 10) * 1000 }), 'EX', ttl);    return value;  });}

簡略化

Burst size = request rate × recomputation time. Real systems see partial overlaps and multiple cache nodes. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

関連する課題

参考資料