Caching Strategies: Redis + CDN + Edge Computing · Lekcja

Ochrona przed efektem stampeding herd

Poznaj mechanizm lawiny żądań do cache, który występuje po wygaśnięciu popularnych kluczy, oraz techniki zapobiegania mu: łączenie żądań, blokady, wcześniejsze przeliczanie i TTL z losowym rozrzutem.

Lekcja 4 z 413 kroki

Ochrona przed efektem stampeding herd to bezpłatna lekcja Caching Strategies: Redis + CDN + Edge Computing na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Caching Strategies: Redis + CDN + Edge Computing, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Caching Strategies: Redis + CDN + Edge Computing zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Caching Strategies: Redis + CDN + Edge Computing dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Ochrona przed efektem stampeding herd” jest bezpłatna?

Tak — pełny tekst „Ochrona przed efektem stampeding herd” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Caching Strategies: Redis + CDN + Edge Computing, przejdź na CoddyKit PRO. Kurs Caching Strategies: Redis + CDN + Edge Computing zawiera 4 lekcji w sumie.

Co nauczysz się w „Ochrona przed efektem stampeding herd”?

Poznaj mechanizm lawiny żądań do cache, który występuje po wygaśnięciu popularnych kluczy, oraz techniki zapobiegania mu: łączenie żądań, blokady, wcześniejsze przeliczanie i TTL z losowym rozrzutem. Ćwiczysz Caching Strategies: Redis + CDN + Edge Computing z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Caching Strategies: Redis + CDN + Edge Computing?

Nie wymagamy żadnego doświadczenia. Caching Strategies: Redis + CDN + Edge Computing w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Ochrona przed efektem stampeding herd”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Caching Strategies: Redis + CDN + Edge Computing?

Tak. Każda lekcja Caching Strategies: Redis + CDN + Edge Computing zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Typowe wzorce buforowania
  2. Strategie unieważniania pamięci podręcznej
  3. Zasady eksmisji z pamięci podręcznej
  4. Ochrona przed efektem stampeding herd
← Powrót do Caching Strategies: Redis + CDN + Edge Computing