Skip to content

LRU and friends: what a cache throws out

Working knowledgeUnder the hood

Your cache is full and a new key arrives. Something has to go. Here is how LRU, LFU and TTLs decide, drawn on a cache that holds three keys.

01 A full cache has to choose

A cache has a fixed amount of memory. While there is room, every new key just goes in. Once it is full, storing one more key means throwing one out, and the rule that picks which one is the eviction policy.

A good policy throws out the key you will not ask for again soon. Nobody knows the future, so each policy bets on a clue from the past: LRU bets on recent use, LFU on frequent use. To compare them, we will run the same nine requests through a cache that holds three keys.

Text
capacity: 3 keys
requests: A B A B C D E A B

A and B are the popular keys. C, D and E are asked for once each, like a report job reading old rows. A good policy keeps A and B.

02 LRU: throw out the least recently used

LRU keeps the keys in order of last use. Every hit moves a key to the front; when room is needed, the key at the back goes. The bet: what you used a moment ago, you will use again soon.

LRU on a 3-key cache
Step 1 of 10
Misses 0
Requests, in order
A0
B1
A2
B3
C4
D5
E6
A7
B8
Cache, most recent first (holds 3)
Empty
Thrown out
Empty
  • miss
  • hit
  • just added
  • not arrived yet

The cache is empty and holds three keys. Nine requests are about to arrive.

0 hits

03 LRU in a dozen lines

LRU must find a key and move it to the front in constant time. The usual build is a hash map that points into a doubly linked list: the map finds the node, the list moves it in O(1). Python's OrderedDict is exactly that pair, so a working LRU is short.

lru.py
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.data = OrderedDict() # oldest first, newest last
def get(self, key):
if key not in self.data:
return None
self.data.move_to_end(key) # now the most recent
return self.data[key]
def put(self, key, value):
if key in self.data:
self.data.move_to_end(key)
Text
$ python3 lru.py
evict A
evict B
evict C
evict D
hits 2 order ['E', 'A', 'B']

The output matches the trace: four evictions and two hits. OrderedDict lists the oldest first, so the order is the trace's list read backwards.

04 LFU: throw out the least frequently used

LFU keeps a count of uses per key and throws out the lowest count. When two keys tie, it throws out the one used least recently. The bet: a key that has been popular will stay popular.

LFU on a 3-key cache
Step 1 of 10
Misses 0
Requests, in order
A0
B1
A2
B3
C4
D5
E6
A7
B8
Cache: key → times used (holds 3)
Empty
Thrown out
Empty
  • miss
  • hit
  • just added
  • thrown out
  • not arrived yet

The same empty cache and the same nine requests. This time each key keeps a count of how often it was used.

0 hits
LRU on this sequence2 hits of 9Three one-off keys in a row were enough to push out both popular keys.
LFU on this sequence4 hits of 9Two uses each were enough to protect A and B from keys used once.

05 Where LFU loses

Plain counts only grow. Try A A A A B C D B C D: A was hot early and is never asked for again, but with a count of 4 it holds its slot for good. B, C and D keep throwing each other out of the two slots left, and every one of the last six requests misses. LRU drops A as soon as D arrives, then hits on B, C and D: 6 hits against LFU's 3.

Real LFU caches make counts fade. Redis's allkeys-lfu, for example, keeps a small logarithmic counter per key and lowers it as time passes without use (lfu-decay-time), so yesterday's star loses its place. Both policies also need memory for their bookkeeping: a list position or a counter on every key.

Common eviction policies
PolicyThrows outGood atBad at
LRUthe key unused for longestrecent working sets, sessionsone-off scans push out hot keys
LFUthe key with the fewest usesstable favourites, scansold favourites linger without decay
FIFOthe oldest key storedsimple, no work on hitsthrows out hot keys just for age
Randomany keyalmost free to runno sense of what matters

06 TTLs: expiry is not eviction

A TTL (time to live) says how long a key is valid. It is about freshness, not space: a key expires when its time is up, even if the cache is nearly empty. Eviction happens only when memory runs out. Most caches use both.

How Redis expires keys
Step 1 of 7
Redis memory: key → expires at
Empty
  • just set
  • expired, still stored
  • deleted

An empty cache at t = 0. Each key will get its own time to live.

t = 0s clock

So an expired key can still take memory until someone reads it or the sweep finds it. In Redis the sweep runs about ten times a second by default (hz 10) and samples a few keys with a TTL each time, so expired keys go quickly but not instantly.

07 Choosing a policy in Redis

Redis evicts only once you set maxmemory. The policy then decides what goes. allkeys-* policies may evict any key; volatile-* policies only evict keys that have a TTL.

redis.conf
maxmemory 256mb
maxmemory-policy allkeys-lru

The default policy is noeviction. When memory is full, Redis keeps every key and fails writes with an OOM error. If you use Redis as a cache, set a policy on purpose.

SCAN every key onceA batch job flushes an LRU cacheA report that reads every key once makes each of them the most recent. The keys real users need are pushed out, and hit rate drops until they come back.
EX 3600 on every keyEverything expires at onceKeys cached together with the same TTL expire together, and the database takes all the misses in one burst. Add a little random jitter to each TTL.
maxmemory-samples 5Redis LRU is approximateRedis does not keep one big list. It samples a few keys (5 by default) and evicts the least recently used of those. Close to LRU, much cheaper, but not exact.
volatile-lruNo TTLs, nothing to evictA volatile-* policy only considers keys with a TTL. If none have one, it behaves like noeviction and writes start failing.

08 Check yourself

Question

An LRU cache holds 3 keys: X, Y, Z, used in that order (so Z most recently). X is read, then a new key W arrives. Which key is thrown out?

Question

Each night a job reads every product once. In the morning the cache hit rate is low. Which policy change helps most?

Question

A Redis key's TTL ran out a minute ago and nobody has read it since. Is it still in memory?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?