System Design Basics for Backend Developers · Lección

Políticas de expulsión de caché

Explore cómo las cachés deciden qué conservar y qué descartar cuando la memoria está llena, incluyendo LRU, LFU, FIFO y TTL, así como sus ventajas y desventajas.

Lección 4 de 413 pasos

Políticas de expulsión de caché es una lección gratuita de System Design Basics for Backend Developers en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de System Design Basics for Backend Developers, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de System Design Basics for Backend Developers incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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
Gratis para empezar

Aprende System Design Basics for Backend Developers con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Políticas de expulsión de caché» es gratis?

Sí — el texto completo de «Políticas de expulsión de caché» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de System Design Basics for Backend Developers, actualiza a CoddyKit PRO. El curso de System Design Basics for Backend Developers incluye 4 lecciones en total.

¿Qué aprenderé en «Políticas de expulsión de caché»?

Explore cómo las cachés deciden qué conservar y qué descartar cuando la memoria está llena, incluyendo LRU, LFU, FIFO y TTL, así como sus ventajas y desventajas. Practicas System Design Basics for Backend Developers con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar System Design Basics for Backend Developers?

No se requiere experiencia previa. System Design Basics for Backend Developers en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Políticas de expulsión de caché»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de System Design Basics for Backend Developers?

Sí. Cada lección de System Design Basics for Backend Developers incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Patrones de invalidación de caché
  2. Integración con CDN y caché en el edge
  3. Caché distribuida con Redis
  4. Políticas de expulsión de caché
← Volver a System Design Basics for Backend Developers