›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Caching in Depth

Caching in Depth, Part 1: Every Caching Strategy, and When to Use Which

October 18, 2026 · 51 min read

Caching, Software Architecture, Design Patterns, Performance, C#, Python, Redis

"Add a cache" is one of the most common fixes in software, and one of the vaguest. A cache is not one thing. It's a set of decisions: who fills it, when writes reach the database, when entries die, who tells the cache that the data changed, and what happens when a thousand requests miss at once. Each decision has a named strategy, and each strategy is right for some data and wrong for other data.

This is Part 1 of Caching in Depth, and it's about those strategies: the how. Part 2 is about the where: browser HTTP caches, CDNs, service workers, client data caches like TanStack Query, in-process versus distributed caches like IMemoryCache, HybridCache and Redis, and response caching. If your question is "should this live in Redis or in memory?", that's Part 2. If it's "should writes go to the cache first?", read on.

Every example below runs. Each one uses an in-memory stand-in for a slow database with a call counter, and a fake clock where timing matters, so the output shows exactly which reads hit, which missed, and how many times the database was called. I ran each C# file as a .NET 10 file-based app (dotnet run file.cs) and each Python file with Python 3.12. The output under each pair is the real output, and both languages print the same thing unless I say otherwise.

Here's the whole post on one page:

QuestionStrategiesSection
Who loads data into the cache?Cache-aside, read-through, refresh-aheadRead strategies
When does a write reach the database?Write-through, write-behind, write-aroundWrite strategies
When does an entry die?Absolute TTL, sliding TTL, LRU, LFU, FIFO, size limitsExpiry and eviction
How does the cache learn the data changed?TTL, delete on write, versioned and tagged keys, eventsInvalidation
What goes wrong under load?Stampede, penetration, avalanche, hot keys, stale dataFailure modes
Is caching a function the same thing?Memoization vs data cachingMemoization

Read strategies: who fills the cache?

All three read strategies return a cached value when there is one. They differ in who loads the data on a miss and whether anyone loads it before a miss happens.

Cache-aside (lazy loading)

What it is: the application checks the cache. On a miss, the application reads the database, writes the result into the cache, and returns it. The cache is a dumb key-value store; all the logic lives in your code.

I covered cache-aside in detail, including its GoF ancestor and a stampede-safe version, in the cloud structure patterns post. The short version: it's the default for a reason. It works with any cache and any database, it only caches data someone actually asked for, and if the cache goes down your app still works (slowly). The costs are that the first read of every key is slow, and nothing tells the cache when the database changes, so you need a TTL or explicit invalidation.

Use it when: you want one cache in front of an ordinary database and you're not sure which strategy you need. That covers most apps.

Read-through

What it is: the same flow as cache-aside, but the cache does the loading. You give the cache a loader function once, and from then on the caller only ever asks the cache. The caller can't tell a hit from a miss.

A use case: a product catalog where a dozen services read products. Put the loader inside a read-through cache and none of them can forget to populate it or populate it differently.

Use it when: many call sites read the same data and you want one place that owns how it's loaded. In .NET, HybridCache.GetOrCreateAsync and IMemoryCache.GetOrCreate are read-through APIs: you pass the key and the loader together.

Avoid it when: the loader needs context the cache doesn't have (the current user's permissions, a transaction), or your cache product can't run your code. Redis can't call your database for you, so with Redis "read-through" means a library wrapper in your app, not a Redis feature.

Refresh-ahead

What it is: a read-through cache that reloads an entry before it expires. When a read lands late in an entry's life (say, after 75% of its TTL), the cache returns the current value immediately and schedules a background reload. If the key is busy, nobody ever waits for a miss.

A use case: the home page's "top products" query. It's expensive, every visitor needs it, and a few seconds of staleness is fine. You never want a visitor to be the one who waits for it.

Use it when: a small number of hot keys carry most of the traffic, and the reload is slow enough that users notice a miss.

Avoid it when: keys are read rarely. You'll reload data nobody reads, which is extra database load for nothing. And refresh-ahead only helps keys that are read near their expiry; a cold key still misses.

Here are all three over the same fake database, with a 60-second TTL and reads at 0, 10, 50 and 70 seconds:

// Three read strategies over the same fake database, driven by a fake clock.
var clock = new FakeClock();
var db = new FakeDb(new() { ["p1"] = "Widget $10" });
const double Ttl = 60;

// 1. Cache-aside: the application checks the cache, reads the DB on a miss, then fills the cache.
var asideCache = new Dictionary<string, (string Value, double ExpiresAt)>();
string GetCacheAside(string key)
{
    if (asideCache.TryGetValue(key, out var e) && e.ExpiresAt > clock.Now) return e.Value;
    var value = db.Read(key);
    asideCache[key] = (value, clock.Now + Ttl);
    return value;
}

// 2. Read-through: the cache owns the loader. The caller only ever talks to the cache.
var readThrough = new ReadThroughCache(db.Read, clock, Ttl);

// 3. Refresh-ahead: like read-through, but a read late in an entry's life schedules a reload.
var refreshAhead = new RefreshAheadCache(db.Read, clock, Ttl, refreshAfter: 0.75);

foreach (var (name, get) in new (string, Func<string, string>)[]
         { ("cache-aside", GetCacheAside), ("read-through", readThrough.Get), ("refresh-ahead", refreshAhead.Get) })
{
    clock.Now = 0; db.Reads = 0;
    Console.WriteLine($"-- {name} (ttl {Ttl}s) --");
    foreach (var t in new double[] { 0, 10, 50, 70 })
    {
        clock.Now = t;
        var before = db.Reads;
        var value = get("p1");
        Console.WriteLine($"t={t,3}s  get p1 -> {value}  {(db.Reads > before ? "MISS" : "hit ")}  db reads={db.Reads}");
        if (name == "refresh-ahead" && refreshAhead.RunBackgroundRefreshes() is var n and > 0)
            Console.WriteLine($"         background refresh ran ({n})  db reads={db.Reads}");
    }
}

class FakeClock { public double Now; }

class FakeDb(Dictionary<string, string> rows)
{
    public int Reads;
    public string Read(string key) { Reads++; return rows[key]; }
}

class ReadThroughCache(Func<string, string> loader, FakeClock clock, double ttl)
{
    private readonly Dictionary<string, (string Value, double ExpiresAt)> _items = new();

    public string Get(string key)
    {
        if (_items.TryGetValue(key, out var e) && e.ExpiresAt > clock.Now) return e.Value;
        var value = loader(key);               // the cache calls the database, not the app
        _items[key] = (value, clock.Now + ttl);
        return value;
    }
}

class RefreshAheadCache(Func<string, string> loader, FakeClock clock, double ttl, double refreshAfter)
{
    private readonly Dictionary<string, (string Value, double LoadedAt)> _items = new();
    private readonly Queue<string> _pending = new();
    private readonly HashSet<string> _scheduled = new();

    public string Get(string key)
    {
        if (_items.TryGetValue(key, out var e) && clock.Now - e.LoadedAt < ttl)
        {
            // Still fresh, but old enough that we reload it before anyone has to wait.
            if (clock.Now - e.LoadedAt >= ttl * refreshAfter && _scheduled.Add(key))
                _pending.Enqueue(key);
            return e.Value;
        }
        var value = loader(key);
        _items[key] = (value, clock.Now);
        return value;
    }

    // In a real app this runs on a background worker. Here we call it explicitly so output is deterministic.
    public int RunBackgroundRefreshes()
    {
        var count = 0;
        while (_pending.TryDequeue(out var key))
        {
            _items[key] = (loader(key), clock.Now);
            _scheduled.Remove(key);
            count++;
        }
        return count;
    }
}
# Three read strategies over the same fake database, driven by a fake clock.
TTL = 60


class FakeClock:
    now = 0.0


class FakeDb:
    def __init__(self, rows):
        self.rows, self.reads = rows, 0

    def read(self, key):
        self.reads += 1
        return self.rows[key]


clock, db = FakeClock(), FakeDb({"p1": "Widget $10"})

