System Design Basics for Backend Developers · Lekcja

Zasady usuwania elementów z cache

Poznaj sposoby decydowania przez cache, co zachować, a co odrzucić po zapełnieniu pamięci, w tym LRU, LFU, FIFO i TTL oraz kompromisy między nimi.

Lekcja 4 z 413 kroki

Zasady usuwania elementów z cache to bezpłatna lekcja System Design Basics for Backend Developers 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 System Design Basics for Backend Developers, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.

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

Why Eviction Is Necessary

A cache is fast because it lives in limited memory. When it fills up, it must evict something to make room for new data. The eviction policy decides what to drop.

A good policy keeps the data most likely to be reused.

Hit Rate Is the Goal

The metric that matters is the hit rate: the fraction of requests served from cache. A better eviction policy raises the hit rate, which means fewer slow trips to the database or origin.

hits = 850
misses = 150
hit_rate = hits / (hits + misses)
print('hit rate:', hit_rate)

FIFO

FIFO (First In, First Out) evicts the oldest inserted item regardless of usage. It is simple but ignores access patterns, so a frequently used old item can be wrongly evicted.

LRU: Least Recently Used

LRU evicts the item that has not been accessed for the longest time. It assumes recently used data will be used again soon — true for most workloads, which is why LRU is the default in many caches.

Implementing LRU

A classic LRU uses an ordered map. On access, move the key to the most-recent end; when full, evict from the least-recent end.

from collections import OrderedDict
class LRU:
    def __init__(self, cap):
        self.cap = cap
        self.d = OrderedDict()
    def get(self, k):
        if k in self.d:
            self.d.move_to_end(k)
            return self.d[k]
    def put(self, k, v):
        self.d[k] = v
        self.d.move_to_end(k)
        if len(self.d) > self.cap:
            self.d.popitem(last=False)

c = LRU(2)
c.put('a', 1); c.put('b', 2); c.get('a'); c.put('c', 3)
print(list(c.d.keys()))

LFU: Least Frequently Used

LFU evicts the item accessed the fewest times. It favors long-term popular items over recent bursts. The downside: a once-popular item can linger long after it stops being useful.

TTL-Based Expiration

A TTL (time to live) expires items after a fixed duration regardless of memory pressure. It bounds staleness and is often combined with LRU: TTL controls freshness, LRU controls memory.

SET session:42 "..." EX 3600
# expires in 3600 seconds

Random and Allkeys Variants

Some caches offer random eviction (cheap, surprisingly decent) and scope variants: evict only keys with a TTL set, or evict from all keys. Redis exposes policies like allkeys-lru and volatile-ttl.

Thundering Herd on Eviction

When a hot key is evicted or expires, many clients may simultaneously rebuild it — a thundering herd that hammers the origin. Mitigate with request coalescing (single-flight) or slightly randomized TTLs to spread out expirations.

Choosing a Policy

Match the policy to the workload:

  • Recency-driven traffic: LRU
  • Stable popularity: LFU
  • Freshness-critical data: TTL
  • Uniform access: random is fine and cheap

Eviction in a CDN

CDNs apply the same ideas at the edge. Each edge node has finite storage and evicts (often LRU) plus honors Cache-Control: max-age as a TTL. Understanding eviction explains why a cold edge node has a low initial hit rate.

Quick Check

Test your understanding of eviction policies.

Recap

You learned how caches manage limited memory:

  • Eviction policies aim to maximize hit rate
  • FIFO, LRU, LFU, TTL, and random each suit different patterns
  • Thundering herds need coalescing or jittered TTLs
  • CDNs apply the same eviction logic at the edge
Bezpłatny start

Ucz się System Design Basics for Backend Developers 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 „Zasady usuwania elementów z cache” jest bezpłatna?

Tak — pełny tekst „Zasady usuwania elementów z cache” 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 System Design Basics for Backend Developers, przejdź na CoddyKit PRO. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.

Co nauczysz się w „Zasady usuwania elementów z cache”?

Poznaj sposoby decydowania przez cache, co zachować, a co odrzucić po zapełnieniu pamięci, w tym LRU, LFU, FIFO i TTL oraz kompromisy między nimi. Ćwiczysz System Design Basics for Backend Developers 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ąć System Design Basics for Backend Developers?

Nie wymagamy żadnego doświadczenia. System Design Basics for Backend Developers 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 „Zasady usuwania elementów z cache”?

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 System Design Basics for Backend Developers?

Tak. Każda lekcja System Design Basics for Backend Developers 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. Wzorce unieważniania pamięci podręcznej
  2. Integracja z CDN i cache’owanie na brzegu sieci
  3. Rozproszone cache’owanie z Redis
  4. Zasady usuwania elementów z cache
← Powrót do System Design Basics for Backend Developers