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

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

Here the caller loads. That is called cache aside. A loading cache hides the last three steps, see Loading once.

A put with room, and an update

New key, then the same key again

The second put does not write to the map at all.

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

Removing twice is not an error. The caller wanted it gone, and it is gone.

Six more cases, and where they live

CaseFlowPage
Create with optionsBuilder collects and checks, then builds onceBuilder and events
Miss with a loaderMiss is counted, one caller loads, the result is storedLoading once
Remove with a writerDelete in the store first, then hereLoading once
ExpiryLazy at get, plus a bounded sweepTime to live
Two threadsLock, whole operation, release even on errorOne lock
StatisticsCounters are read without stopping anybodyMetrics