AlgoViz

Design an LRU cache

medium 85 min

Design an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.

Watch lesson4:49

Builder and events

Many options, and others who want to know

The point: a builder pays when options multiply, and listeners pay when others must react. Both have one rule that people break: check once at build, and never call strangers under the lock.

From constructor to builder

Java
Cache<String, User> users = new CacheBuilder<String, User>()    .capacity(10_000)    .expireAfterWrite(Duration.ofMinutes(5))    .loader(repository::find)    .onRemoval((key, user, cause) -> log.debug("{} left: {}", key, cause))    .recordStats()    .build();// in build(): all checks in one place, then the layers from the inside outCache<K, V> build() {    if (capacity < 1) throw new IllegalStateException("capacity is required");    Cache<K, V> cache = new LruCache<>(capacity);    if (ttl != null) cache = new ExpiringCache<>(cache, ttl, ticker);    cache = new LockedCache<>(cache);    if (loader != null) cache = new LoadingCache<>(cache, loader);    if (stats) cache = new CountingCache<>(cache);    return cache;}
The builder is also the one place that knows the right order of the layers. Callers cannot get it wrong. The pattern itself is on builder.
OptionEffectConflict to check
capacityEntries, or the sum of weightsBoth at once: refuse
expireAfterWriteAge since it was writtenZero or negative
expireAfterAccessAge since the last useReads extend a life for ever: combine with the former
loaderFills missesWithout it, get never loads
writerWrite throughWith a loader that reads another store: stale for ever
recordStatsCountsOff by default, costs a little

Events

EventWhenCarries
HIT, MISSEach getKey. Better as counters: an event for each call is expensive
INSERTION, UPDATEputKey, new value, and the old one for an update
EVICTIONNo roomKey, value
EXPIRATIONToo oldKey, value. Late: at the next get or sweep
REMOVAL by handremoveKey, value
Why the cause matters: an evicted connection must be closed, an updated one too, but a listener that treats an update like an eviction may delete the file that was just written.
Python
from collections import OrderedDictfrom threading import Lockclass NotifyingLru:    def __init__(self, capacity, listener):        self._capacity, self._listener = capacity, listener        self._data, self._lock = OrderedDict(), Lock()    def put(self, key, value):        events = []        with self._lock:            if key in self._data:                events.append(("UPDATE", key, self._data[key]))                self._data.move_to_end(key)            elif len(self._data) == self._capacity:                events.append(("EVICTION", *self._data.popitem(last=False)))            self._data[key] = value        for event in events:                # the lock is free: a listener may call us back            try:                self._listener(*event)            except Exception as error:      # their problem must not become the caller's                print("listener failed:", error)seen = []cache = NotifyingLru(2, lambda *e: (seen.append(e), cache.put("log", len(seen)) if e[0] == "UPDATE" else None))cache.put("a", 1)cache.put("b", 2)cache.put("b", 3)                           # the listener writes into the cache and does not hangprint(seen)   # [('UPDATE', 'b', 2), ('EVICTION', 'a', 1)]
Collect under the lock, tell afterwards. The price: two threads may tell their events in the other order. If order matters, number the events inside the lock.
Edit and run it in your browser

Three mistakes with listeners

  1. 1

    Calling under the lock

    A slow listener stops the cache. One that calls the cache hangs a lock that cannot be taken twice.

  2. 2

    Letting errors out

    A put fails because a logger failed. The entry is stored, the caller thinks it is not.

  3. 3

    Closing a value that is in use

    A reader got the connection a moment ago, then it is evicted and closed. Count the users of a value, or close it later.

Evicted values must be written to disk. How?

BreaksIn the listener, under the lock
How
put waits for the disk.
Limit
Everyone waits.
Choose when
Never.
WorksIn the listener, after the lock
How
Only this put is slow.
Limit
A get in the gap misses and reads the old value from disk.
Choose when
Old data is acceptable.
StrongKeep it findable until it is written
How
A small table of values being written. get looks there as well.
Limit
One more state for an entry.
Choose when
No update may be lost.