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

Where it shows up

The same pattern appears across everyday software.

  • Python: functools.lru_cache

    A decorator that remembers the results of a function, 128 by default. Its Python source is a dictionary and a circular doubly linked list with one root. The documentation says it is thread-safe, and also that a function may run more than once if a second call arrives before the first has finished: coherent, but no single flight.

  • Java: LinkedHashMap

    A hash map whose entries are also a doubly linked list. Built with access order, and with `removeEldestEntry` overridden, it is an LRU cache. It is not synchronized, and in access order even `get` is a structural change.

  • Caffeine

    A Java cache that records reads in striped ring buffers and replays them in batches under a lock. Its policy is Window TinyLFU: a small LRU window, then an admission test by frequency, then a segmented LRU.

  • Guava Cache

    The builder, the loader and the statistics of this page in one library: `CacheBuilder`, `CacheLoader` with one load for each key, `recordStats`. Its guide warns that entries may be evicted before the maximum size is reached.

  • Redis

    Approximated LRU: a few random keys are sampled, five by default, and the one idle longest is evicted. Since 4.0 an LFU mode exists with a probabilistic counter of a few bits.

  • memcached

    Segmented LRU with the parts HOT, WARM and COLD. Items are moved by a background thread and marked as fetched or active, so that a hit rarely has to take a lock.

  • RocksDB block cache

    LRU split into shards to reduce waiting for a lock. The capacity is divided evenly, and shards do not share it.

  • Android LruCache

    A class for apps, for example for bitmaps. Override `sizeOf` and the limit becomes a weight, such as 4 MiB, and not a number of entries. Calls are thread-safe by one lock on the cache.

  • PostgreSQL buffers

    No list at all. Its buffer manager uses a clock sweep: a hand goes round, and a buffer that was used gets another round. Large sequential scans use a small ring of buffers, so they do not flush the rest.

  • hashicorp/golang-lru

    A fixed-size, thread-safe LRU for Go with Peek, Remove, Resize, an eviction callback, and a 2Q variant in the same package.

  • Processor caches

    Hardware has no time for a list. It keeps a few bits for each set of lines, called pseudo LRU, which is enough to avoid the most recent one.