# 1. Cache-aside: the application checks the cache, reads the DB on a miss, then fills the cache.
aside_cache: dict[str, tuple[str, float]] = {}


def get_cache_aside(key):
    hit = aside_cache.get(key)
    if hit and hit[1] > clock.now:
        return hit[0]
    value = db.read(key)
    aside_cache[key] = (value, clock.now + TTL)
    return value


# 2. Read-through: the cache owns the loader. The caller only ever talks to the cache.
class ReadThroughCache:
    def __init__(self, loader, ttl):
        self.loader, self.ttl, self.items = loader, ttl, {}

    def get(self, key):
        hit = self.items.get(key)
        if hit and hit[1] > clock.now:
            return hit[0]
        value = self.loader(key)  # the cache calls the database, not the app
        self.items[key] = (value, clock.now + self.ttl)
        return value


# 3. Refresh-ahead: a read late in an entry's life schedules a reload before it expires.
class RefreshAheadCache:
    def __init__(self, loader, ttl, refresh_after=0.75):
        self.loader, self.ttl, self.refresh_after = loader, ttl, refresh_after
        self.items: dict[str, tuple[str, float]] = {}  # key -> (value, loaded_at)
        self.pending: list[str] = []

    def get(self, key):
        hit = self.items.get(key)
        if hit and clock.now - hit[1] < self.ttl:
            age = clock.now - hit[1]
            if age >= self.ttl * self.refresh_after and key not in self.pending:
                self.pending.append(key)
            return hit[0]
        value = self.loader(key)
        self.items[key] = (value, clock.now)
        return value

    def run_background_refreshes(self):
        # A background worker in real life; called explicitly here for deterministic output.
        count = len(self.pending)
        for key in self.pending:
            self.items[key] = (self.loader(key), clock.now)
        self.pending.clear()
        return count


read_through = ReadThroughCache(db.read, TTL)
refresh_ahead = RefreshAheadCache(db.read, TTL)

for name, get in [("cache-aside", get_cache_aside),
                  ("read-through", read_through.get),
                  ("refresh-ahead", refresh_ahead.get)]:
    db.reads = 0
    print(f"-- {name} (ttl {TTL}s) --")
    for t in (0, 10, 50, 70):
        clock.now = t
        before = db.reads
        value = get("p1")
        status = "MISS" if db.reads > before else "hit "
        print(f"t={t:>3}s  get p1 -> {value}  {status}  db reads={db.reads}")
        if name == "refresh-ahead" and (n := refresh_ahead.run_background_refreshes()):
            print(f"         background refresh ran ({n})  db reads={db.reads}")

Output:

-- cache-aside (ttl 60s) --
t=  0s  get p1 -> Widget $10  MISS  db reads=1
t= 10s  get p1 -> Widget $10  hit   db reads=1
t= 50s  get p1 -> Widget $10  hit   db reads=1
t= 70s  get p1 -> Widget $10  MISS  db reads=2
-- read-through (ttl 60s) --
t=  0s  get p1 -> Widget $10  MISS  db reads=1
t= 10s  get p1 -> Widget $10  hit   db reads=1
t= 50s  get p1 -> Widget $10  hit   db reads=1
t= 70s  get p1 -> Widget $10  MISS  db reads=2
-- refresh-ahead (ttl 60s) --
t=  0s  get p1 -> Widget $10  MISS  db reads=1
t= 10s  get p1 -> Widget $10  hit   db reads=1
t= 50s  get p1 -> Widget $10  hit   db reads=1
         background refresh ran (1)  db reads=2
t= 70s  get p1 -> Widget $10  hit   db reads=2

Cache-aside and read-through give identical numbers. That's the point: they're the same algorithm, and the difference is only who owns it. Refresh-ahead is the one that changes behavior. At t=50 the entry is past 75% of its life, so the read schedules a reload, and at t=70, when the other two miss, refresh-ahead still hits.

Write strategies: when does the database find out?

Reads are the reason you cache. Writes are where caches cause bugs. Every write strategy answers one question: when the app changes data, does it update the cache, the database, or both, and in what order?

Write-through

What it is: every write goes to the database and the cache together, in the same request. The caller waits for both. The next read is a guaranteed hit with the new value.

A use case: a user profile. When someone changes their display name, the very next page should show it, on every server.

Use it when: data is read soon after it's written and must be fresh. Pair it with cache-aside for reads, so keys that were never written still get loaded.

Avoid it when: most written data is never read. You'll fill the cache with entries nobody wants. One detail: write the database first, then the cache. If the database write fails, the cache never holds a value that doesn't exist.

Write-behind (write-back)

What it is: the write goes to the cache only, and the caller returns immediately. A background process flushes changed ("dirty") keys to the database later, in batches. Several writes to the same key collapse into one database write.

A use case: view counters, "last seen" timestamps, game scores, rate-limit counters. High-volume writes where the latest value is what matters.

Use it when: the write rate is more than the database can absorb, and you can accept losing the last few seconds of writes.

Avoid it when: losing a write is unacceptable: orders, payments, anything a user would notice going missing. If the cache node dies before a flush, those writes are gone. A replicated cache with persistence narrows the window, but it doesn't close it.

Write-around

What it is: writes go to the database only, and the cache entry is removed (or never created). The data enters the cache later, through cache-aside, only if someone reads it.

A use case: audit logs, uploaded documents, bulk imports, order history. Data that's written constantly but read rarely, or long after it was written.

Use it when: you don't want writes to push useful entries out of the cache. This is what most cache-aside apps actually do on writes ("update the database, delete the key").

Avoid it when: data is read right after it's written. Every such read is a miss.

Here are all three, with simulated costs of 1 ms for a cache operation and 20 ms for a database operation:

// Write-through, write-around and write-behind over a fake cache and a fake database.
// Simulated costs: a cache operation takes 1 ms, a database operation takes 20 ms.
var s = new Store();
s.Db["p1"] = "v1";

Console.WriteLine("-- write-through: cache and DB updated together --");
Console.WriteLine($"write p1=v2   caller waited {s.WriteThrough("p1", "v2")} ms  db writes={s.DbWrites}");
Console.WriteLine($"read  p1 -> {s.Read("p1")}");

Console.WriteLine("-- write-around: DB only, cache entry dropped --");
Console.WriteLine($"write p1=v3   caller waited {s.WriteAround("p1", "v3")} ms  db writes={s.DbWrites}");
Console.WriteLine($"read  p1 -> {s.Read("p1")}");
Console.WriteLine($"read  p1 -> {s.Read("p1")}");

Console.WriteLine("-- write-behind: cache now, DB later --");
for (var views = 1; views <= 3; views++)
    Console.WriteLine($"write views={views}  caller waited {s.WriteBehind("views:home", $"{views}")} ms  db writes={s.DbWrites}");
Console.WriteLine($"flush: {s.Flush()} DB write(s) for 3 cache writes  db writes={s.DbWrites}  db views={s.Db["views:home"]}");
s.WriteBehind("views:home", "4");
s.Crash();
Console.WriteLine($"wrote views=4, then the cache node crashed before the flush. db views={s.Db["views:home"]}");

class Store
{
    public readonly Dictionary<string, string> Db = new();
    private Dictionary<string, string> _cache = new();
    private readonly HashSet<string> _dirty = new();   // keys written to cache but not yet to the DB
    public int DbWrites;
    const int CacheMs = 1, DbMs = 20;

    public int WriteThrough(string key, string value)
    {
        Db[key] = value; DbWrites++;          // DB first: if it fails, the cache never sees the bad value
        _cache[key] = value;
        return DbMs + CacheMs;
    }

    public int WriteAround(string key, string value)
    {
        Db[key] = value; DbWrites++;
        _cache.Remove(key);                   // the next read will load it, if anyone reads it
        return DbMs + CacheMs;
    }

    public int WriteBehind(string key, string value)
    {
        _cache[key] = value;
        _dirty.Add(key);                      // a later flush writes it to the DB
        return CacheMs;
    }

