Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
UML design
Draw it in the order you think it
The point: draw the caller and two methods first, then the list, then the node that sits in both. The diagram fits on a quarter of the board.
The design to reach: a map that finds, a list that orders, a node in both
1/4Two verbs
Start with what the caller sees: get and put. Nothing else is needed to use a cache. peek and remove come from the layers you will put around it later.
usesowns (dies together)has (lives on)
Arrows that people mix up
| Arrow | Why this one |
|---|---|
| LruCache to RecencyList, filled diamond | Created with the cache, dies with it, shared with nobody |
| LruCache to Node, filled diamond | The map is the owner. An evicted node is gone |
| RecencyList to Node, open diamond | It links nodes it does not own |
| Node to Node | prev and next point at the same class. One arrow to itself is enough on the board |
| No triangle anywhere | Nothing is a kind of anything. A triangle between Node and LruCache, which one sometimes sees, would say that a cache is a node |
The large version
Some rounds expect the picture of a whole caching library: an interface, variants, a builder, loaders, writers, statistics, events. Know it, and know which question brings each part in.
A full library, as it is often drawn
Keep or drop
| Part | Holds | Comes in when | Our shape |
|---|---|---|---|
| Cache interface | get, put, put with a lifetime, remove, containsKey, statistics | Something wraps the cache | get, peek, put, remove |
| Node with time stamp and use count | Access time, count, lifetime | A policy needs them | Not in the plain node. One node type with all fields pays for all policies at once |
| Builder | capacity, expire after write, expire after access, loader, writer, record statistics | More than about five options | See Builder and events |
| ConcurrentLruCache extends LruCache | segments[] | A measured lock problem | It holds N caches. Inheriting gives it a tenth one it never uses |
| TtlLruCache extends LruCache | Deadlines | Data gets old | A layer around any cache, see Time to live |
| CacheStats | hits, misses, evictions, insertions, expirations, hit rate | Production | A layer, see Metrics |
| CacheLoader, CacheWriter | load, loadAll, write, delete | The cache hides the slow store | See Loading once |
| Events and listeners | HIT, MISS, INSERTION, UPDATE, EVICTION, EXPIRATION | Somebody must react | See Builder and events |
Extended for threads and policies
| Question | Class that appears | Where it is discussed |
|---|---|---|
| Many threads | A lock, a concurrent map, atomic counters | FAANG interview: One lock, Concurrent map |
| Another eviction rule | Lru, Lfu, Segmented behind one interface | FAANG interview: Other policies |
| Old data | ExpiringCache | FAANG interview: Time to live |