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

Evitando avalanches de cache e estouros de requisições

Aprenda o que é uma avalanche de cache, por que ela sobrecarrega seu banco de dados quando uma chave popular expira e quais técnicas de bloqueio e atualização mantêm seu back-end seguro sob carga.

Evitando avalanches de cache e estouros de requisições é uma aula grátis de Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Redis Caching & Messaging (Pub/Sub, Streams), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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

Perguntas Frequentes

A aula “Evitando avalanches de cache e estouros de requisições” é grátis?

Sim — o texto completo de “Evitando avalanches de cache e estouros de requisições” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Redis Caching & Messaging (Pub/Sub, Streams), atualize para CoddyKit PRO. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

O que vou aprender em “Evitando avalanches de cache e estouros de requisições”?

Aprenda o que é uma avalanche de cache, por que ela sobrecarrega seu banco de dados quando uma chave popular expira e quais técnicas de bloqueio e atualização mantêm seu back-end seguro sob carga. Você pratica Redis Caching & Messaging (Pub/Sub, Streams) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Redis Caching & Messaging (Pub/Sub, Streams)?

Nenhuma experiência prévia é necessária. Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Evitando avalanches de cache e estouros de requisições”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Redis Caching & Messaging (Pub/Sub, Streams)?

Sim. Cada aula de Redis Caching & Messaging (Pub/Sub, Streams) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Por que usar cache? Introdução ao armazenamento em cache
  2. Implementação de padrões básicos de cache
  3. Remoção e expiração do cache
  4. Evitando avalanches de cache e estouros de requisições
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)