    public int Flush()
    {
        foreach (var key in _dirty) { Db[key] = _cache[key]; DbWrites++; }
        var flushed = _dirty.Count;
        _dirty.Clear();
        return flushed;
    }

    public void Crash() { _cache = new(); _dirty.Clear(); }

    public string Read(string key)
    {
        if (_cache.TryGetValue(key, out var v)) return $"{v} (cache hit, {CacheMs} ms)";
        _cache[key] = Db[key];
        return $"{Db[key]} (cache miss, read DB, {DbMs + CacheMs} ms)";
    }
}
# Write-through, write-around and write-behind over a fake cache and a fake database.
# Simulated costs: a cache operation takes 1 ms, a database operation takes 20 ms.
CACHE_MS, DB_MS = 1, 20


class Store:
    def __init__(self):
        self.db: dict[str, str] = {}
        self.cache: dict[str, str] = {}
        self.dirty: set[str] = set()  # written to cache, not yet to the DB
        self.db_writes = 0

    def write_through(self, key, value):
        self.db[key] = value  # DB first: if it fails, the cache never sees the bad value
        self.db_writes += 1
        self.cache[key] = value
        return DB_MS + CACHE_MS

    def write_around(self, key, value):
        self.db[key] = value
        self.db_writes += 1
        self.cache.pop(key, None)  # the next read loads it, if anyone reads it
        return DB_MS + CACHE_MS

    def write_behind(self, key, value):
        self.cache[key] = value
        self.dirty.add(key)  # a later flush writes it to the DB
        return CACHE_MS

    def flush(self):
        for key in self.dirty:
            self.db[key] = self.cache[key]
            self.db_writes += 1
        flushed = len(self.dirty)
        self.dirty.clear()
        return flushed

    def crash(self):
        self.cache, self.dirty = {}, set()

    def read(self, key):
        if key in self.cache:
            return f"{self.cache[key]} (cache hit, {CACHE_MS} ms)"
        self.cache[key] = self.db[key]
        return f"{self.db[key]} (cache miss, read DB, {DB_MS + CACHE_MS} ms)"


s = Store()
s.db["p1"] = "v1"

print("-- write-through: cache and DB updated together --")
print(f"write p1=v2   caller waited {s.write_through('p1', 'v2')} ms  db writes={s.db_writes}")
print(f"read  p1 -> {s.read('p1')}")

print("-- write-around: DB only, cache entry dropped --")
print(f"write p1=v3   caller waited {s.write_around('p1', 'v3')} ms  db writes={s.db_writes}")
print(f"read  p1 -> {s.read('p1')}")
print(f"read  p1 -> {s.read('p1')}")

print("-- write-behind: cache now, DB later --")
for views in range(1, 4):
    print(f"write views={views}  caller waited {s.write_behind('views:home', str(views))} ms  db writes={s.db_writes}")
print(f"flush: {s.flush()} DB write(s) for 3 cache writes  db writes={s.db_writes}  db views={s.db['views:home']}")
s.write_behind("views:home", "4")
s.crash()
print(f"wrote views=4, then the cache node crashed before the flush. db views={s.db['views:home']}")

Output:

-- write-through: cache and DB updated together --
write p1=v2   caller waited 21 ms  db writes=1
read  p1 -> v2 (cache hit, 1 ms)
-- write-around: DB only, cache entry dropped --
write p1=v3   caller waited 21 ms  db writes=2
read  p1 -> v3 (cache miss, read DB, 21 ms)
read  p1 -> v3 (cache hit, 1 ms)
-- write-behind: cache now, DB later --
write views=1  caller waited 1 ms  db writes=2
write views=2  caller waited 1 ms  db writes=2
write views=3  caller waited 1 ms  db writes=2
flush: 1 DB write(s) for 3 cache writes  db writes=3  db views=3
wrote views=4, then the cache node crashed before the flush. db views=3

Three things to see. Write-through and write-around cost the caller the same 21 ms; the difference is the next read (a hit versus a miss). Write-behind costs the caller 1 ms and turned three writes into one database write. And then the crash: the database says 3, but the user saw 4. That's the deal you sign with write-behind.

Write-throughWrite-behindWrite-around
ConsistencyCache and DB agree after every writeDB lags the cache until the next flushDB is the truth; cache fills on the next read
Write latency for the callerCache + DB (slowest)Cache only (fastest)DB only
Data-loss riskNone beyond the DB's ownUnflushed writes are lost if the cache failsNone beyond the DB's own
Read right after writeHitHitMiss
Best fitRead-after-write data: profiles, settings, cartsHigh-volume, loss-tolerant writes: counters, metrics, presenceWrite-heavy, read-rarely data: logs, history, imports

Expiry and eviction: when does an entry die?

Two different mechanisms decide when an entry leaves the cache, and it's worth keeping them apart:

  • Expiration is about time. The entry is too old to trust, so it's removed (or ignored) even if there's plenty of room.
  • Eviction is about space. The cache is full, so something has to go, even if it's still fresh.

Absolute vs sliding expiration

Absolute expiration (a plain TTL) says "this entry dies 30 seconds after it was created." Sliding expiration says "this entry dies after 30 seconds without a read." Every hit pushes a sliding expiry forward.

Sliding is good for session-like data: keep it while someone's using it, drop it when they leave. Its trap is that a key read often enough never expires, so it never picks up changes from the database. The fix is to combine them: sliding, with an absolute cap. MemoryCacheEntryOptions lets you set both SlidingExpiration and AbsoluteExpirationRelativeToNow on one entry.

Here's one entry, created at t=0 and read every 20 seconds, under each policy:

// Absolute vs sliding expiration, using a fake clock so the output is exact.
var reads = new double[] { 20, 40, 60, 80 };
var policies = new (string Name, Entry Entry)[]
{
    ("absolute 30s", new Entry(Absolute: 30, Sliding: null)),
    ("sliding 30s", new Entry(Absolute: null, Sliding: 30)),
    ("sliding 30s, capped at 60s", new Entry(Absolute: 60, Sliding: 30)),
};

foreach (var (name, entry) in policies)
{
    var line = $"{name,-28}";
    foreach (var t in reads) line += $" t={t}:{(entry.TryRead(t) ? "hit " : "MISS")}";
    Console.WriteLine(line);
}

// Created at t=0. Absolute = max lifetime from creation. Sliding = max idle time since the last read.
class Entry(double? Absolute, double? Sliding)
{
    private double _lastAccess = 0;
    private bool _expired;

    public bool TryRead(double now)
    {
        if (_expired) return false;
        if (now >= Absolute || now - _lastAccess >= Sliding) { _expired = true; return false; }
        _lastAccess = now;   // a hit pushes a sliding expiry forward
        return true;
    }
}
# Absolute vs sliding expiration, using a fake clock so the output is exact.
import math


class Entry:
    """Created at t=0. absolute = max lifetime. sliding = max idle time since the last read."""

    def __init__(self, absolute=math.inf, sliding=math.inf):
        self.absolute, self.sliding = absolute, sliding
        self.last_access, self.expired = 0.0, False

    def try_read(self, now):
        if self.expired:
            return False
        if now >= self.absolute or now - self.last_access >= self.sliding:
            self.expired = True
            return False
        self.last_access = now  # a hit pushes a sliding expiry forward
        return True


policies = [
    ("absolute 30s", Entry(absolute=30)),
    ("sliding 30s", Entry(sliding=30)),
    ("sliding 30s, capped at 60s", Entry(absolute=60, sliding=30)),
]
for name, entry in policies:
    cells = " ".join(f"t={t}:{'hit ' if entry.try_read(t) else 'MISS'}" for t in (20, 40, 60, 80))
    print(f"{name:<28} {cells}")

Output:

absolute 30s                 t=20:hit  t=40:MISS t=60:MISS t=80:MISS
sliding 30s                  t=20:hit  t=40:hit  t=60:hit  t=80:hit
sliding 30s, capped at 60s   t=20:hit  t=40:hit  t=60:MISS t=80:MISS

