Saltar al contenido principal

What Gets Thrown Out: LRU, LFU, and the Admission Filter

· 11 min de lectura
Clustron Team
Ingeniería de Sistemas Distribuidos

A cache with room for a million entries will, sooner or later, be asked to store the million-and-first. At that instant it must evict something, and the rule it uses to pick the victim — the eviction policy — decides the one number that justifies the cache's existence: the hit rate. A cache that evicts well absorbs your read traffic and shields the store behind it; a cache that evicts badly keeps all the wrong things, serving misses while the database it was supposed to protect takes the full load. The policy is not a tuning knob you can safely ignore. It is the cache.

The default answer is least-recently-used: when space is needed, evict the entry that has gone longest without a read, on the theory that recent use predicts future use. It is cheap — a hash map and an intrusive linked list — and for recency-biased traffic it is genuinely good. Then one day a batch job, an analytics query, or a cursor walks sequentially through a large set of cold keys, and LRU does exactly what it was told: it treats every one of those cold keys as "recently used," parks them at the front of the list, and evicts your hot working set out the back to make room. When the scan finishes, the popular keys are gone, every subsequent real request misses, and the cache spends the next few minutes refilling itself from the store it exists to spare. One scan, and the cache is cold.

The obvious counter is least-frequently-used: keep the keys that are asked for most, regardless of when. That survives the scan — a scanned key seen once cannot out-rank a key seen thousands of times — but it fails in its own ways. It needs a frequency counter per key, it clings to keys that were hot last week and are dead now because nothing ages their counts down, and it refuses entry to brand-new popular keys whose count starts at zero and loses to stale incumbents. The way out of this is to stop asking "which entry do I remove?" and start asking "should the newcomer be let in at all, and is it worth more than what it would push out?"

Recency and frequency are both half-right​

The reason neither policy wins alone is that they each capture one true signal and ignore the other. Recency matters: a key touched a moment ago is often about to be touched again. Frequency matters: a key touched ten thousand times is more valuable than one touched once, whenever it was last seen. LRU is blind to frequency, so a scan's one-hit keys look as good as a hot key. LFU is blind to recency and to aging, so last week's champion squats forever and this morning's rising star never gets a seat.

Modern cache policies — the ones that ship in libraries like Caffeine — combine the two and add a third idea that neither had: admission control. When the cache is full and a new key arrives, the policy does not automatically evict the least-valuable resident to make room. First it decides whether the newcomer even deserves to displace that resident, by comparing their estimated frequencies. If the candidate is likely to be used less often than the victim it would evict, it is simply not admitted — the cache keeps what it has. This single inversion is what makes a scan harmless: each cold scan key, arriving once, is weighed against a hot resident and loses, so it bounces off the cache instead of flushing it.

LRU — the scan key walks in and a hot key falls outXfreq 1Afreq 5Bfreq 4Cfreq 6A evictedhot key lostW-TinyLFU — admission compares frequencies and bars the doorXfreq 1admission filtercandidate freq 1 < victim A freq 5rejected at the doorA stayscache intactthe newcomer must out-rank the key it would evict, so a one-hit scan key never gets in

A frequency estimate that fits in a pocket​

Admission control needs to know, cheaply, roughly how often each key has been seen — including keys that are not even in the cache, because the candidate at the door usually is not. Storing an exact counter per key would cost more than the cache itself. The trick is to accept approximate counts from a count-min sketch: a small grid of counters where each key hashes to one cell per row, a read takes the minimum across its rows, and the whole structure estimates frequencies for an unbounded key space in a few kilobytes. It is the same family of probabilistic structure as the Bloom filter — trade a little accuracy for an enormous space saving, and never let an occasional over-count turn into a wrong decision that matters.

Two refinements make it work in practice. The sketch is aged by periodically halving every counter, so popularity decays and last week's hot key gradually loses to this week's — the fix for LFU's staleness, in constant time. And a small admission window, a little LRU at the front, gives brand-new keys a brief probation in which they can accumulate hits before they ever face the frequency comparison, so a genuinely new hot key is not rejected simply for having started at zero. Recency lives in the window, frequency lives in the sketch, and the main cache holds whatever has proven it belongs.

// On every access, bump the key's estimated frequency.
sketch.Increment(key); // count-min sketch: approximate, tiny, key-space unbounded

// On an insert into a full cache, admit only if the candidate beats the victim.
var victim = mainCache.EvictionCandidate(); // the lowest-value resident (LRU tail)
if (sketch.Estimate(candidate) > sketch.Estimate(victim.Key))
mainCache.Replace(victim, candidate); // newcomer earned its seat
else
drop(candidate); // not admitted — the cache keeps what it has

// Periodically: sketch.Halve(); — age out stale popularity so yesterday's champion decays.

Which to reach for​

LRU is still the right default when the workload is purely recency-biased and free of scans — it is simple, its metadata is one pointer per entry, and its behavior is easy to reason about. Plain LFU is rarely worth its downsides on its own. The admission-based policies earn their slightly larger metadata by holding up across the full range of workloads a shared cache actually sees — recency bursts, stable frequency distributions, and the periodic scans that flatten a naive cache — which is exactly the mix a cache in front of a busy data store is subjected to. The signal to upgrade is a hit rate that collapses on a schedule: if your cache goes cold every time a report runs or a crawler sweeps, you are watching LRU admit a scan, and an admission filter is the fix. It also composes with the rest of the cache's defenses — bounding memory, expiring keys, and spreading hot keys — because admission decides what earns a slot while those decide how many slots there are and how long a slot lasts.

Wrap-up​

When a full cache must drop something, the policy that chooses is the whole game, because the choice is the hit rate and the hit rate is the point. LRU trusts recency and is flushed by a scan that makes cold keys look fresh; LFU trusts frequency and is poisoned by stale popularity and a zero-count door. The policies that win stop choosing a victim and start vetting the newcomer: a tiny count-min sketch estimates how often any key is used, an admission filter refuses to evict a hot resident for a candidate that would be used less, periodic halving ages out old popularity, and a small recency window gives new keys a fair start. The result is a cache that keeps what matters through recency bursts, frequency skew, and the scans that wreck the naive approaches — which is the difference between a cache that protects your store and one that just keeps the wrong things.