Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Sequence
Who calls whom, case by case
The point: draw one diagram for each case that could go differently. Four cases are the problem. The others are layers that somebody may ask for.
A hit
get finds the key
A miss
get does not find the key
A put with room, and an update
New key, then the same key again
A put that evicts
This is the diagram on the Overview. The order of the steps is the content: find, choose the victim, unlink it, remove its key, then insert.
Remove
Forget one key
Six more cases, and where they live
| Case | Flow | Page |
|---|---|---|
| Create with options | Builder collects and checks, then builds once | Builder and events |
| Miss with a loader | Miss is counted, one caller loads, the result is stored | Loading once |
| Remove with a writer | Delete in the store first, then here | Loading once |
| Expiry | Lazy at get, plus a bounded sweep | Time to live |
| Two threads | Lock, whole operation, release even on error | One lock |
| Statistics | Counters are read without stopping anybody | Metrics |