0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Lezione

Prevenire cache stampede e thundering herd

Impari che cos'è una cache stampede, perché sovraccarica il database quando scade una chiave molto richiesta e quali tecniche di locking e refresh mantengono sicuro il backend sotto carico.

Prevenire cache stampede e thundering herd è una lezione Redis Caching & Messaging (Pub/Sub, Streams) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Redis Caching & Messaging (Pub/Sub, Streams), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

What Is a Cache Stampede?

A cache stampede (or thundering herd) happens when a popular cached key expires and many requests miss the cache at the same moment. They all rush to the database to rebuild the value, overwhelming it.

Why It Is So Dangerous

Under high traffic, hundreds or thousands of concurrent misses can hit the database in milliseconds. The backend that normally serves zero load for that key suddenly takes the full firehose, causing latency spikes or outages.

The Naive Cache-Aside Flow

The basic pattern reads the cache, and on a miss queries the DB and stores the result. Every concurrent miss runs this DB query — that is the vulnerability.

Solution 1: A Recompute Lock

Let only the first missing request rebuild the value while others wait or serve stale. Redis SET NX grants a short-lived lock to exactly one client.

SET lock:product:42 "1" NX EX 10

How the Lock Flow Works

On a miss:

  • Try to acquire the lock with SET NX
  • If you got it, query the DB and repopulate the cache
  • If not, briefly wait and re-read the cache

Only one DB query runs per expiry.

Solution 2: Stale-While-Revalidate

Store the value with a logical expiry earlier than its physical TTL. When the logical time passes, serve the stale value immediately and refresh it in the background, so users never wait on a miss.

Solution 3: Early Probabilistic Expiry

Each request, with a small growing probability as expiry nears, voluntarily refreshes the key before it dies. This spreads recomputation across time so the herd never forms.

Adding Jitter to TTLs

If many keys are written together (e.g. on deploy) they expire together, causing a synchronized stampede. Add random jitter to each TTL so expiries spread out.

SET product:42 "..." EX 305
SET product:43 "..." EX 318

Releasing the Lock Safely

After rebuilding, delete the lock. Give it a short TTL too, so a crashed worker does not hold it forever and block refreshes.

DEL lock:product:42

Choosing a Strategy

Guidelines:

  • Lock: simplest, briefly delays some requests
  • Stale-while-revalidate: best UX, needs background refresh
  • Probabilistic + jitter: smooths load, no waiting

Combine them for very hot keys.

Negative Caching

A related danger is the cache penetration miss: many requests for a key that does not exist in the DB always miss the cache and hammer the backend. Cache the not-found result briefly too, so repeated lookups are absorbed.

SET product:9999 "__NULL__" EX 30

Quick Check

Test your stampede-prevention knowledge.

Recap

You learned to stop cache stampedes:

  • A stampede floods the DB when a hot key expires
  • A SET NX recompute lock limits rebuilds to one client
  • Stale-while-revalidate serves old data while refreshing
  • Probabilistic early expiry spreads recomputation out
  • TTL jitter prevents synchronized mass expiry

Domande Frequenti

La lezione «Prevenire cache stampede e thundering herd» è gratuita?

Sì — il testo completo di «Prevenire cache stampede e thundering herd» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Redis Caching & Messaging (Pub/Sub, Streams), passa a CoddyKit PRO. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Cosa imparerò in «Prevenire cache stampede e thundering herd»?

Impari che cos'è una cache stampede, perché sovraccarica il database quando scade una chiave molto richiesta e quali tecniche di locking e refresh mantengono sicuro il backend sotto carico. Eserciti Redis Caching & Messaging (Pub/Sub, Streams) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Redis Caching & Messaging (Pub/Sub, Streams)?

Non è richiesta alcuna esperienza precedente. Redis Caching & Messaging (Pub/Sub, Streams) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Prevenire cache stampede e thundering herd»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Redis Caching & Messaging (Pub/Sub, Streams)?

Sì. Ogni lezione Redis Caching & Messaging (Pub/Sub, Streams) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Perché usare una cache? Introduzione al caching
  2. Implementare pattern di caching di base
  3. Rimozione e scadenza degli elementi dalla cache
  4. Prevenire cache stampede e thundering herd
← Torna a Redis Caching & Messaging (Pub/Sub, Streams)