The plain sliding entry is still being served at t=80, and would be at t=8,000 if the reads kept coming. The capped one refreshes at 60 seconds no matter what. My default is an absolute TTL, with sliding only for per-user, per-session data, and always with a cap.

LRU, LFU and FIFO

When the cache is full, the eviction policy picks the victim:

  • LRU (least recently used) evicts whatever was touched longest ago. It's the default almost everywhere because recent use is a good predictor of the next use.
  • LFU (least frequently used) evicts whatever has been used the fewest times. It protects steady favourites from a one-off burst, but it's slow to let go of keys that used to be popular.
  • FIFO (first in, first out) evicts whatever was added first, ignoring reads. It's the simplest and usually the worst for a cache, but it's predictable, and cheap to build.

The classic exercise, and a good way to understand LRU, is to build one with O(1) get and put. You need two structures: a hash map for lookup, and a doubly linked list for order. On every hit, you move the node to the front. On a put to a full cache, you drop the node at the back.

// An LRU cache: a Dictionary for O(1) lookup plus a LinkedList for O(1) "most recently used" order.
var lru = new LruCache<string, int>(capacity: 3);
lru.Put("a", 1); lru.Put("b", 2); lru.Put("c", 3);
lru.TryGet("a", out _);          // touch "a", so "b" is now the least recently used
lru.Put("d", 4);                 // over capacity: evicts "b"
Console.WriteLine($"keys, most recent first: {string.Join(", ", lru.Keys)}");
Console.WriteLine($"has b? {lru.TryGet("b", out _)}");

class LruCache<TKey, TValue>(int capacity) where TKey : notnull
{
    private readonly Dictionary<TKey, LinkedListNode<(TKey Key, TValue Value)>> _map = new();
    private readonly LinkedList<(TKey Key, TValue Value)> _order = new();   // front = most recent

    public IEnumerable<TKey> Keys => _order.Select(n => n.Key);

    public bool TryGet(TKey key, out TValue value)
    {
        if (_map.TryGetValue(key, out var node))
        {
            _order.Remove(node);         // O(1): we hold the node itself
            _order.AddFirst(node);
            value = node.Value.Value;
            return true;
        }
        value = default!;
        return false;
    }

    public void Put(TKey key, TValue value)
    {
        if (_map.TryGetValue(key, out var existing)) _order.Remove(existing);
        else if (_map.Count == capacity)
        {
            _map.Remove(_order.Last!.Value.Key);   // evict the least recently used
            _order.RemoveLast();
        }
        _map[key] = _order.AddFirst((key, value));
    }
}
# An LRU cache on OrderedDict: move_to_end on every hit, popitem(last=False) to evict the oldest.
from collections import OrderedDict


class LruCache:
    def __init__(self, capacity):
        self.capacity, self.items = capacity, OrderedDict()

    def get(self, key, default=None):
        if key not in self.items:
            return default
        self.items.move_to_end(key)  # now the most recently used
        return self.items[key]

    def put(self, key, value):
        if key in self.items:
            self.items.move_to_end(key)
        elif len(self.items) == self.capacity:
            self.items.popitem(last=False)  # evict the least recently used
        self.items[key] = value


lru = LruCache(3)
lru.put("a", 1); lru.put("b", 2); lru.put("c", 3)
lru.get("a")      # touch "a", so "b" is now the least recently used
lru.put("d", 4)   # over capacity: evicts "b"
print("keys, most recent first:", ", ".join(reversed(lru.items)))
print("has b?", lru.get("b") is not None)

Output:

keys, most recent first: d, a, c
has b? False

In Python, OrderedDict already is the map plus the linked list, which is why that version is so short. In practice you rarely write this yourself: Python has functools.lru_cache for functions (more on that below), .NET's MemoryCache evicts by size and priority when you set a SizeLimit, and Redis has allkeys-lru and allkeys-lfu policies (both approximated by sampling, which is close enough and much cheaper).

To see why the policy matters, here are all three on two access patterns, with room for three keys. The first pattern is two hot keys followed by a one-off scan. The second is two keys that were popular, then two new keys that become popular:

// FIFO vs LRU vs LFU on two access patterns, cache capacity 3. Each Access returns true on a hit.
var patterns = new (string Name, string Keys)[]
{
    ("hot A,B then a one-off scan", "ABABCDEAB"),
    ("old favourites, new hot pair", "AAABBBCDCDCD"),
};

foreach (var (name, keys) in patterns)
{
    Console.WriteLine($"{name}: {keys}");
    foreach (var policy in new IPolicy[] { new Fifo(3), new Lru(3), new Lfu(3) })
        Console.WriteLine($"  {policy.GetType().Name.ToUpper(),-4} hits={keys.Count(k => policy.Access(k))}");
}

interface IPolicy { bool Access(char key); }

class Fifo(int capacity) : IPolicy   // evict whatever was added first, reads don't matter
{
    private readonly Queue<char> _queue = new();
    public bool Access(char key)
    {
        if (_queue.Contains(key)) return true;
        if (_queue.Count == capacity) _queue.Dequeue();
        _queue.Enqueue(key);
        return false;
    }
}

class Lru(int capacity) : IPolicy    // evict whatever was used longest ago
{
    private readonly LinkedList<char> _order = new();
    public bool Access(char key)
    {
        var hit = _order.Remove(key);
        if (!hit && _order.Count == capacity) _order.RemoveLast();
        _order.AddFirst(key);
        return hit;
    }
}

class Lfu(int capacity) : IPolicy    // evict whatever has been used least often (ties: oldest)
{
    private readonly Dictionary<char, (int Count, int Added)> _items = new();
    private int _tick;
    public bool Access(char key)
    {
        _tick++;
        if (_items.TryGetValue(key, out var e)) { _items[key] = (e.Count + 1, e.Added); return true; }
        if (_items.Count == capacity)
            _items.Remove(_items.MinBy(kv => (kv.Value.Count, kv.Value.Added)).Key);
        _items[key] = (1, _tick);
        return false;
    }
}
# FIFO vs LRU vs LFU on two access patterns, cache capacity 3. Each access() returns True on a hit.
from collections import OrderedDict
from itertools import count


class Fifo:  # evict whatever was added first; reads don't matter
    def __init__(self, capacity):
        self.capacity, self.items = capacity, OrderedDict()

    def access(self, key):
        if key in self.items:
            return True
        if len(self.items) == self.capacity:
            self.items.popitem(last=False)
        self.items[key] = None
        return False


class Lru(Fifo):  # same as FIFO, except a hit moves the key to the back of the line
    def access(self, key):
        if key in self.items:
            self.items.move_to_end(key)
            return True
        return super().access(key)


class Lfu:  # evict whatever has been used least often (ties: oldest)
    def __init__(self, capacity):
        self.capacity, self.items, self.tick = capacity, {}, count()

    def access(self, key):
        added = next(self.tick)
        if key in self.items:
            hits, first = self.items[key]
            self.items[key] = (hits + 1, first)
            return True
        if len(self.items) == self.capacity:
            del self.items[min(self.items, key=self.items.get)]
        self.items[key] = (1, added)
        return False


for name, keys in [("hot A,B then a one-off scan", "ABABCDEAB"),
                   ("old favourites, new hot pair", "AAABBBCDCDCD")]:
    print(f"{name}: {keys}")
    for policy in (Fifo(3), Lru(3), Lfu(3)):
        print(f"  {type(policy).__name__.upper():<4} hits={sum(policy.access(k) for k in keys)}")

Output:

hot A,B then a one-off scan: ABABCDEAB
  FIFO hits=2
  LRU  hits=2
  LFU  hits=4
old favourites, new hot pair: AAABBBCDCDCD
  FIFO hits=8
  LRU  hits=8
  LFU  hits=4

LFU wins the first pattern, because the scan of C, D and E can't push out keys with a higher count. LRU wins the second, because LFU keeps A and B on their old counts while C and D thrash. Neither is always better. Redis's LFU deals with the second problem by decaying counts over time, so old popularity fades. If you don't know your access pattern, start with LRU.

