0Pricing
Caching Strategies: Redis + CDN + Edge Computing · Урок

Защита от эффекта «стада»

Узнайте, как возникает лавина запросов к кэшу при истечении срока действия популярных ключей и какие методы помогают её предотвратить: объединение запросов, блокировки, досрочное пересоздание и случайное распределение TTL.

«Защита от эффекта «стада»» — бесплатный урок Caching Strategies: Redis + CDN + Edge Computing на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Caching Strategies: Redis + CDN + Edge Computing, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The Thundering Herd Problem

When a hot cache key expires, every concurrent request misses at once and rushes the origin together. This cache stampede (or thundering herd) can overwhelm the database in an instant.

Why It Is Dangerous

A single popular item serving 10,000 requests/second normally hits the cache. The moment it expires, those 10,000 requests all hit the database simultaneously, often causing a spike that takes the origin down.

Cause: Synchronized Expiry

The root cause is many keys (or many requests on one key) expiring at the same moment. The fix strategies all aim to spread or serialize the resulting recomputation.

Fix 1: Request Coalescing

Let only the first request recompute the value; everyone else waits for that result. This is also called single-flight.

in_flight = {}

def get(key, compute):
    if key in in_flight:
        return 'waiting for in-flight result'
    in_flight[key] = True
    return compute()

print(get('hot', lambda: 'computed once'))

Fix 2: Mutex Lock

Use a distributed lock (e.g. a Redis key with NX) so only one process recomputes. Others briefly serve stale data or retry after a short wait.

lock = None

def acquire_lock(holder):
    global lock
    if lock is None:
        lock = holder
        return True
    return False

print(acquire_lock('worker-1'))
print(acquire_lock('worker-2'))

Fix 3: Jittered TTL

Add randomness to each entry's TTL so they do not all expire together. A base TTL plus random jitter spreads recomputation over time.

import random
base_ttl = 300
jitter = random.randint(0, 60)
print('TTL for this entry:', base_ttl + jitter, 'seconds')

Fix 4: Early Recomputation

Refresh a value before it expires. When an entry is close to its TTL, a background task (or a probabilistic check) recomputes it so it never actually goes cold for users.

Probabilistic Early Expiration

A clever trick: as a key nears expiry, give each request a small, growing probability of recomputing early. One lucky request refreshes the value while others still serve the cached copy.

import random
time_left = 5
beta = 1.0
should_refresh = random.random() < (1 / max(time_left, 1)) * beta
print('Refresh early?', should_refresh)

Fix 5: Serve Stale While Revalidating

Return the expired value immediately while a background job fetches fresh data. Users get a fast (slightly stale) response and the origin sees only one refresh request.

Combining Defenses

Real systems layer these: jittered TTLs to avoid synchronized expiry, plus coalescing or a lock to serialize the inevitable misses, plus stale-while-revalidate for the best user experience.

Watch for Cache Penetration Too

A related issue is penetration: requests for keys that never exist always miss and hit the origin. Cache negative results (or use a bloom filter) so missing keys are also absorbed.

Quick Check

Which technique prevents a cache stampede by ensuring only one request recomputes the value while the rest wait for that result?

Recap

You learned to defend against the thundering herd:

  • Stampedes happen when hot keys expire and many requests miss at once.
  • Coalescing and locks serialize recomputation.
  • Jittered TTLs and early recomputation spread the load.
  • Stale-while-revalidate keeps responses fast.

Combine these to keep your origin safe under load.

Часто задаваемые вопросы

Урок «Защита от эффекта «стада»» бесплатный?

Да — полный текст урока «Защита от эффекта «стада»» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Caching Strategies: Redis + CDN + Edge Computing, подпишись на CoddyKit PRO. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.

Чему я научусь в уроке «Защита от эффекта «стада»»?

Узнайте, как возникает лавина запросов к кэшу при истечении срока действия популярных ключей и какие методы помогают её предотвратить: объединение запросов, блокировки, досрочное пересоздание и случа… Ты практикуешь Caching Strategies: Redis + CDN + Edge Computing с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Caching Strategies: Redis + CDN + Edge Computing?

Предыдущий опыт не требуется. Caching Strategies: Redis + CDN + Edge Computing на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Защита от эффекта «стада»»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Caching Strategies: Redis + CDN + Edge Computing?

Да. Каждый урок Caching Strategies: Redis + CDN + Edge Computing включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Распространённые шаблоны кэширования
  2. Стратегии аннулирования кэша
  3. Политики вытеснения из кэша
  4. Защита от эффекта «стада»
← Назад к Caching Strategies: Redis + CDN + Edge Computing