Algorithms · Huge scale

Approximate LRU eviction

How Redis decides what to forget. When memory is full, throw out what nobody has touched in a while. Roughly.

The problem

Redis is a cache: it keeps popular data in fast memory so apps don't have to fetch it from somewhere slower. But memory is finite. Eventually it fills up, and every new key that arrives forces a question: what do we throw away?

The rule for picking a victim is called an eviction policy. A popular choice is least-recently-used (LRU): remove the item that has gone untouched the longest. The bet is that if nobody has asked for it in ages, nobody will soon.

The obvious way

Keep every key in a perfect list, ordered from most to least recently used. Each read moves that key to the front, and eviction takes the one at the back. It's exactly right, but it means tracking a full ordering of all keys and reshuffling it on every single access. That's extra memory and extra work spent on bookkeeping instead of serving data.

The clever idea

Redis documents that its LRU is approximated. It doesn't keep a perfect ordering. When it must evict, it samples a few keys (maxmemory-samples, default 5) and evicts the oldest one in that sample. Think of picking 5 random milk cartons from a huge fridge and tossing the one with the oldest date. It's not guaranteed the oldest in the fridge, but it's usually very old.

Redis documents this as close to true LRU at far lower memory cost. Let's check that claim ourselves: 2000 requests, 100 possible keys, a cache that holds only 20, and a few keys that are much more popular than the rest.

How the code does it

Both caches see the identical 2000 requests, so the contest is fair. The perfect one uses an OrderedDict: every hit moves the key to the end, so the front is always the true oldest.

The sampled one keeps no order at all, just a last-used timestamp per key. When full, it grabs 5 random keys and takes the stalest. Run it: the bars for exact and sampled should sit very close, and both dwarf the no-cache bar of 0.

Trade-offs

Sampling is sometimes wrong: it can evict a key that was fairly recent because all five candidates happened to be recent too. You trade a little accuracy for less memory and less bookkeeping. If your cache is tiny, or a single wrong eviction is very costly, exact LRU is simple and may be the better choice.

Where else you’ll see it

The idea of check a small random sample instead of everything shows up across computing whenever perfect knowledge costs too much. To see how Redis really does it, browse the open-source code at github.com/redis/redis.

You set SAMPLES = 1 in the sampled version. What most likely happens to its hit rate?

  • It stays the same as SAMPLES = 5
  • It drops, since eviction becomes basically random
  • It rises above exact LRU
Show the answer

It drops, since eviction becomes basically random. With one sample, the 'oldest of the sample' is just a random key, so popular keys get evicted as easily as stale ones. More samples means better guesses at the true oldest.

Change it and see
  • Set SAMPLES to 1
  • Set SAMPLES to 10
  • Change SIZE from 20 to 5

The code

Python, with what each line means beside it. It compares the clever way with a perfect least-recently-used list.

import randomBring in randomness tools
from collections import OrderedDictBring in an ordered dictionary
random.seed(7)Fix the randomness so runs repeat
SIZE, REQUESTS, SAMPLES = 20, 2000, 5Set cache size, request count, sample size
weights = [1 / (k + 1) for k in range(100)]Give low-numbered keys bigger weights
requests = random.choices(range(100), weights, k=REQUESTS)Draw 2000 requests, favoring popular keys
def exact_lru(reqs):Define the perfect LRU cache
cache, hits = OrderedDict(), 0Start empty with zero hits
for k in reqs:Handle each request in turn
if k in cache:If the key is cached...
hits += 1Count a hit
cache.move_to_end(k)Mark it as most recently used
else:Otherwise it's a miss
if len(cache) >= SIZE:If the cache is full...
cache.popitem(last=False)Drop the longest-untouched key
cache[k] = TrueStore the new key
return hits / len(reqs) * 100Return hit percentage
def sampled_lru(reqs):Define the sampled LRU cache
last_used, hits = {}, 0Track last-used time per key
for t, k in enumerate(reqs):Handle each request with its clock tick
if k in last_used:If the key is cached...
hits += 1Count a hit
elif len(last_used) >= SIZE:Otherwise, if the cache is full...
pool = random.sample(list(last_used), SAMPLES)Pick five random cached keys
oldest = min(pool, key=last_used.get)Find the stalest of those five
del last_used[oldest]Evict that one
last_used[k] = tRecord when this key was used
return hits / len(reqs) * 100Return hit percentage
exact = exact_lru(requests)Run the perfect version
sampled = sampled_lru(requests)Run the sampled version
show([0, round(exact, 1), round(sampled, 1)], "hit %: no cache | exact LRU | sampled (5)")Draw bars comparing all three
print(f"gap: {abs(exact - sampled):.1f} points")Print how far apart they are

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on huge scale