Size limits

An unbounded cache is a memory leak with good intentions. Every cache needs a limit, by entry count or by bytes, and you need to know what happens when it's reached. In Redis that's maxmemory plus maxmemory-policy; the default policy, noeviction, returns errors on writes instead of evicting, which surprises people who meant to use Redis as a cache.

.NET's MemoryCache has its own surprise. With a SizeLimit set, every entry must declare a Size, and an entry that doesn't fit is not added: the call succeeds, and the value just isn't there.

#:package Microsoft.Extensions.Caching.Memory@10.0.0
using Microsoft.Extensions.Caching.Memory;

using var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 2 });
cache.Set("a", 1, new MemoryCacheEntryOptions { Size = 1 });
cache.Set("b", 2, new MemoryCacheEntryOptions { Size = 1 });
cache.Set("c", 3, new MemoryCacheEntryOptions { Size = 1 });   // over the limit
Console.WriteLine($"a={cache.TryGetValue("a", out _)} b={cache.TryGetValue("b", out _)} c={cache.TryGetValue("c", out _)}");
try { cache.Set("d", 4); } catch (InvalidOperationException ex) { Console.WriteLine($"no Size: {ex.GetType().Name}"); }

Output:

a=True b=True c=False
no Size: InvalidOperationException

Set for "c" returned normally and cached nothing (it also starts a compaction in the background, so a later Set can succeed). That's fine for a cache, since a miss just goes to the database, but it's a nasty surprise if you assumed Set then Get always round-trips.

Invalidation: the hard one

Phil Karlton's line is the one everyone quotes: "There are only two hard things in Computer Science: cache invalidation and naming things." It's hard because invalidation is a distributed systems problem in disguise. The database changed, and now some number of caches, on some number of machines, hold a copy that's wrong. There are four ways to deal with that, from simplest to most precise:

  1. TTL only. Don't invalidate at all; let entries expire. Simple and always eventually correct, but you serve stale data for up to one TTL. Fine for anything where "a few minutes old" is acceptable.
  2. Delete on write. When the app changes a row, it deletes the cache key. Update the database first, then delete the key. Delete first, and a reader can slip in between, load the old value, and put it back. Delete, rather than update, the cache entry: two writers updating the cache can finish in the wrong order, but two deletes can't conflict.
  3. Versioned and tagged keys. Put a version number in the key: catalog:v3:product:42. To invalidate everything in the catalog, bump the version to 4. Old keys are never read again and age out on their own. It's one write instead of finding and deleting thousands of keys. HybridCache's RemoveByTagAsync works the same way: it doesn't delete anything, it records "ignore entries with this tag created before now."
  4. Event-driven. The writer publishes "product 42 changed" on a message bus (Redis pub/sub, a queue, database change feeds), and every node drops its copy. This is how you keep several in-process caches in sync, and it's the most precise option. Its weakness is that messages can be delayed or lost, so you still keep a TTL as a backstop.

Here are all four:

// Four ways to make a cache let go of old data, over one fake database.
var db = new Dictionary<string, string> { ["p1"] = "$10", ["p2"] = "$20", ["p3"] = "$30" };

// 1. TTL only: nobody tells the cache. It serves the old price until the entry expires.
var cache = new Dictionary<string, (string Value, double ExpiresAt)>();
double now = 0;
string Get(string key)
{
    if (cache.TryGetValue(key, out var e) && e.ExpiresAt > now) return e.Value;
    cache[key] = (db[key], now + 60);
    return db[key];
}
Get("p1");
db["p1"] = "$12";
now = 30; Console.WriteLine($"ttl only        t=30 p1={Get("p1")}  (stale)");
now = 61; Console.WriteLine($"ttl only        t=61 p1={Get("p1")}  (fresh after expiry)");

// 2. Delete on write: update the database first, then remove the cache entry.
db["p1"] = "$13";
cache.Remove("p1");
Console.WriteLine($"delete on write p1={Get("p1")}");

// 3. Versioned (tagged) keys: every key embeds its tag's version. Bumping the version
//    orphans every old key in one step; the orphans age out through TTL or eviction.
var tagVersion = new Dictionary<string, int> { ["catalog"] = 1 };
var tagged = new Dictionary<string, string>();
var dbReads = 0;
string GetTagged(string id)
{
    var key = $"catalog:v{tagVersion["catalog"]}:{id}";
    if (tagged.TryGetValue(key, out var v)) return v;
    dbReads++;
    return tagged[key] = db[id];
}
foreach (var id in new[] { "p1", "p2", "p3" }) GetTagged(id);
db["p2"] = "$22"; db["p3"] = "$33";
tagVersion["catalog"]++;                       // one write invalidates the whole catalog
Console.WriteLine($"tag bump        p2={GetTagged("p2")} p3={GetTagged("p3")}  db reads={dbReads}  keys held={tagged.Count}");

// 4. Event-driven: two app nodes, each with its own local cache, sharing a message bus.
var bus = new Bus();
var nodeA = new Node("A", db, bus);
var nodeB = new Node("B", db, bus);
nodeB.Get("p2");                               // B has p2 cached
nodeA.Update("p2", "$25");                     // A writes and publishes "p2 changed"
Console.WriteLine($"event-driven    node B p2={nodeB.Get("p2")}");

class Bus
{
    private readonly List<Action<string>> _subscribers = new();
    public void Subscribe(Action<string> handler) => _subscribers.Add(handler);
    public void Publish(string key) { foreach (var s in _subscribers) s(key); }
}

class Node
{
    private readonly Dictionary<string, string> _local = new();
    private readonly Dictionary<string, string> _db;
    private readonly Bus _bus;
    public Node(string name, Dictionary<string, string> db, Bus bus)
    {
        (_db, _bus) = (db, bus);
        bus.Subscribe(key => { if (_local.Remove(key)) Console.WriteLine($"                node {name} dropped {key}"); });
    }
    public string Get(string key) => _local.TryGetValue(key, out var v) ? v : _local[key] = _db[key];
    public void Update(string key, string value) { _db[key] = value; _bus.Publish(key); }
}
# Four ways to make a cache let go of old data, over one fake database.
db = {"p1": "$10", "p2": "$20", "p3": "$30"}

# 1. TTL only: nobody tells the cache. It serves the old price until the entry expires.
cache: dict[str, tuple[str, float]] = {}
now = 0.0


def get(key):
    hit = cache.get(key)
    if hit and hit[1] > now:
        return hit[0]
    cache[key] = (db[key], now + 60)
    return db[key]


get("p1")
db["p1"] = "$12"
now = 30; print(f"ttl only        t=30 p1={get('p1')}  (stale)")
now = 61; print(f"ttl only        t=61 p1={get('p1')}  (fresh after expiry)")

# 2. Delete on write: update the database first, then remove the cache entry.
db["p1"] = "$13"
cache.pop("p1", None)
print(f"delete on write p1={get('p1')}")

# 3. Versioned (tagged) keys: bumping the tag's version orphans every old key in one step.
tag_version = {"catalog": 1}
tagged: dict[str, str] = {}
db_reads = 0


def get_tagged(item_id):
    global db_reads
    key = f"catalog:v{tag_version['catalog']}:{item_id}"
    if key not in tagged:
        db_reads += 1
        tagged[key] = db[item_id]
    return tagged[key]


for item_id in ("p1", "p2", "p3"):
    get_tagged(item_id)
db["p2"], db["p3"] = "$22", "$33"
tag_version["catalog"] += 1  # one write invalidates the whole catalog
print(f"tag bump        p2={get_tagged('p2')} p3={get_tagged('p3')}  db reads={db_reads}  keys held={len(tagged)}")


# 4. Event-driven: two app nodes, each with its own local cache, sharing a message bus.
class Bus:
    def __init__(self):
        self.subscribers = []

    def publish(self, key):
        for handler in self.subscribers:
            handler(key)


