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

Patterns

Which ones, and which ones not

The point: the core needs no pattern from the catalogue. Two techniques carry it, and a few patterns become useful when the cache grows.

Techniques in the core

  • Combined structure

    Two structures over the same nodes, each good at one job. Not the Composite pattern, which is about trees of parts.

  • Sentinel

    A node without data removes the special cases. A relative of the null object.

  • Policy of eviction

    LRU guesses that the recent past looks like the near future.

  • Key and value store

    get, put, remove. A small surface that many systems share.

Patterns that earn their place later

PatternWhen it paysHere
StrategyA second eviction rulePolicy with added, used, removed, victim
DecoratorFeatures that can be combinedExpiring, counting, locked, around one interface
ObserverSomebody must react to an evictionRemoval listener, called after the lock
BuilderMany optional settingscapacity, ttl, loader, listener
ProxyThe cache stands in front of the real storeA loading cache
IteratorWalk without showing the links__iter__ of the list
Python
from collections import OrderedDictfrom typing import Protocolclass Policy(Protocol):    def added(self, key): ...    def used(self, key): ...    def removed(self, key): ...    def victim(self): ...class Lru:    def __init__(self):        self._order = OrderedDict()    def added(self, key):        self._order[key] = None    def used(self, key):        self._order.move_to_end(key)    def removed(self, key):        del self._order[key]    def victim(self):        return next(iter(self._order))class Fifo(Lru):    def used(self, key):        pass                                # the only differenceclass Cache:    def __init__(self, capacity, policy):        self._capacity, self._policy, self._data = capacity, policy, {}    def get(self, key, default=None):        if key not in self._data:            return default        self._policy.used(key)        return self._data[key]    def put(self, key, value):        if key in self._data:            self._policy.used(key)        else:            if len(self._data) == self._capacity:                victim = self._policy.victim()                self._policy.removed(victim)                del self._data[victim]            self._policy.added(key)        self._data[key] = valuefor policy in (Lru(), Fifo()):    cache = Cache(2, policy)    cache.put("a", 1)    cache.put("b", 2)    cache.get("a")    cache.put("c", 3)    print(type(policy).__name__, cache.get("a"), cache.get("b"))   # Lru 1 None, Fifo None 2
Strategy, done so that each call can stay O(1): the policy hears about every use. The bad interface on the Overview handed it all entries and forced a search.
Edit and run it in your browser

Patterns people add by habit

PatternWhy people add itWhat it costs
Singleton"There is one cache"There are soon two, and tests share entries
Factory"To create policies"A class around one constructor
Template method"Abstract cache with hooks"A lock and a deadline cannot be combined by inheritance
State"Cold, warm, full"It is a comparison of two numbers

Common follow-up questions

QuestionFirst sentence
How would you make it thread-safe?One lock around each method, because a read moves a node
Which other policies exist?FIFO, LFU, random, clock, segments, 2Q, ARC, TinyLFU
How would you add a time to live?A layer that stores value and deadline, and looks before it uses
How does Redis do it?It samples a few random keys and evicts the one idle longest
LRU or LFU?LRU follows change quickly, LFU survives scans. Measure on your own trace

Where does the eviction rule live?

BreaksAn interface that picks from all entries
How
pick(entries) returns the victim.
Limit
Every policy becomes O(n), because it hears nothing between two evictions.
Choose when
Never on a hot path.
WorksInside the cache
How
touch and last are two lines.
Limit
A second rule means a change here.
Choose when
One rule, which is the question as asked.
StrongA policy that hears each use
How
added, used, removed, victim.
Limit
One more object, and a contract to document.
Choose when
The interviewer asks for a second rule.