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

Shards

N small caches, N locks, N orders

The point: split by the hash of the key into independent caches. Threads that use different shards never meet. You pay with one global order.

The whole idea in code

Python
from collections import OrderedDictfrom threading import Lock, Threadclass LockedLru:    def __init__(self, capacity):        self._capacity, self._data, self._lock = capacity, OrderedDict(), Lock()    def get(self, key, default=None):        with self._lock:            if key not in self._data:                return default            self._data.move_to_end(key)            return self._data[key]    def put(self, key, value):        with self._lock:            if key in self._data:                self._data.move_to_end(key)            elif len(self._data) == self._capacity:                self._data.popitem(last=False)            self._data[key] = value    def __len__(self):        with self._lock:            return len(self._data)class ShardedLru:    def __init__(self, capacity, shards):        if shards < 1 or shards & (shards - 1) or capacity < shards:            raise ValueError("shards must be a power of two and not above the capacity")        self._mask = shards - 1        base, more = divmod(capacity, shards)               # 10 in 4: 3, 3, 2, 2        self._shards = [LockedLru(base + (i < more)) for i in range(shards)]    def _shard(self, key):        h = hash(key)        return self._shards[(h ^ (h >> 16)) & self._mask]   # mix: low bits alone may repeat    def get(self, key, default=None):        return self._shard(key).get(key, default)    def put(self, key, value):        self._shard(key).put(key, value)    def __len__(self):                                      # a sum over moments, not one moment        return sum(len(s) for s in self._shards)cache = ShardedLru(1000, 8)def work(name):    for i in range(5000):        cache.put(f"{name}-{i}", i)        cache.get(f"{name}-{i - 3}")threads = [Thread(target=work, args=(n,)) for n in range(8)]for t in threads:    t.start()for t in threads:    t.join()print(len(cache))                                           # 1000: every shard is full, none above
Each shard is a complete LRU cache with a lock. The outer class only chooses. Nothing in the inner class changed.
Edit and run it in your browser
DecisionWhy
A power of twohash & mask chooses the shard, and the sign of the hash does no harm
Mix the high bits inMany hashes differ only there. Integers hash to themselves, and numbers that are multiples of 8 would all meet in shard 0
Share the capacity out exactly10 in 4 shards is 3, 3, 2, 2. Rounding up gives 12
Not more shards than capacityA shard of size zero can hold nothing
Holds shards, does not extend the cacheA sharded cache has no order of its own

What you lose

Suppose 1,000 places in 8 shards, 125 each. Keys do not spread evenly. If 1,000 keys are thrown at 8 shards, a shard gets 125 on average with a standard deviation of about 10.

Spread of keys over shards

σ=1000⋅18⋅78≈10.5\sigma = \sqrt{1000 \cdot \tfrac{1}{8} \cdot \tfrac{7}{8}} \approx 10.5
So a shard with 146 of its keys, two deviations up, evicts 21 of them although the cache as a whole would have had room. With 100 places in 8 shards the same effect is far larger in proportion.
OperationOne cacheShards
get, putOne lockOne of N locks
Which entry is oldest?The last nodeNobody knows
sizeExactA sum of numbers from different moments
clearOne stepN steps, others see it half done
Weighted limitOne totalOne total each: a big value may not fit any shard
One very hot keyWaits for the lockStill waits: it lives in one shard

How many?

Enough that threads rarely meet, and not so many that shards get tiny. A common start is a few times the number of cores. RocksDB splits its block cache into at most 64 shards by default and does not share room between them. Measure, then choose.

Choosing

How do you divide the capacity?

BreaksEvery shard gets the full capacity
How
It is simple.
Limit
N times the memory that was promised.
Choose when
Never.
WorksEqual parts
How
As in the code.
Limit
Early evictions in a crowded shard.
Choose when
The default.
StrongEqual parts, and watch each shard
How
Count hits and evictions for each, and alarm on a large difference.
Limit
More numbers to look at.
Choose when
Production: a bad hash shows up here first.