class Node:
    def __init__(self, name, bus):
        self.name, self.bus, self.local = name, bus, {}
        bus.subscribers.append(self.on_changed)

    def on_changed(self, key):
        if self.local.pop(key, None) is not None:
            print(f"                node {self.name} dropped {key}")

    def get(self, key):
        return self.local.setdefault(key, db[key])

    def update(self, key, value):
        db[key] = value
        self.bus.publish(key)


bus = Bus()
node_a, node_b = Node("A", bus), Node("B", bus)
node_b.get("p2")            # B has p2 cached
node_a.update("p2", "$25")  # A writes and publishes "p2 changed"
print(f"event-driven    node B p2={node_b.get('p2')}")

Output:

ttl only        t=30 p1=$10  (stale)
ttl only        t=61 p1=$12  (fresh after expiry)
delete on write p1=$13
tag bump        p2=$22 p3=$33  db reads=5  keys held=5
                node B dropped p2
event-driven    node B p2=$25

Look at the tag line: one version bump invalidated all three products, the next reads loaded fresh values, and the cache now holds five keys, three of them orphans waiting for TTL or eviction. That's the cost of versioned keys: a little wasted memory, in exchange for invalidation that's one write and can't miss a key.

Even delete-on-write has a known race. A reader misses, reads the old row, and is slow to write it back; meanwhile a writer updates the row and deletes the key; then the slow reader writes the old value into the cache. It's rare, and a TTL bounds the damage, which is the real lesson: always keep a TTL, even when you also invalidate explicitly. Explicit invalidation makes the cache fresh in the normal case. The TTL makes it correct eventually when something goes wrong.

Failure modes and their fixes

Most cache incidents aren't wrong values. They're the cache stopping protecting the database, all at once. These are the five to know.

Cache stampede (thundering herd)

A popular key expires, or a deploy clears the cache, and every request that wanted it misses at the same moment. They all go to the database together, and the database, sized for the hit rate, falls over. The Azure incidents I wrote about in The Decode #013 show what a cold cache at peak traffic can do.

The fixes, cheapest first:

  • Single-flight (request coalescing). The first miss starts the load; every other request for that key waits for the same result. One database call instead of a hundred.
  • A lock. The distributed version of single-flight: the first miss takes a short-lived lock in Redis (SET key value NX PX 5000), loads, and fills the cache; the others wait briefly or serve stale. Single-flight only coalesces within one process, so with fifty app servers you can still get fifty loads. A lock gets you to one.
  • Jittered TTLs. Don't let keys that were cached together expire together (more under avalanche, below).
  • Early refresh. Refresh before expiry, so no reader ever sees the miss: refresh-ahead, or the probabilistic version below.
  • Serve stale while revalidating. Keep the old value past its TTL and return it while one request reloads.

Here's single-flight, with 100 concurrent requests for a cold key:

// 100 requests arrive at once for a key that isn't cached. Without coalescing, all 100 hit the DB.
using System.Collections.Concurrent;

var db = new SlowDb();

var naive = new ConcurrentDictionary<string, string>();
async Task<string> GetNaive(string key)
{
    if (naive.TryGetValue(key, out var v)) return v;
    return naive[key] = await db.Load(key);    // every concurrent miss does its own load
}

// Single-flight: the first miss stores a Lazy<Task>; everyone else awaits that same task.
var inFlight = new ConcurrentDictionary<string, Lazy<Task<string>>>();
var coalesced = new ConcurrentDictionary<string, string>();
async Task<string> GetSingleFlight(string key)
{
    if (coalesced.TryGetValue(key, out var v)) return v;
    var load = inFlight.GetOrAdd(key, k => new Lazy<Task<string>>(() => db.Load(k)));
    try { return coalesced[key] = await load.Value; }
    finally { inFlight.TryRemove(key, out _); }   // so a failed load can be retried
}

await Task.WhenAll(Enumerable.Range(0, 100).Select(_ => GetNaive("home-page")));
Console.WriteLine($"naive:         100 requests -> {db.Calls} DB calls");

db.Calls = 0;
await Task.WhenAll(Enumerable.Range(0, 100).Select(_ => GetSingleFlight("home-page")));
Console.WriteLine($"single-flight: 100 requests -> {db.Calls} DB call");

class SlowDb
{
    public int Calls;
    public async Task<string> Load(string key)
    {
        Interlocked.Increment(ref Calls);
        await Task.Delay(100);                 // the expensive query
        return $"<html for {key}>";
    }
}
# 100 requests arrive at once for a key that isn't cached. Without coalescing, all 100 hit the DB.
import asyncio

db_calls = 0


async def load(key):
    global db_calls
    db_calls += 1
    await asyncio.sleep(0.1)  # the expensive query
    return f"<html for {key}>"


naive: dict[str, str] = {}


async def get_naive(key):
    if key not in naive:
        naive[key] = await load(key)  # every concurrent miss does its own load
    return naive[key]


# Single-flight: the first miss creates a task; everyone else awaits that same task.
coalesced: dict[str, str] = {}
in_flight: dict[str, asyncio.Task] = {}


async def get_single_flight(key):
    if key in coalesced:
        return coalesced[key]
    task = in_flight.get(key)
    if task is None:
        task = in_flight[key] = asyncio.create_task(load(key))
    try:
        coalesced[key] = await task
        return coalesced[key]
    finally:
        in_flight.pop(key, None)  # so a failed load can be retried


async def main():
    global db_calls
    await asyncio.gather(*(get_naive("home-page") for _ in range(100)))
    print(f"naive:         100 requests -> {db_calls} DB calls")
    db_calls = 0
    await asyncio.gather(*(get_single_flight("home-page") for _ in range(100)))
    print(f"single-flight: 100 requests -> {db_calls} DB call")


asyncio.run(main())

Output:

naive:         100 requests -> 100 DB calls
single-flight: 100 requests -> 1 DB call

The Lazy<Task> in the C# version matters: ConcurrentDictionary.GetOrAdd can run its factory more than once under a race, but only one Lazy wins, so only one load starts. HybridCache gives you this for free in .NET (one factory call per key per instance); in Python, the same idea is "share one task per key."

Probabilistic early expiration (XFetch)

The cleverest stampede fix comes from a 2015 paper by Vattani, Chierichetti and Lowenstein, "Optimal Probabilistic Cache Stampede Prevention", and is usually called XFetch. Instead of everyone missing at expiry, each read rolls the dice on refreshing early:

refresh if:  now - delta * beta * ln(random())  >=  expiry

delta is how long the recompute takes, and beta (default 1) tunes how eager it is. Since ln(random()) is negative, each read effectively adds a random amount of time to "now." Far from expiry, almost no read refreshes. Close to expiry, one of them almost certainly does. Slow recomputes start earlier. No locks, no coordination, and no background workers: just a stored delta next to each value. It's in the code block below, with jitter and negative caching.

Cache penetration

Requests for keys that don't exist. A normal cache only stores things it found, so a request for user 999 misses, queries the database, finds nothing, caches nothing, and the next request does it all again. A bug, a scraper or an attacker sending random IDs walks straight through your cache to the database.

The fixes:

  • Negative caching. Cache the "not found" too, with a short TTL (seconds to a minute), so a user created a moment later appears soon.
  • A Bloom filter in front of the cache. It's a compact bit set that can say "definitely not present" for keys that were never added. If the filter says no, skip the cache and the database entirely. It's worth it when the space of possible IDs is huge, and Redis has one built in (BF.ADD and BF.EXISTS).
  • Validate input. If IDs are UUIDs, reject anything that isn't one before it reaches the cache at all.

Cache avalanche

The stampede's bigger sibling: many different keys expire at the same moment, or the cache itself goes down. A common cause is a batch job or a deploy that warms 10,000 keys at once with the same TTL, so they all expire together, five minutes later.

The fix is jitter: add a random spread to every TTL, so 300 seconds becomes "between 270 and 330." For a cache going down, the fixes are about the "where" (replicas, a local L1 cache in front of the shared one, a circuit breaker on the database calls), which Part 2 covers.

Jitter, XFetch and negative caching, together:

