Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Time to live
Two reasons to leave, kept apart
The point: eviction is about room, expiry is about truth. They are different reasons, so put them in different classes. A layer with a clock goes around the cache, and the cache does not change.
A layer that knows the time
The value is stored together with its deadline. A dead entry is never given out. In Python add from heapq import heappush, heappop at the top.
class ExpiringCache: """Adds a time to live to any cache with get, peek, put and remove.""" def __init__(self, cache, ttl, now): self._cache = cache self._ttl = ttl self._now = now # a function: tests pass their own clock self._due = [] # heap of (deadline, number, key) self._number = 0 def get(self, key, default=None): entry = self._cache.peek(key) if entry is None: return default value, deadline = entry if self._now() >= deadline: self._cache.remove(key) # lazy: found dead, buried on the spot return default self._cache.get(key) # alive, so this counts as use return valueLines 4 to 6
It receives a cache and does not create one. So it works around the plain, the locked or the counting cache.
Why it is built this way
- Lazy removal alone is already correct: no caller ever sees old data.
- The deadline is stored, not the age. One comparison, no subtraction.
Three ways to remove the dead
| Way | Cost | Weakness |
|---|---|---|
| Lazy, when somebody asks | One comparison for each get | Keys nobody asks for keep their place |
| Background, every so often | A thread and a lock | Between two runs memory is taken |
| Both | Both | More code. The usual answer, and what Redis does: on access, and by sampling keys with an expiry |
Six details that interviewers like
- 1
Monotonic clock
time.monotonic,System.nanoTime,steady_clock. The wall clock may jump when it is corrected. - 2
Rewritten keys grow the heap
A key written a million times leaves a million heap entries until their deadlines pass. Rebuild the heap when it is, say, twice the size of the cache.
- 3
Everything expires at once
Ten thousand entries loaded at start die in the same second. Add a random part to each deadline. More on cache TTL.
- 4
Eviction prefers the living?
A full cache may evict a good entry while dead ones hold places. Sweep a few before you evict.
- 5
The stored clock
expiresAtas a final field in the node makes updating a value without a new node impossible. Either replace the node, or let the deadline change under the lock. - 6
Stop the thread
A cleanup thread keeps the program and the cache alive. Make it a daemon and give the cache a close method, or do the sweep in put.
Where does expiry live?
BreaksA background thread only
- How
- Every minute it removes what is old.
- Limit
- For up to a minute callers get data that should be gone.
- Choose when
- Never alone.
WorksInside the node and the cache
- How
expiresAtin Node, checks in get.- Limit
- Each feature adds a field and a branch to the core.
- Choose when
- One cache, one feature.
StrongA layer, lazy plus a bounded sweep
- How
- As above.
- Limit
- The core needs peek and remove.
- Choose when
- Features must combine.