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

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

CallerLruCache- capacity: int- nodes: Map<K, Node>- order: RecencyList+ get(key): V+ peek(key): V+ put(key, value): Entry+ remove(key): bool- evict(): Entry

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

ArrowWhy this one
LruCache to RecencyList, filled diamondCreated with the cache, dies with it, shared with nobody
LruCache to Node, filled diamondThe map is the owner. An evicted node is gone
RecencyList to Node, open diamondIt links nodes it does not own
Node to Nodeprev and next point at the same class. One arrow to itself is enough on the board
No triangle anywhereNothing 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

PartHoldsComes in whenOur shape
Cache interfaceget, put, put with a lifetime, remove, containsKey, statisticsSomething wraps the cacheget, peek, put, remove
Node with time stamp and use countAccess time, count, lifetimeA policy needs themNot in the plain node. One node type with all fields pays for all policies at once
Buildercapacity, expire after write, expire after access, loader, writer, record statisticsMore than about five optionsSee Builder and events
ConcurrentLruCache extends LruCachesegments[]A measured lock problemIt holds N caches. Inheriting gives it a tenth one it never uses
TtlLruCache extends LruCacheDeadlinesData gets oldA layer around any cache, see Time to live
CacheStatshits, misses, evictions, insertions, expirations, hit rateProductionA layer, see Metrics
CacheLoader, CacheWriterload, loadAll, write, deleteThe cache hides the slow storeSee Loading once
Events and listenersHIT, MISS, INSERTION, UPDATE, EVICTION, EXPIRATIONSomebody must reactSee Builder and events

Extended for threads and policies

QuestionClass that appearsWhere it is discussed
Many threadsA lock, a concurrent map, atomic countersFAANG interview: One lock, Concurrent map
Another eviction ruleLru, Lfu, Segmented behind one interfaceFAANG interview: Other policies
Old dataExpiringCacheFAANG interview: Time to live