// Three cheap protections: jittered TTLs, XFetch early refresh, and negative caching.
var rng = new Random(42);   // seeded, so the output is repeatable

// 1. Jitter. 1,000 keys are cached in the same second with a 300 s TTL.
int WorstSecond(Func<double> ttl) =>
    Enumerable.Range(0, 1000).Select(_ => (int)ttl()).GroupBy(t => t).Max(g => g.Count());
Console.WriteLine($"no jitter:     worst second has {WorstSecond(() => 300)} keys expiring");
Console.WriteLine($"+/-10% jitter: worst second has {WorstSecond(() => 300 * (0.9 + 0.2 * rng.NextDouble()))} keys expiring");

// 2. XFetch (probabilistic early expiration). Each read rolls the dice; the closer to expiry,
//    and the slower the recompute (delta), the more likely this read refreshes early.
bool ShouldRefresh(double now, double expiry, double delta, double beta = 1.0) =>
    now - delta * beta * Math.Log(1 - rng.NextDouble()) >= expiry;

for (var trial = 1; trial <= 5; trial++)
{
    // Ten reads per second; the entry expires at t=60 and takes about 2 s to recompute.
    var t = Enumerable.Range(0, 601).Select(i => i / 10.0).First(now => ShouldRefresh(now, expiry: 60, delta: 2));
    Console.WriteLine($"xfetch trial {trial}: the read at t={t:0.0}s refreshes early{(t < 60 ? "" : " (no: plain expiry)")}");
}

// 3. Negative caching. Someone keeps asking for a user that doesn't exist.
var dbCalls = 0;
string? LoadUser(int id) { dbCalls++; return id == 1 ? "Ada" : null; }

var cache = new Dictionary<int, string?>();   // a null value means "we checked: it doesn't exist"
string? GetUser(int id)
{
    if (cache.TryGetValue(id, out var cached)) return cached;
    return cache[id] = LoadUser(id);           // cache the miss too (give it a short TTL in real code)
}
for (var i = 0; i < 5; i++) LoadUser(999);
Console.WriteLine($"no negative cache:   5 lookups for user 999 -> {dbCalls} DB calls");
dbCalls = 0;
for (var i = 0; i < 5; i++) GetUser(999);
Console.WriteLine($"with negative cache: 5 lookups for user 999 -> {dbCalls} DB call");
# Three cheap protections: jittered TTLs, XFetch early refresh, and negative caching.
import math
import random
from collections import Counter

rng = random.Random(42)  # seeded, so the output is repeatable


# 1. Jitter. 1,000 keys are cached in the same second with a 300 s TTL.
def worst_second(ttl):
    return max(Counter(int(ttl()) for _ in range(1000)).values())


print(f"no jitter:     worst second has {worst_second(lambda: 300)} keys expiring")
print(f"+/-10% jitter: worst second has {worst_second(lambda: 300 * rng.uniform(0.9, 1.1))} keys expiring")


# 2. XFetch (probabilistic early expiration). Each read rolls the dice; the closer to expiry,
#    and the slower the recompute (delta), the more likely this read refreshes early.
def should_refresh(now, expiry, delta, beta=1.0):
    return now - delta * beta * math.log(1 - rng.random()) >= expiry


for trial in range(1, 6):
    # Ten reads per second; the entry expires at t=60 and takes about 2 s to recompute.
    t = next(i / 10 for i in range(601) if should_refresh(i / 10, expiry=60, delta=2))
    print(f"xfetch trial {trial}: the read at t={t:.1f}s refreshes early" + ("" if t < 60 else " (no: plain expiry)"))

# 3. Negative caching. Someone keeps asking for a user that doesn't exist.
db_calls = 0


def load_user(user_id):
    global db_calls
    db_calls += 1
    return "Ada" if user_id == 1 else None


MISSING = object()
cache: dict[int, object] = {}  # None stored here means "we checked: it doesn't exist"


def get_user(user_id):
    cached = cache.get(user_id, MISSING)
    if cached is not MISSING:
        return cached
    cache[user_id] = load_user(user_id)  # cache the miss too (short TTL in real code)
    return cache[user_id]


for _ in range(5):
    load_user(999)
print(f"no negative cache:   5 lookups for user 999 -> {db_calls} DB calls")
db_calls = 0
for _ in range(5):
    get_user(999)
print(f"with negative cache: 5 lookups for user 999 -> {db_calls} DB call")

C# output:

no jitter:     worst second has 1000 keys expiring
+/-10% jitter: worst second has 30 keys expiring
xfetch trial 1: the read at t=51.5s refreshes early
xfetch trial 2: the read at t=55.3s refreshes early
xfetch trial 3: the read at t=51.6s refreshes early
xfetch trial 4: the read at t=54.4s refreshes early
xfetch trial 5: the read at t=54.0s refreshes early
no negative cache:   5 lookups for user 999 -> 5 DB calls
with negative cache: 5 lookups for user 999 -> 1 DB call

Python output:

no jitter:     worst second has 1000 keys expiring
+/-10% jitter: worst second has 26 keys expiring
xfetch trial 1: the read at t=49.2s refreshes early
xfetch trial 2: the read at t=53.4s refreshes early
xfetch trial 3: the read at t=54.3s refreshes early
xfetch trial 4: the read at t=51.8s refreshes early
xfetch trial 5: the read at t=55.8s refreshes early
no negative cache:   5 lookups for user 999 -> 5 DB calls
with negative cache: 5 lookups for user 999 -> 1 DB call

The two languages print different numbers here because their seeded random generators produce different sequences, which is why I've shown both. The shape is the same. Without jitter, 1,000 keys expire in the same second; with 10% jitter, the worst second has 26 to 30. XFetch refreshed the key between about 49 and 56 seconds in every trial, so with ten reads a second the key never actually expired. And caching "not found" turned five database calls into one.

Hot keys

One key gets so much traffic that the single cache node holding it becomes the bottleneck, even though the cache as a whole is fine. Think of a celebrity's profile, a flash sale item, or a global config object read on every request. In a sharded Redis cluster, each key lives on one shard, so one key's traffic can't be spread out.

The fixes: put a small in-process cache in front of the shared one for that key (even a 1-second TTL removes almost all of the load), or split the key into copies (config:1 to config:8), with readers picking one at random and writers updating all of them. Both are about where the copies live, so I'll leave the details to Part 2.

Stale data

Not a failure the cache can detect, which is what makes it dangerous. Every strategy above trades some freshness for speed; the bug is when nobody decided how much. For each cached thing, I'd write down the answer to "how old can this be before a user is harmed?" Prices in a cart: seconds, and re-check at checkout. A blog post: minutes. A list of countries: days. That number is your TTL, and anything that needs to be fresher than that needs explicit invalidation, or shouldn't be cached.

Memoization is not data caching

Memoization caches a function's result, keyed by its arguments. It's safe when the function is pure: the same inputs always give the same output, and nothing else changes it. Recursive algorithms, parsing, formatting, expensive math. There's no TTL and no invalidation, because the answer can never go stale.

Data caching caches a copy of data that lives somewhere else and can change behind your back. It needs everything in this post: expiry, invalidation, and a plan for stale data.

The bug is using the first tool for the second job:

// Memoization: cache a function's result by its arguments. Safe when the function is pure.
using System.Collections.Concurrent;

var calls = 0;
long Fib(int n) { calls++; return n < 2 ? n : Fib(n - 1) + Fib(n - 2); }
Console.WriteLine($"plain fib(25)    = {Fib(25)}  calls={calls}");

// Lazy<T> makes sure the factory runs once per key even if two threads race on GetOrAdd.
var memo = new ConcurrentDictionary<int, Lazy<long>>();
long FibMemo(int n) => memo.GetOrAdd(n, k => new Lazy<long>(() =>
{
    calls++;
    return k < 2 ? k : FibMemo(k - 1) + FibMemo(k - 2);
})).Value;

calls = 0;
Console.WriteLine($"memoized fib(25) = {FibMemo(25)}  calls={calls}  entries={memo.Count}");

