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

Loading once

Stampedes, errors, and writing through

The point: when a cache also loads, it must promise two things. A missing key is loaded once however many callers ask. And nobody holds a lock while waiting for the slow store.

Bug

A miss is a crowd

A popular key expires. In the 50 milliseconds of one load, 200 more callers miss it, and all of them call the database. The cache that should protect the database sends it 200 equal queries. At the level of a service this is the thundering herd. Inside one process it is solved by single flight.

Python
from collections import OrderedDictfrom concurrent.futures import Futurefrom threading import Lock, Threadimport timeclass LoadingCache:    def __init__(self, capacity, load):        self._capacity, self._load = capacity, load        self._data, self._loading, self._lock = OrderedDict(), {}, Lock()    def get(self, key):        with self._lock:            if key in self._data:                self._data.move_to_end(key)                return self._data[key]            future = self._loading.get(key)            leader = future is None            if leader:                future = self._loading[key] = Future()        if not leader:            return future.result()                 # waits, without the lock        try:            value = self._load(key)                # slow, without the lock        except BaseException as error:            with self._lock:                if self._loading.get(key) is future:                    del self._loading[key]         # the next caller may try again            future.set_exception(error)            # the waiting ones hear the truth            raise        with self._lock:            if self._loading.get(key) is future:   # not invalidated meanwhile                del self._loading[key]                if len(self._data) == self._capacity:                    self._data.popitem(last=False)                self._data[key] = value        future.set_result(value)        return value    def invalidate(self, key):        with self._lock:            self._data.pop(key, None)            self._loading.pop(key, None)           # a load that runs now may not be storedcalls = []def slow(key):    calls.append(key)    time.sleep(0.05)    return key.upper()cache = LoadingCache(10, slow)answers = []threads = [Thread(target=lambda: answers.append(cache.get("p"))) for _ in range(50)]for t in threads:    t.start()for t in threads:    t.join()print(len(answers), set(answers), "loads:", len(calls))     # 50 {'P'} loads: 1
Fifty threads, one load. The lock is held for a few dictionary operations, never during the load.
Edit and run it in your browser

Walk through it with a failure at each line

What happensResult
The load raises an errorThe waiting callers get the same error, the note is gone, the next caller tries again
The load never returnsAll wait for ever. Give the load a timeout of its own, and the wait too
The key is invalidated during the loadThe result goes to those who asked before, and is not stored. Without the identity check an old value would come back to life
The load calls the cache for the same keyIt waits for itself. Document it, or detect the same thread
The leader thread is killedThe future is never finished. Python threads cannot be killed from outside. In other systems the wait needs a timeout

Should an error be remembered?

If a missing user is asked for a thousand times, each call goes to the database. Remember the answer *not there* for a few seconds: negative caching. Remember *the database is down* for a much shorter time or not at all, because it is not a fact about the key.

Serve the old value while you load

Refresh ahead

  • After the soft limit, one caller reloads.
  • All others get the old value meanwhile.
  • Nobody waits. Good for data that may be a little old.

Expire and wait

  • After the hard limit, all callers wait for one load.
  • Right when old data would be wrong.
  • Latency has a spike at every expiry.

Writers: the other direction

Wayput doesIf the store failsIf the process dies
Cache asideThe caller writes the store and removes the key hereNothing was cachedNothing is lost
Write throughWrites the store, then the cacheThe error goes to the caller, the cache is unchangedNothing is lost
Write behindWrites the cache and a queueRetry later, in orderQueued writes are lost
Store first. If the cache is written first and the store refuses, readers see a value that does not exist.
Python
class WriteThrough:    def __init__(self, cache, store):        self._cache, self._store = cache, store    def put(self, key, value):        self._store.write(key, value)      # may raise: then the cache still tells the truth        self._cache.put(key, value)    def remove(self, key):        self._store.delete(key)        self._cache.remove(key)
Two threads can still cross between the two lines: A writes the store, B writes the store and the cache, A writes the cache. For one key at a time, hold a lock for that key, or remove instead of put. More on write through.

Two hundred callers miss the same key. What happens?

BreaksEveryone loads
How
get, miss, load, put.
Limit
The store gets the full crowd.
Choose when
Only for cheap loads.
WorksLoad under the lock
How
computeIfAbsent with one lock.
Limit
All keys wait for one slow load.
Choose when
Loads take microseconds.
StrongSingle flight for each key
How
One future for each key in flight.
Limit
Errors and invalidation need thought.
Choose when
The default for a loading cache.