Try
↑ ↓ move↵ openesc close
In this lesson · topic 2 of 7
  1. 1. Why a small cache works at all
  2. 2. FIFO, LRU, LFU, and TinyLFU
  3. 3. Move the hot keys under four policies
  4. 4. Why plain LFU stays stuck after a shift
  5. 5. How big a cache do you need
  6. 6. When a hot key expires
  7. 7. Check the eviction rules

Topic 2

FIFO, LRU, LFU, and TinyLFU

5 min read

Trace a short sequence

Below, a cache of three slots sees a short list of requests. Pick a policy and step through. The cache is the real implementation the lab uses, not a drawing. Switch policy and compare what each one evicts.

Request trace, cache of 3

Step 1 / 12
1231415216121hits 1cache slots, oldest or least valued first for FIFO and LRUorange tint: hit. grey: miss. accent frame: this request.
result
miss
hits so far
0 of 1
cache
1
  1. Request key 1

    Key 1 is missing. There is free space, so it is simply added.

The policies

FIFO evicts the key that has been in the cache the longest. A hit does not change its position. It is simple and cheap, and it throws out a key that is being used constantly just because it arrived early.

LRU evicts the key that was used least recently. Every hit moves the key to the safe end. It adapts quickly when popularity moves, because a key that stops being requested drifts to the exit. Its weakness is that recency is a weak signal. One pass over many rarely used keys pushes every popular key out.

LFU counts hits and evicts the key with the fewest. When popularity is stable, counts are a better signal than recency, because the keys that are popular really are popular. Its weakness is memory. A key that was popular an hour ago keeps a high count, so it stays after it has gone cold, and a newly popular key has a low count and keeps getting evicted before it can build one.

TinyLFU with SLRU separates two decisions. Frequency is tracked for every key, resident or not, in a small table of counters called a count-min sketch. The counters are halved every so often, so old popularity decays. When a missed key arrives at a full cache, TinyLFU compares its estimated frequency with the key that would be evicted. The newcomer gets in only if it is estimated to be more popular. The resident keys are organised as a segmented LRU: new keys sit in a probationary segment and move to a protected segment on a second hit, so a one-off key cannot push out a proven one.

Cost of each

FIFO needs a queue. LRU needs a queue and a reorder on every hit. LFU needs counters and a way to find the smallest. TinyLFU needs the sketch on top of its queues. More bookkeeping buys a better decision, and the lab will show how much better.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms