Design an LRU cache
medium 85 minDesign 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
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;}| Option | Effect | Conflict to check |
|---|---|---|
| capacity | Entries, or the sum of weights | Both at once: refuse |
| expireAfterWrite | Age since it was written | Zero or negative |
| expireAfterAccess | Age since the last use | Reads extend a life for ever: combine with the former |
| loader | Fills misses | Without it, get never loads |
| writer | Write through | With a loader that reads another store: stale for ever |
| recordStats | Counts | Off by default, costs a little |
Events
| Event | When | Carries |
|---|---|---|
| HIT, MISS | Each get | Key. Better as counters: an event for each call is expensive |
| INSERTION, UPDATE | put | Key, new value, and the old one for an update |
| EVICTION | No room | Key, value |
| EXPIRATION | Too old | Key, value. Late: at the next get or sweep |
| REMOVAL by hand | remove | Key, value |
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)]Three mistakes with listeners
- 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
Letting errors out
A put fails because a logger failed. The entry is stored, the caller thinks it is not.
- 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.