// The trap: memoizing something that isn't pure. Data changes; a memo never forgets.
var prices = new Dictionary<string, int> { ["p1"] = 10 };
var priceMemo = new ConcurrentDictionary<string, int>();
int GetPrice(string id) => priceMemo.GetOrAdd(id, k => prices[k]);   // really a database read
GetPrice("p1");
prices["p1"] = 12;
Console.WriteLine($"price after update: {GetPrice("p1")}  (stale forever, nothing ever removes it)");
# Memoization: cache a function's result by its arguments. Safe when the function is pure.
from functools import lru_cache

calls = 0


def fib(n):
    global calls
    calls += 1
    return n if n < 2 else fib(n - 1) + fib(n - 2)


print(f"plain fib(25)    = {fib(25)}  calls={calls}")


@lru_cache(maxsize=None)  # maxsize=128 (the default) would make it an LRU cache
def fib_memo(n):
    global calls
    calls += 1
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)


calls = 0
print(f"memoized fib(25) = {fib_memo(25)}  calls={calls}  {fib_memo.cache_info()}")

# The trap: memoizing something that isn't pure. Data changes; a memo never forgets.
prices = {"p1": 10}


@lru_cache(maxsize=None)
def get_price(product_id):
    return prices[product_id]  # really a database read


get_price("p1")
prices["p1"] = 12
print(f"price after update: {get_price('p1')}  (stale forever, until cache_clear())")

C# output:

plain fib(25)    = 75025  calls=242785
memoized fib(25) = 75025  calls=26  entries=26
price after update: 10  (stale forever, nothing ever removes it)

Python output:

plain fib(25)    = 75025  calls=242785
memoized fib(25) = 75025  calls=26  CacheInfo(hits=23, misses=26, maxsize=None, currsize=26)
price after update: 10  (stale forever, until cache_clear())

Memoizing fib turned 242,785 calls into 26. Memoizing get_price froze the price forever. In Python, @lru_cache(maxsize=None) (or @functools.cache) never evicts anything, so on a function with many possible arguments it's also a memory leak. And on a method, it holds self alive. If the data can change, use a cache with a TTL. If the function is pure, memoize away.

The AI version of this distinction is worth a look too: prompt caching and semantic caching are data caches for model calls, and semantic caching adds a twist, matching by meaning instead of by exact key.

A decision guide

If your situation is...Use...
A read-heavy app with one database, and you're not sureCache-aside with an absolute TTL, and delete on write
Many services or call sites reading the same dataRead-through (one loader, owned by the cache)
A few hot keys with an expensive load, where waiting is not OKRefresh-ahead, or XFetch
Users must see their own change on the next readWrite-through (DB first, then cache), plus cache-aside for reads
Huge write volume, and losing a few seconds of writes is OKWrite-behind, with a replicated cache
Lots of writes that are rarely read backWrite-around
Data used in sessions or bursts, then abandonedSliding expiration, with an absolute cap
A popular key that expires, or a cold start under loadSingle-flight in-process, a lock across servers, jittered TTLs
Many requests for IDs that don't existNegative caching with a short TTL; a Bloom filter for huge ID spaces
One key hammering one cache nodeA local cache in front, or split the key
Several app servers, each with its own in-memory cacheEvent-driven invalidation, with a TTL as a backstop
Invalidating a whole group of keys at onceVersioned or tagged keys
A pure, expensive functionMemoization, with a size bound
Reads are slow because there are too many of them, even with a cacheRead replicas

And the short flow I'd run through for any new cache:

  1. Should this be cached at all? Is it read much more than it's written, and is it slow to get? If it's neither, an index may beat a cache.
  2. How stale can it be? That's your TTL. If the answer is "not at all," you need explicit invalidation, or no cache.
  3. Who loads it? Cache-aside by default; read-through if many places read it; refresh-ahead for the few hot, slow keys.
  4. What happens on write? Delete the key (write-around), update both (write-through), or buffer (write-behind, only if losing writes is OK).
  5. What happens when it's full? Set a size limit and an eviction policy (LRU unless you know better).
  6. What happens when it's empty? Protect the database from the stampede: single-flight, jitter, and a lock if you have many servers.
  7. Where does it live? In process, shared, at the edge, or in the browser. That's Part 2.

Check yourself: questions and answers

1. What's the difference between cache-aside and read-through?

Who loads the data on a miss. In cache-aside, the application checks the cache, reads the database, and fills the cache itself. In read-through, the cache is given a loader and does that work, so the caller only ever talks to the cache. The algorithm is the same; read-through puts it in one place.

2. Write-through vs write-behind: when would you pick each?

Write-through writes the database and the cache in the same request, so the cache is never behind and nothing is lost, but every write pays for both. Write-behind writes only the cache and flushes to the database later, so writes are fast and repeated writes collapse into one, but anything not yet flushed is lost if the cache fails. I'd use write-through for data users expect to see immediately, like a profile, and write-behind only for high-volume, loss-tolerant data, like counters.

3. How do you prevent a cache stampede?

Make sure one request does the expensive load and the rest wait for it or get the old value. In one process that's single-flight (share one in-flight task per key). Across servers it's a short distributed lock. Then stop keys from expiring together, with jittered TTLs, and refresh hot keys before they expire, with refresh-ahead or probabilistic early expiration (XFetch). Serving stale while one request revalidates also works.

4. How do you invalidate a cache?

Four options. A TTL alone, if some staleness is fine. Delete the key on every write: update the database first, then delete. Versioned or tagged keys, where bumping one version number orphans a whole group at once. Or publish a change event that every cache node listens to, which is how you keep several in-process caches in sync. Whichever you choose, keep a TTL as well, as a backstop for missed invalidations and races.

5. On a write, why delete the cache entry instead of updating it?

Because two concurrent writers can update the cache in a different order than they updated the database, leaving the cache permanently wrong. Two deletes can't conflict: the next read just loads whatever the database has now. And delete after the database write, not before, or a reader can reload the old value in between.

6. LRU or LFU?

LRU evicts what was used longest ago, which suits most workloads and handles changing popularity well. LFU evicts what's been used least often, which protects steady favourites from one-off scans, but it holds on to keys that used to be popular unless the counts decay over time. Start with LRU; switch to LFU (with decay, as Redis does it) if scans are pushing out your hot keys.

7. What's cache penetration and how do you stop it?

Requests for keys that don't exist. Nothing gets cached, so every request reaches the database. Cache the "not found" result with a short TTL, put a Bloom filter in front for very large ID spaces, and validate IDs before they reach the cache.

8. What's the difference between memoization and caching?

Memoization caches a pure function's result by its arguments; it never goes stale, so it needs a size limit but no expiry. A data cache holds a copy of data that lives somewhere else and can change, so it needs expiry and invalidation. Memoizing a function that reads a database is a bug: the result is frozen until the process restarts.

Further reading

  • Azure Architecture Center, Cache-Aside pattern
  • AWS, Caching strategies (lazy loading, write-through and TTLs in the ElastiCache guide) and Caching best practices
  • Redis docs, Key eviction (maxmemory, the eviction policies, and how Redis approximates LRU and LFU)
  • Andrea Vattani, Flavio Chierichetti and Keegan Lowenstein, Optimal Probabilistic Cache Stampede Prevention (VLDB 2015, the XFetch paper)
  • Microsoft Learn, HybridCache library in ASP.NET Core (stampede protection and tag-based invalidation)
  • Microsoft Learn, Caching in .NET (IMemoryCache, expiration and size limits)
  • Python docs, functools.lru_cache
  • In this blog: Cloud structure patterns (cache-aside and its GoF ancestor), Data at scale (read replicas), AI in production (prompt and semantic caching), and the architecture patterns map
  • Next in this series: Caching in Depth, Part 2: where caching lives, frontend to database
← Previous

Command, Chain of Responsibility, Mediator and Template Method in the Agent Era

Next →

AI Patterns for Reliable Output: Structured Output, RAG, Context Engineering, Evals

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.