11 - Cache Eviction Policies & Invalidation Pitfalls

Executive Summary: RAM is finite and expensive, while database storage is virtually infinite and cheap. Cache eviction algorithms (LRU, LFU, FIFO) govern which data to discard when memory runs out. Meanwhile, cache invalidation failure modesβ€”Cache Stampede (Thundering Herd), Cache Penetration, and Cache Avalancheβ€”represent three of the most notorious causes of catastrophic site-wide outages in distributed systems.


🏒 Real-world case studies: how Facebook keeps memcache consistent and how Caffeine's W-TinyLFU picks what to keep, in REAL_WORLD_EXAMPLES.md.

⏱️ Prerequisites: What You Need to Know First

To get the most out of this module, make sure you understand:


πŸ§’ The 30-Second Version (ELI5)

Imagine you have a small desk where you keep books you are actively reading. Your desk can only hold 3 books, but you own thousands of books on shelves downstairs.


πŸ• Everyday Analogy

Imagine a busy coffee table in a doctor's waiting room that can hold exactly 4 magazines:

Concept Waiting Room Analogy Technical Reality in Distributed Systems
Cache Capacity Coffee table space (holds 4 magazines) Allocated RAM budget (e.g., 64 GB in Redis cluster)
Eviction (LRU) Throwing out the magazine no one picked up for 3 days Discarding the least recently accessed key in O(1) time
Cache Stampede The magazine with celebrity gossip is removed; 20 patients all shout at the nurse at once demanding she sprint to the store Hot key expires; 50,000 concurrent threads simultaneously hammer the database
Singleflight Mutex Nurse tells the crowd: "Only Bob will go get a copy; everyone else sit down and wait for Bob to return" Exactly one worker thread queries the DB and repopulates cache; others await the promise
Cache Penetration Pranksters repeatedly ask for a magazine that doesn't exist; the nurse walks downstairs every time Malicious/buggy requests query user_id=-99999; bypasses cache and exhausts DB IOPS
Bloom Filter A receptionist desk checklist that knows every magazine title ever printed; immediately denies fake titles Space-efficient probabilistic bit-set checking key existence before querying cache or DB
Cache Avalanche All 4 magazines have an expiration sticker for Friday 5:00 PM; at 5:01 PM the table is empty and everyone panics Millions of keys set with identical 2-hour TTL expire at the exact same second
TTL Jitter Staggering sticker dates: one expires at 4:45, one at 5:10, one at 5:30 Adding random noise (Β± 10%) to key TTLs so expirations are smoothed over time

🧩 The Problem It Solves

Without Proper Eviction & Invalidation Protections

With Modern Eviction & Fault-Tolerant Cache Architecture


πŸ–ΌοΈ Picture It: Architecture & Flow

High-Resolution Architecture Animation

Below is an animated trace of an O(1) Doubly Linked List LRU Cache evicting the oldest key upon capacity overflow, alongside the defensive architectures for Cache Stampede and Cache Avalanche:

Cache Eviction & Fault Modes Architecture


Invalidation Failure Modes & Mitigations Flowchart

flowchart TD
    subgraph Stampede["1. Cache Stampede (Thundering Herd)"]
        A[πŸ”₯ Hot Key Expires] --> B[100k Simultaneous Requests]
        B -->|Without Singleflight| C[πŸ’₯ 100k Concurrent DB Queries -> Outage]
        B -->|With Distributed Mutex| D[πŸ”’ Only 1 Thread Queries DB]
        D --> E[Populate Cache & Unblock Waiting 99,999 Requests]
    end

    subgraph Penetration["2. Cache Penetration (Attacker Scanning Fake IDs)"]
        F[Request for Non-Existent ID] --> G{Bloom Filter Check}
        G -->|Key Definitely Not in DB| H[πŸ›‘ Return 404 Immediately in 100ns]
        G -->|Key Might Exist| I[Query Cache -> Query DB -> Cache NULL Object]
    end

    subgraph Avalanche["3. Cache Avalanche (Synchronized Expirations)"]
        J[10 Million Keys Written at Midnight] --> K{TTL Configuration}
        K -->|Fixed TTL: 3600s| L[πŸ’₯ All 10M Keys Expire at 1:00:00 AM -> DB Crashes]
        K -->|Jittered TTL: 3600s +/- 300s| M[βœ… Keys Expire Smoothly Over 10 Minutes]
    end

    style Stampede fill:#161b22,stroke:#58a6ff,stroke-width:2px;
    style Penetration fill:#161b22,stroke:#3fb950,stroke-width:2px;
    style Avalanche fill:#161b22,stroke:#d29922,stroke-width:2px;

πŸ”’ Walk-Through with Real Numbers

