Skip to content

Lesson 4 of 14 · 16m

Linked Lists and the LRU Pattern

`functools.lru_cache` is a dict plus a circular doubly-linked list — the same two-structure combo behind `OrderedDict` and Redis eviction.

Open Lib/functools.py in CPython and find _lru_cache_wrapper: a dict plus a circular doubly-linked list of [key, result, prev, next] links rooted at a sentinel. Every hit relinks the node to the front. Every eviction pops the tail. Both operations are O(1). That is the entire LRU cache — and the entire argument for why linked lists still exist.

The wrong model runs both directions. "Linked lists are interview trivia" ignores that they sit inside OrderedDict (implemented in C at Objects/odictobject.c), allocator free lists, and every LRU ever shipped. "Use linked lists like arrays" ignores that iterating a linked list is a cache-miss festival — pointer-chasing defeats the CPU prefetcher, and each node is a separate allocation. The list wins exactly one way: when you already hold the node, removing or moving it is a couple of pointer swaps — in an array the same operation is a memmove, O(n). LRU needs O(1) eviction order and O(1) lookup, which is why it's always two structures cooperating: map for get, list for recency.

Doubly-linked is the part people forget. Removing an arbitrary node needs its predecessor — with singly-linked nodes that's a traversal. The sentinel-headed circle also removes the edge cases: no null head/tail checks, every node has a prev and next, and the LRU list in functools.py exploits exactly that.

Building it yourself

from collections import OrderedDict

class LRU:
    def __init__(self, cap):
        self.cap = cap
        self.d = OrderedDict()
    def get(self, k):
        if k not in self.d:
            return None
        self.d.move_to_end(k)      # most-recent goes last
        return self.d[k]
    def put(self, k, v):
        self.d[k] = v
        self.d.move_to_end(k)
        if len(self.d) > self.cap:
            self.d.popitem(last=False)  # evict oldest — O(1)

move_to_end + popitem(last=False) are the two pointer-swap primitives the hand-rolled version does by hand. In Java the same trick is new LinkedHashMap<>(cap, 0.75f, true) — the true is accessOrder — overriding removeEldestEntry to cap size. Three lines, production LRU.

Where it runs in production

Redis eviction is the deployed version: maxmemory-policy allkeys-lru drops the least-recently-used keys when maxmemory is hit — and since Redis 4.0 it's approximate LRU, sampling a small pool of candidates per eviction rather than tracking a global list, because exact ordering at Redis scale isn't worth the bookkeeping. allkeys-lfu (also 4.0+) evicts by frequency instead of recency — pick it when hot keys stay hot rather than just recent.

The unbounded-cache leak

@lru_cache without maxsize — or plain @cache — never evicts. On keys drawn from user input (paths, IDs, query strings) that's a memory leak with a friendly API, and the object graphs cached often keep whole request structures alive. lru_cache(maxsize=1024) bounds it; unbounded caches on untrusted keys are a self-DoS. One more subtlety: lru_cache holds a lock — it's thread-safe, but contended under heavy concurrency, which is its own scaling story.

What to actually do

Need O(1) lookup + O(1) eviction? OrderedDict. Need bounded memoization? lru_cache(maxsize=N) — always with the size. Need frequency-aware eviction at scale? Redis allkeys-lfu. And when the requirement is "iterate a million elements fast," that's an array's job — reach for list, not a chain of pointers.

Field notes

  • lru_cache.cache_info() reports hits, misses, and current size — the first thing to check when a service's memory climbs.
  • A cached value keeps its whole object graph alive: memoizing a function that returns a parsed request object pins the request, its buffers, everything it references.
  • OrderedDict is implemented in C (Objects/odictobject.c) — the per-entry cost is two extra pointers, which is the whole trick's price.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.