AlgoViz

Cache eviction policies

easy 22 min

A cache has a memory limit.

See it run

The same requests, different rules: watch who is marked NEXT, who leaves, and what it costs.

Operations

LRU

Evict the entry that was used longest ago.

Step 1 of 11

Empty cache

place 1place 2place 3
key---
last used---
uses---
stored at---
next out---

hits 0

3 places. The requests are A B C A A D A E A B.

Step 1: Empty cache

def get(key):    if key not in data: return None    data.move_to_end(key)      # newest    return data[key]def put(key, value):    if len(data) >= capacity:        data.popitem(last=False)   # oldest use    data[key] = value
Per operation
O(1)
Keeps
order of use
Best possible
5 hits of 10

A map plus a linked list: no clock is needed, only the order.

In the real world

The same cache eviction policies doing real jobs. Pick one and step through it.

C, D and E are read once each. A and B are the keys people want.

Step 1 of 12

Empty cache

place 1place 2place 3
key---
last used---
uses---
stored at---
next out---

hits 0

3 places. The requests are A A B B C D A B E A B.

Step 1: Empty cache

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No memory limit

    critical

    Without a limit the cache grows until the machine runs out of memory, and the operating system kills the process.

    Wrong
    cache = {}                 # grows forever
    Right
    cache = LRUCache(10_000)   # a limit and a rule
  • Cache and sessions in one store

    critical

    Under an all-keys policy a busy product page can push out a login session.

    Wrong
    redis.set("session:7", token)redis.set("page:home", html)   # allkeys-lru
    Right
    sessions.set("session:7", token)   # noevictionpages.set("page:home", html)       # allkeys-lru
  • LFU without decay

    major

    Last month's star has a count nobody can beat and stays for weeks.

    Wrong
    count[key] += 1            # only ever up
    Right
    if minutes_idle(key) >= 1:    count[key] -= 1        # old fame fadescount[key] += 1
  • Batch jobs fill the cache

    major

    A scan stores a million values that nobody reads again.

    Wrong
    for pid in all_products():    get_cached(pid)
    Right
    for pid in all_products():    read_replica(pid)      # never stored

Interview tips

  • How to explain it

    • A full cache must drop one copy.
    • The policy guesses what will not be wanted.
    • A wrong guess costs one slow read.
  • Memory trick: LIFE

    • L: last used, LRU.
    • I: in demand, LFU.
    • F: first in, FIFO. E: expiry, TTL.
  • Good defaults

    • LRU plus TTL.
    • A memory limit, with headroom.
    • Frequency-aware when scans appear.
  • Watch

    • Hit rate and evictions per second.
    • How long victims were idle.
    • Expired versus evicted keys.