Let's model an e-commerce platform during Black Friday to calculate the blast radius of cache failure modes:

Scenario: Black Friday Hot Deal Flash Sale

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Scenario A: Cache Stampede (No Mutex / Singleflight)                    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. Deal key expires at t = 0.000s                                      β”‚
β”‚ 2. In the next 40 ms (DB query time), 4,000 incoming requests miss.    β”‚
β”‚    (100,000 req/sec * 0.040 sec = 4,000 queries)                       β”‚
β”‚ 3. Database connection pool limit = 200 connections.                   β”‚
β”‚ 4. Result: 3,800 connection requests queued, 504 Gateway Timeouts,     β”‚
β”‚    DB CPU spikes to 100%, health checks fail, replica gets killed.     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Scenario B: Protected with Singleflight (Mutex Locking)                β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 1. Deal key expires at t = 0.000s                                      β”‚
β”‚ 2. Request #1 acquires distributed mutex lock (`lock:deal:blackfriday`) β”‚
β”‚ 3. Requests #2 through #4,000 fail to acquire lock -> sleep / subscribeβ”‚
β”‚ 4. Request #1 finishes DB query in 40 ms, writes key to Redis, releasesβ”‚
β”‚ 5. Requests #2 through #4,000 read fresh key directly from Redis (1 ms)β”‚
β”‚ 6. Total DB Queries issued: Exactly 1. Peak DB CPU delta: 0.04%.       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

βš™οΈ How It Works Under the Hood

1. The Classic Eviction Algorithms

LRU (Least Recently Used)

LFU (Least Frequently Used)

Advanced: W-TinyLFU (Window TinyLFU)


2. The Three Critical Invalidation Failures

Threat 1: Cache Stampede (Thundering Herd)

Ξ” Β· Ξ² Β· \ln(random()) > time_to_expire
 Background worker recalculates and refreshes the key *before* it actually expires when access probability is high.

Threat 2: Cache Penetration

Threat 3: Cache Avalanche

TTL = BaseTTL + random(-Delta, +Delta)

βš–οΈ Trade-Offs & Decision Matrix

Eviction Policy Lookup Time Space Overhead Best Suited For Major Vulnerability
LRU O(1) Medium (2 pointers per node) Temporal locality (recently read will be read again) Batch scans completely wipe hot working set
LFU O(1) High (frequency nodes + lists) Long-term stable access patterns Stale keys with old high counts resist eviction
FIFO O(1) Lowest (simple queue) Streaming data where age strictly predicts irrelevance Evicts heavily used keys simply because they are old
Random O(1) Zero extra metadata Memory-constrained systems (e.g., low-RAM edge routers) Suboptimal hit rates compared to LRU
W-TinyLFU O(1) Low (~8 bits per key) High-throughput, mixed read/write microservices Higher implementation complexity

🚫 Common Mistakes & Production Pitfalls

  1. Setting TTL Without Jitter in Batch Scripts:

    • Pitfall: A nightly sync job writes 5,000,000 customer records to Redis at 03:00 AM with TTL = 86400 (24 hours). At 03:00 AM the next night, all 5M keys expire simultaneously, killing the DB during early morning traffic.
    • Fix: Apply jitter: TTL = 86400 + random.randint(-3600, 3600).
  2. Unbounded Cache Memory:

    • Pitfall: Running Redis with maxmemory disabled on a 16 GB instance. Keys grow until Linux invokes OOM-Killer, violently terminating the redis-server process with SIGKILL.
    • Fix: Always define maxmemory 12gb and set an explicit policy like maxmemory-policy allkeys-lru or volatile-lru.
  3. Re-fetching on Stampede Instead of Singleflight:

    • Pitfall: Relying solely on caching without request coalescing. When a key expires, 5,000 identical SQL queries are fired in 50 ms.
    • Fix: Implement Go's singleflight or Python's mutex coalescer to share 1 execution among all concurrent callers.

πŸ’» Try It Yourself: Python Simulation

The companion simulation script demo.py implements:

  1. An O(1) Doubly Linked List LRU Cache with automatic eviction.
  2. A multi-threaded simulation of a Cache Stampede vs. a Mutex Singleflight Defense.
  3. A benchmark showing DB query count dropping from 50 concurrent calls down to 1 single query.

Run it locally in your terminal:

python demo.py

🌍 Where You'll See It in Production


🎯 Top Interview Questions & Deep Answers

Q1: "How do you implement an LRU Cache with O(1) operations for both get and put?"

Interviewer Goal: Testing data structure mastery, pointer manipulation, and memory complexity.

