Video in progress

How do you choose a cache eviction policy? What results do LRU, LFU and W-TinyLFU give, and when?

LRU keeps what was used recently: it's simple, but a one-off scan washes the cache out. LFU keeps what is used often, but doesn't forget stale popularity. W-TinyLFU (Caffeine) gets the strengths of both with a small LRU window and an admission filter that estimates frequency with an approximate sketch. I make the choice by simulating with a real trace.

📖 Answer

A few percentage points of difference in hit rate is a big difference in the load on the DB behind it. Going from 90% to 95% hit rate means half as many requests reach the DB.

LRU's problem: at night, a report reads the entire catalog once. Every element becomes "the newest" and pushes out the hot daytime data. In the morning the cache is cold and the DB load spikes. That's "scan pollution".

With LFU it's the opposite. An article that was trending yesterday was read 1 million times. Today nobody reads it, but its counter is large, so it stays in the cache forever. You need to periodically halve the counters (aging). Also, exact LFU keeps a counter per key, and eviction needs O(log n) or a complex structure.

In W-TinyLFU, a new element first goes into a small LRU "window" (about 1%), which gives a new key a chance. When it leaves the window, it's compared with the candidate to be evicted from the main segment: whichever has the higher estimated frequency stays. The frequency is kept in 4-bit counters like a Count-Min Sketch, periodically halved. Memory is small, it resists scan pollution, and it adapts to trends. Caffeine also tunes the window size automatically with hill climbing.

Cache<Long, Product> cache = Caffeine.newBuilder()
        .maximumSize(200_000)
        .expireAfterWrite(Duration.ofMinutes(10))
        .recordStats()
        .build();

How I decide:

  1. I collect a one-hour sample of the access trace (the sequence of keys) from prod.
  2. I simulate with different policies and sizes; Caffeine's simulator exists for exactly this. You get the hit rate curve "by size" and see where it saturates.
  3. On prod, recordStats() and hit rate and eviction count metrics.

Often the answer is "Caffeine's defaults", but without a trace the size choice stays a guess. For a distributed cache (Redis), allkeys-lru and allkeys-lfu are both approximate and sample-based; those can be compared against a trace too.

An eviction policy doesn't replace a TTL: one is for memory, the other for data freshness.