Model Answer: "To achieve O(1) time complexity for both get and put, we combine two data structures:

  1. A Hash Map that maps each key to its corresponding node pointer in memory.
  2. A Doubly Linked List where the head represents the Most Recently Used (MRU) item and the tail represents the Least Recently Used (LRU) item.

Q2: "What is the difference between Cache Stampede, Cache Penetration, and Cache Avalanche, and how do you protect against each?"

Interviewer Goal: Checking whether the candidate has lived through or prepared for real-world production cache outages.

Model Answer: "These are three distinct failure modes with different root causes:

  1. Cache Stampede (Thundering Herd):
    • Cause: A high-concurrency valid key expires. Thousands of simultaneous requests miss the cache and all run the same heavy database query.
    • Defense: Request coalescing / Singleflight Mutex (only 1 thread queries the DB; others wait for its completion) or probabilistic early refresh (XFetch algorithm refreshes the key before actual TTL expiry).
  2. Cache Penetration:
    • Cause: High volume of requests for keys that do not exist in either cache or database (e.g., malicious enumeration of id = -1 or random UUIDs).
    • Defense: Deploy a Bloom Filter in front of the cache to drop non-existent keys in O(k) bit-lookups, and cache NULL results with a short TTL (e.g., 30–60s) for missing items.
  3. Cache Avalanche:
    • Cause: Millions of cached keys are set with the identical TTL (e.g., 2 hours). When that duration elapses, a massive volume of keys drop out at the exact same second, overwhelming the database.
    • Defense: Add random jitter to expiration times (e.g., TTL = 7200 Β± random(0, 600)) to disperse expirations across time."

Q3: "Redis claims to support LRU, but why does its documentation say it uses an 'approximated LRU' instead of true LRU?"

Interviewer Goal: Testing deep knowledge of systems programming trade-offs and memory efficiency.

Model Answer: "In a standard LRU implementation, every entry requires a doubly linked list node containing two 64-bit pointers (prev and next), consuming at least 16 additional bytes of RAM per key. Across 100,000,000 keys, that overhead alone wastes 1.6 GB of expensive RAM purely for pointer bookkeeping. Furthermore, updating pointers on every single read operation degrades memory locality and creates lock contention.

To solve this, Redis uses Approximated LRU:


Q4: "In a write-heavy microservices architecture, how do you handle cache invalidation consistency without race conditions?"

Interviewer Goal: Checking distributed systems rigor regarding Cache-Aside vs. Write-Through race conditions.

Model Answer: "A classic race condition occurs in Cache-Aside when:

  1. Thread A reads from DB (returns version 1).
  2. Before Thread A can write version 1 to Cache, Thread B writes version 2 to DB and deletes the key from Cache.
  3. Thread A now writes stale version 1 into Cache. Stale data remains indefinitely until TTL expires.

To resolve this in production:

  1. Always Delete, Never Update: In Cache-Aside, mutating operations must delete/invalidate the cache key rather than updating it, avoiding serialization race order issues.
  2. Short TTL as a Safety Net: Always assign a reasonable TTL (e.g., 5–15 minutes) to ensure that any temporary inconsistency is self-healing.
  3. Change Data Capture (CDC): Use Debezium or DynamoDB Streams with a dedicated invalidator service that tails the database Write-Ahead Log (WAL) and publishes invalidation events to Redis, decoupling application workers from the cache invalidation contract."

Q5: "How does a Bloom Filter work, and what are its trade-offs when protecting against Cache Penetration?"

Interviewer Goal: Assessing understanding of probabilistic algorithms and space-efficiency tradeoffs.

Model Answer: "A Bloom Filter is a space-efficient probabilistic data structure used to test set membership:

Trade-offs:


βœ… Check Yourself: Flash Quiz

1. Why is LRU vulnerable to batch scanning scripts (e.g. daily backup or analytics queries)?
Because LRU only tracks recency. A batch script reading 1,000,000 old records touches each once, moving them to the front of the LRU list and evicting all high-frequency, highly active keys from RAM. Solutions like W-TinyLFU or 2Q (Two-Queue) defend against this by requiring an item to be accessed more than once before admission into the main cache.
2. If you set 1,000,000 keys with a 60-second TTL at 12:00:00 without jitter, what happens at 12:01:00?
You cause a Cache Avalanche. All 1,000,000 keys expire at the exact same millisecond. If traffic is active, millions of incoming queries miss the cache simultaneously and hit the database tier at once, likely exhausting connection pools and causing cascading service failures.
3. Can a Bloom Filter ever return a False Negative (telling you an item does not exist when it actually is in the database)?
No. Bloom filters have a mathematical guarantee of zero false negatives. If an item was added, all k of its hash bits were set to 1. If any hash bit is 0, the item was definitely never added.