Library/Coding patterns that get asked/Building a small system

Caches: LRU order and time limits

115 min6 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Say a cache class's operations, their costs, its invariants and its edge cases before you write code
  • Build an LRU cache with O(1) get and put from a dict and a doubly linked list, then again with OrderedDict
  • Expire entries by time with a clock you pass in, on each read and with a heap sweep that skips stale heap entries
  • Give one class a capacity and time limits, and drop expired entries before you evict a live one
  • Answer the follow-ups with numbers: locks, surviving a crash, memory bounds and other eviction policies
Part 1 of 6about 15 min
Two limits

A TTL cache and an LRU cache

Netflix candidates report a key-value cache with a time to live, and for one of them the whole prompt was a single line (3 sources). Anthropic candidates report an LRU cache that comes in parts (2 reports). They start like this:

A cache with a time to live

Build TTLCache. put(key, value, ttl) stores a value that stays live for ttl seconds. get(key, default=None) returns a live value, or default. Read the time from a clock you're given, so a test can move it by hand.

TimeCallReturns
0put("a", 1, ttl=10)
9.9get("a")1
10get("a")None, because it was written at 0 with a TTL of 10

An LRU cache

Build LRUCache(capacity). get(key) returns the value and makes the key the most recently used. put(key, value) adds or updates a key, and when a new key overflows the cache, the least recently used entry goes.

Call, with capacity 2Returns
put("a", 1), then put("b", 2)
get("a")1, and now b is the least recently used
put("c", 3)evicts b
get("b")None

Each one grows from there. The TTL cache adds cleanup that costs only what it removes, then a size limit. The LRU cache adds a key for a function call's arguments, then a log on disk so the cache survives a crash.

You don't write them yet. Both rest on the two limits every cache has: it runs out of room, and its copies go stale, and the lesson starts there. At the end you solve each problem, level by level, in an interview simulation with a timer: 45 minutes for the TTL cache and 60 for the LRU cache.

This lesson builds on the database lesson's records and time windows, and on two coding patterns: a dict for every lookup, and a heap of deadlines from the heaps lesson for the expiry sweep.

A cache can't keep everything: it runs out of room, and copies go stale

A cache keeps copies of answers that are slow to get: a database row, a page from another service, the result of an expensive function. When the same request comes again, the cache answers it, and the slow part is skipped.

A hit gives back what was stored. A miss is allowed: the caller goes to the real source.

What a cache can't promise is to keep everything, for two reasons, and every cache question in an interview is about one or both:

  • Memory is finite. When the cache is full and a new key arrives, an entry has to go. The rule that picks it is the eviction policy. LRU, least recently used, evicts the entry nobody has used for the longest time.
  • Copies go stale. The real data changes, so an entry stops being valid after a while. A time to live (TTL) is how long an entry may be served after it was written. After that it has expired, and a read must treat it as a miss.

Try the first limit before the figures show both:

Predict

Capacity 3 holds a, b and c, used in that order. put("d", 4) arrives, and the cache evicts the least recently used entry. Which key goes?

Pick an answer above to see the rest

Say the class before you write it

In a design-a-class question, how you get to the code counts as much as the code. Before you type, say the operations and their costs, the state, the invariants and the edge cases. Here they are for an LRU cache with a fixed capacity.

get and put must both be O(1) on average, so nothing may search

All three must cost O(1):

OperationWhat it does
get(key, default=None)returns the value, and key becomes the most recent. A miss returns default and changes nothing
put(key, value)inserts or updates, and key becomes the most recent. A new key in a full cache first evicts the least recent
len(cache)how many entries are stored

O(1) means the cost doesn't grow with n, the number of entries. That rules out anything that searches. It's O(1) on average, because get and put each start with a dict lookup.

The class must answer two questions fast. Where is this key? A dict answers that. Which key was used longest ago? That needs an order, and most of this lesson is about keeping that order cheap.

The editor holds CountingCache, a dict with two counters, hits and misses. The share of hits is how you judge a real cache. Write its get, so a miss counts and returns default and stores nothing.

Three invariants and five edge cases are your test plan

Invariants are facts that must hold after every operation. Say them, then check them in your tests:

  1. len(cache) <= capacity.
  2. The map and the order hold exactly the same keys.
  3. The order is by last use, oldest first.
Predict

A cache stores None for a key, and get(key) returns None. Hit or miss?

Pick an answer above to see the rest
Predict

lru_cache(maxsize=0) wraps square, and square(3) runs twice. How many hits?

Pick one to see what it prints.
Pick an answer above to see the rest

In LRU, a get can change which key a full cache evicts

In an LRU cache, a read counts as a use, and that changes what gets evicted.

Predict

Capacity 2: put a, put b, get a, then put c. Which key does put("c", 3) evict?

Pick an answer above to see the rest
Predict

Same calls on a FIFO cache: put a, put b, get a, then put c. Which key does put("c", 3) evict?

Pick an answer above to see the rest
Part 1 done
Part 2 of 6about 21 min
The LRU order

A list keeps the order, but moving a key in it costs O(n)

list.remove and list.pop(0) both touch O(n) keys

The obvious version keeps the values in a dict and the order in a list, oldest first:

class SlowLRU:
    def __init__(self, capacity):
        self.capacity, self.data, self.order = capacity, {}, []

    def get(self, key, default=None):
        if key not in self.data:
            return default
        # searches the list for key
        self.order.remove(key)
        self.order.append(key)
        return self.data[key]

    def put(self, key, value):
        if key in self.data:
            self.order.remove(key)
        elif len(self.data) >= self.capacity:
            # shifts every key behind it
            del self.data[self.order.pop(0)]
        self.data[key] = value
        self.order.append(key)

It passes the trace. The two marked lines are the problem:

Predict

The order list holds 100,000 keys. How many of them does order.pop(0) move?

Pick an answer above to see the rest
Predict

At n = 100,000 the list's get took 304 µs, but its evicting put only 16.1 µs. Both shift keys. What makes get slower?

Pick an answer above to see the rest

Build the LRU order from a dict and a doubly linked list

The fix is two structures working together. Start with the list.

Two sentinel nodes remove the special cases for an empty list and its ends

class Node:
    def __init__(self, key=None, value=None):
        self.key, self.value = key, value
        self.prev = self.next = None


# sentinels: they hold no entry
head, tail = Node(), Node()
# an empty list
head.next, tail.prev = tail, head
The list, empty and then holding three entries
nodes
emptyheadtaila, b, cheadabctail

head.next is the oldest use, and tail.prev the newest. Each node points both ways.

A node holds a key, a value and two pointers: prev to the node before it, and next to the node after it. With both pointers, a node you're holding can be taken out in O(1), because both its neighbours are right there. A singly linked list can't do that: a node doesn't know who points at it.

head and tail are sentinels: dummy nodes that never hold an entry and never leave. So every real node always has a node on both sides, and there's no special case for an empty list, the first node or the last. The list is empty when head.next is tail.

The editor holds Node and an empty list between head and tail. Write is_empty(head, tail), and keys_oldest_first(head, tail), which walks from head.next to tail.

Every LRU operation comes down to two moves on that list.

Predict

Push back sets four pointers. Which one must you read before you overwrite it?

Pick an answer above to see the rest

The dict maps each key to its node

With the list in place, the cache class ties it to a dict.

class LRUCache:
    def __init__(self, capacity):
        if capacity < 1:
            raise ValueError("capacity must be at least 1")
        self.capacity = capacity
        # key -> its node
        self.nodes = {}
        # oldest is head.next, newest is tail.prev
        self.head, self.tail = Node(), Node()
        self.head.next, self.tail.prev = self.tail, self.head

    def _unlink(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def _push(self, node):
        last = self.tail.prev
        last.next, node.prev = node, last
        node.next, self.tail.prev = self.tail, node

    def get(self, key, default=None):
        node = self.nodes.get(key)
        if node is None:
            return default
        # a hit is a use: move it to newest
        self._unlink(node)
        self._push(node)
        return node.value

The dict holds each key's node, so finding a key's place in the order is one lookup. Here is the cache after the trace's first three calls, put("a", 1), put("b", 2) and get("a"):

Key in self.nodesIts nodePlace in the list
"b"b 2head.next, the oldest use
"a"a 1tail.prev, the newest use

Notice that get writes. Every hit rewrites six pointers, two to unlink and four to push back. That matters the moment two threads share the cache, which comes up in the follow-ups.

The LRUCache in the editor has the same __init__, _unlink and _push as above, and its get returns the right values. A full cache still evicts the wrong key. Fix get.

A put has three cases, and only a new key in a full cache evicts

  • The key is stored. Set the new value and move its node to newest. Never evict: the cache isn't growing.
  • A new key, and the cache is full. Take head.next, the oldest, off the list, and delete its key from the map. Then add the new key, as in the next case.
  • A new key. Make a node, map the key to it, and push it back.

Here is the full case, as the trace's put("c", 3) arrives:

Predict

Evicting takes head.next off the list, then deletes its key from the map. Where does it get that key?

Pick an answer above to see the rest

A check method walks the list, with a step limit

Make the invariants executable. A check method walks the list and compares it with the map:

    def check(self):
        keys, node = [], self.head.next
        while node is not self.tail:
            assert node.next.prev is node, "a forward link has no matching backward link"
            keys.append(node.key)
            assert len(keys) <= self.capacity, "more nodes than capacity, or a cycle"
            node = node.next
        assert len(keys) == len(self.nodes) and set(keys) == set(self.nodes), "the map and the list disagree"

The second assert is a step limit, and it isn't decoration. A list can be broken in a way that a walk never leaves:

Predict

A walk collects keys from head until it reaches tail. A bug left c.next pointing back at b. What happens?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 11 min
OrderedDict

OrderedDict gives you the same order in a few lines

Python already ships a dict that keeps an order you can change.

With the newest on the right, move_to_end marks a use and popitem(last=False) evicts the oldest

from collections import OrderedDict

d = OrderedDict.fromkeys("abc")
d["a"] = 10
print(list(d))
d.move_to_end("a")
print(list(d))
print(d.popitem(last=False))
print(d.popitem())
Predict

popitem() with no argument: which end of the OrderedDict does it take?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

This OrderedDict put stores the new key first and evicts after. Which test decides that it must evict?

Pick an answer above to see the rest

A plain dict can fake the order, but its evictions slow down until it rebuilds its table

A plain dict keeps insertion order too. You can fake both moves: d[k] = d.pop(k) for move_to_end, and next(iter(d)) for the oldest key. In the same benchmark, get stayed fast: 0.23 µs at 100,000 entries. Evicting didn't, because of where a dict keeps its entries:

Predict

A plain dict fakes the LRU order, and next(iter(d)) finds the oldest key. Why do its evictions get slower as they go on?

Pick an answer above to see the rest

Keeping the order cost 137 to 180 bytes per entry, against a plain dict's 84

The order isn't free. Here is what each version costs in memory.

Predict

A Node object gets __slots__ = ("key", "value", "prev", "next"). What does that save?

Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 21 min
Time limits

Expire entries by time, with a clock you pass in

Now the second question: when does an entry stop being valid? Each entry gets a ttl in seconds when it's written.

Store when an entry expires: it's live while t <= now < t + ttl

put("a", 1, ttl=10) at time 0 stores expires_at = 10Interactive
024681012
a
● the start is in. ○ the end is out.
0 <= 10 < 10 is false, so at 10 it's gone.

Store when it expires, not how long it lives. Save expires_at = now + ttl with the value. A read then compares one number with the current time. ttl=None stores expires_at=None, an entry that never expires.

Decide the boundary before you write a line. An entry written at time t with time to live ttl is live while t <= now < t + ttl. So the entry above is live at 9, and at exactly 10 it's gone. The first practice problem uses the same rule. Get it backwards and every test at the boundary fails.

Predict

a is written at time 0 with ttl=10, then again at time 8 with ttl=10. When does it expire?

Pick an answer above to see the rest

Pass the clock in, so a test can move time by hand

A TTL cache reads the time. Where it reads it from decides whether you can test it.

Predict

time.time() and time.monotonic() both give seconds. Which one can jump backwards?

Pick an answer above to see the rest

Lazy expiry: a get deletes the expired entry it finds, and nothing else does

Lazy expiry is the simplest way to honor a TTL: check on every read. A get that finds an expired entry deletes it and returns the default, as if it was never there. Redis does this too. Its docs say it expires keys in a passive way and an active way, and the passive way is this check on access.

Predict

Write 100,000 entries at time 0 with ttl=60. At time 61, read 1,000 of them. With lazy expiry only, how many expired entries are still stored?

Pick an answer above to see the rest

Sweep with a heap, so a sweep touches only the heap entries that are due

Scanning every entry costs O(n), however few have expired

The fix for entries nobody reads is a sweep: a purge() that removes everything expired. It runs on a timer, or when the cache needs room. The obvious sweep walks every entry and checks it. That's O(n) per sweep, however few entries have expired.

Here are n entries written at time 0, 10 of them with ttl=5 and the rest with ttl=1000, swept once at time 10. A full scan against the heap version below, median of 5 runs, same laptop:

EntriesScan every entryPop from a heap
10,0000.83 ms0.015 ms
100,0007.99 ms0.034 ms
1,000,00077.2 ms0.134 ms

Each sweep removed the same 10 entries. The scan's time grew with every entry it had to look at.

In the editor, write that scan as scan_purge(entries, now): delete every expired entry and return how many went. entries maps each key to (value, expires_at), as in TTLCache.

A min-heap keeps the soonest expiry at heap[0]

A sweep should cost what it removes. That needs the entries in expiry order, soonest first, and a min-heap is the tool: a list that heapq keeps arranged so the smallest item is always heap[0]. heapq.heappush adds an item in O(log n), and heapq.heappop removes the smallest in O(log n), where n is the heap's size.

Predict

The heap holds expiries 3 (b), 10 (a) and 14 (c). purge() runs at time 10. How many heap entries does it pop?

Pick an answer above to see the rest

A count in each heap entry stops a tie from comparing keys

Heap items are tuples, compared one field at a time:

import heapq

heap = []
heapq.heappush(heap, (5, "a"))
heapq.heappush(heap, (5, 7))
Predict

heappush (5, "a"), then (5, 7). What happens?

Pick one to see what it prints.
Pick an answer above to see the rest

A heap entry counts only if its key is still stored with that expiry

A key written again gets a new heap entry, and the old one stays behind. So does the heap entry of a key that was deleted or evicted. You can't fish them out: the heapq docs explain that removing an entry or changing its priority would break the heap's structure. So leave them, and check each one as it comes off:

TimeCallHeap afterStored a expires at
0put("a", 1, ttl=5)(5, 0, a)5
1put("a", 2, ttl=100)(5, 0, a), (101, 1, a)101
5purge()(101, 1, a)101

At time 5 the sweep pops (5, 0, a). The stored a expires at 101, not 5, so that heap entry is stale: a leftover. The sweep skips it and deletes nothing. A sweep that trusted it would have deleted a live entry with 96 seconds left.

So a popped (expires_at, count, key) is real only if the key is still stored with that same expires_at. Otherwise, skip it.

Predict

1,000 keys, each written 1,000 times with a one-hour TTL. How many heap entries pile up?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 19 min
Both limits

Capacity and time limits in one class: a new key in a full cache sweeps first, then evicts

Recency and expiry are two different orders over the same entries

Now give the time-limited cache a capacity too. The entries then carry two orders at once:

Predict

At time 10 the cache holds c, a, b, oldest use first. They expire at 50, 90 and 11. A new key needs room, and nothing has expired. Which key goes?

Pick an answer above to see the rest

A new key in a full cache sweeps first, and evicts only if it's still full

Capacity 2. At time 0, put("a", 1, ttl=100), then put("b", 2, ttl=5). At time 10, put("c", 3):

StepStored, oldest use first
beforea (expires at 100), b (expires at 5): full
1. purge()a (expires at 100): b expired at 5
2. still full?no, so nothing live is evicted
3. store ca (expires at 100), c (never): put returns None

The rule for a put of a new key into a full cache is sweep first, then evict. An expired entry still takes a slot until something removes it. Expired entries are dead weight, so they all go before anything live. Only if the cache is still full does the least recently used entry go.

When it does evict, it goes by last use, not by expiry. The least recently used entry goes even when another live entry expires sooner.

A put of a key that's already stored never evicts, expired or not. A get that finds a live entry moves it to the newest end, the same as before.

The heap may hold extra entries, but it must never miss a real one

The invariants grow by one:

  1. len(entries) <= capacity.
  2. The OrderedDict is in order of last use.
  3. Every stored entry with an expires_at has a heap entry with the same key and time. The heap can hold extra, stale entries. It must never miss a real one, or that entry is never swept.

The third is what lets len(cache) count only live entries without walking them: purge first, and whatever is still stored is live.

The editor holds TTLCache with a capacity, and its purge and get are done. Fill in the two gaps in put: sweep, then evict if it's still full, and make the key the newest.

CheckpointSweep, then evict

Fill in the two gaps in put. Before storing a new key in a full cache, purge(), and if it's still full, evict the least recently used entry and remember its key in evicted. After storing, make key the most recent, whether it's new or rewritten.

A worked example: design a cache with TTL

Here is the one-line prompt from the reports, solved the way you'd do it in the room.

Clarify for two minutes, and say what you'll assume

Predict

Every entry gets the same TTL. Do you still need the heap?

Pick an answer above to see the rest

State the costs, then write it

Say the class in a minute:

  • put(key, value, ttl=None) returns the evicted key or None. It costs O(log n) for the heap push, plus an occasional sweep.
  • get(key, default=None) is O(1) on average.
  • purge() is O(k log n) for the k heap entries it pops.
  • len(cache) sweeps, then counts.

The invariants are the three above. Then write it:

import heapq
import itertools
import time
from collections import OrderedDict


class TTLCache:
    def __init__(self, capacity, default_ttl=None, clock=time.monotonic):
        if capacity < 1:
            raise ValueError("capacity must be at least 1")
        if default_ttl is not None and default_ttl <= 0:
            raise ValueError("default_ttl must be positive")
        self.capacity, self.default_ttl, self.clock = capacity, default_ttl, clock
        # key -> (value, expires_at), least recently used first
        self.entries = OrderedDict()
        # (expires_at, count, key), soonest first
        self.heap = []
        # breaks ties, so two keys are never compared
        self.count = itertools.count()

    def get(self, key, default=None):
        entry = self.entries.get(key)
        if entry is None:
            return default
        value, expires_at = entry
        if expires_at is not None and self.clock() >= expires_at:
            # lazy expiry: a read that finds it dead drops it
            del self.entries[key]
            return default
        # a hit is a use
        self.entries.move_to_end(key)
        return value

    def put(self, key, value, ttl=None):
        ttl = self.default_ttl if ttl is None else ttl
        if ttl is not None and ttl <= 0:
            raise ValueError("ttl must be positive")
        now, evicted = self.clock(), None
        if key not in self.entries and len(self.entries) >= self.capacity:
            # the expired go first: they're dead anyway
            self.purge()
            if len(self.entries) >= self.capacity:
                evicted, _ = self.entries.popitem(last=False)
        expires_at = None if ttl is None else now + ttl
        self.entries[key] = (value, expires_at)
        self.entries.move_to_end(key)
        if expires_at is not None:
            heapq.heappush(self.heap, (expires_at, next(self.count), key))
        return evicted

    def purge(self):
        now, removed = self.clock(), 0
        while self.heap and self.heap[0][0] <= now:
            expires_at, _, key = heapq.heappop(self.heap)
            entry = self.entries.get(key)
            # skip stale heap entries
            if entry is not None and entry[1] == expires_at:
                del self.entries[key]
                removed += 1
        return removed

    def __len__(self):
        self.purge()
        return len(self.entries)

    def check(self):
        assert len(self.entries) <= self.capacity, "more entries than capacity"
        scheduled = {(key, expires_at) for expires_at, _, key in self.heap}
        for key, (_, expires_at) in self.entries.items():
            assert expires_at is None or (key, expires_at) in scheduled, f"{key!r} has no heap entry for its expiry"

A ttl of 0 or less raises before anything is stored, so a bad call leaves the cache as it was.

TTLStore in the editor is a small store with the TTL rules of put above: a default_ttl, and a ttl of 0 or less raises. Its put lets ttl=0 through. Find the line and fix it.

Trace it out loud with a fake clock

The cache has capacity=2. Each entry shows its key, value and expires_at, oldest use first:

tCall, and what it returnsEntries after
0put("a", 1, ttl=10)a 1 10
0put("b", 2, ttl=3)a 1 10 b 2 3
1get("a") returns 1b 2 3 a 1 10
4put("c", 3, ttl=10)a 1 10 c 3 14
5put("d", 4) returns "a"c 3 14 d 4 None
6get("c") returns 3d 4 None c 3 14
14len(cache) returns 1d 4 None
Each entry's life
a evicted at 5
b expired at 3
c expires at 14
d never expires
0351014
seconds

Narrate the three interesting rows:

  • At time 4 the cache is full, but b expired at 3. The sweep frees its slot, and nothing live is evicted.
  • At time 5 nothing has expired, so the least recently used entry, a, is evicted, even though it had 5 seconds left. Its heap entry (10, 0, a) is now stale.
  • At time 14 the sweep pops (10, 0, a), finds no a stored, and skips it. Then it pops (14, 2, c) and deletes c, which expires at exactly 14. Only d is left, and it never expires.

In the editor, write stale_count(entries, heap): how many heap entries no longer match what's stored. The editor holds the cache after put("d", 4): c and d are stored, and the heap still holds the entry of a.

Test it against a brute-force version too simple to be wrong

A brute-force version keeps a plain list, filters out expired entries before it does anything, and finds keys by scanning. It's slow and obviously right. Run both on the same random calls and compare every answer:

import random


def brute_force(capacity, clock):
    # [key, value, expires_at], least recent first
    items = []

    def live():
        items[:] = [it for it in items if it[2] is None or clock() < it[2]]

    def get(key, default=None):
        live()
        for i, it in enumerate(items):
            if it[0] == key:
                items.append(items.pop(i))
                return it[1]
        return default

    def put(key, value, ttl=None):
        new = [key, value, None if ttl is None else clock() + ttl]
        for i, it in enumerate(items):
            if it[0] == key:
                items.pop(i)
                items.append(new)
                return None
        live()
        evicted = items.pop(0)[0] if len(items) >= capacity else None
        items.append(new)
        return evicted

    return get, put


mismatches = 0
for seed in range(300):
    rng, clock = random.Random(seed), FakeClock()
    capacity = rng.choice([1, 2, 3, 5])
    cache, (get, put) = TTLCache(capacity, clock=clock), brute_force(capacity, clock)
    for step in range(200):
        clock.now += rng.choice([0, 0, 1, 2])
        key, ttl = rng.choice("abcdefg"), rng.choice([None, 1, 2, 5, 10])
        if rng.random() < 0.5:
            same = cache.put(key, step, ttl=ttl) == put(key, step, ttl=ttl)
        else:
            same = cache.get(key, "miss") == get(key, "miss")
        cache.check()
        if not same:
            mismatches += 1
            break
print("seeds with a mismatch:", mismatches)

It printed seeds with a mismatch: 0. To be sure the comparison can fail, break one line at a time and run it again:

Predict

Break one line at a time. Which bug did the random test catch in all 300 seeds?

Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 28 min
Follow-ups

What interviewers ask next

Make it thread-safe: in an LRU cache, a read is a write

Two threads calling get and put at once can interleave their pointer changes. And get writes too: every hit moves a node. Here is one order of steps that loses a node, with two gets and no put at all:

The list holds a, b, c. Thread 1 runs get("a"), thread 2 get("b"). Both unlink their node. Then both read tail.prev before either one pushes back:

Predict

Both threads read tail.prev as c, then each pushes its node after c, thread 1 first. How does the list end?

Pick an answer above to see the rest

Without a lock, 59 of 100 runs broke, and with one lock none did

Here's a measurement on this lesson's two LRU caches. In each run, 4 threads each made 20,000 random calls on 64 keys, against a cache of capacity 32:

Broken runs out of 100, with 4 threads
linked list, get and put
59
linked list, get only
6
OrderedDict, get and put
1
either, with one lock
0

No lock in the first three. The last holds one threading.Lock inside each method.

What broke:

  • Linked list, get and put: KeyError and AttributeError from half-updated nodes, and lists with too many nodes or one-way links.
  • Linked list, get only: the map and the list disagreed, because nodes fell out of the list.
  • OrderedDict: a KeyError from move_to_end, because another thread evicted the key between two steps.

Thread timing varies from run to run. An earlier run with the same calls and seeds gave 71, 4 and 2 for the unlocked caches, and 0 again with the lock. Here's the code, with the counting left out:

import random
import threading


def hammer(cache, threads=4, ops=20_000, keys=64, seed=0, only_gets=False):
    for key in range(32):
        cache.put(key, key)
    errors = []

    def work(n):
        rng = random.Random(seed * 1000 + n)
        for _ in range(ops):
            key = rng.randrange(keys)
            try:
                if only_gets or rng.random() < 0.5:
                    cache.get(key)
                else:
                    cache.put(key, n)
            except Exception as e:
                errors.append(type(e).__name__)
                if len(errors) > 50:
                    return

    workers = [threading.Thread(target=work, args=(n,)) for n in range(threads)]
    for w in workers:
        w.start()
    for w in workers:
        w.join()
    return errors

A run counts as broken when it raised, or failed the invariant check afterwards: check() on the linked list, and len(cache.data) <= cache.capacity on the OrderedDict. The locked runs wrap each get and put in with self.lock:. Seeds 0 to 99 give the 100 runs.

The get-only number is the one to quote. Even a cache that's only read needs the lock, because in an LRU cache a read is a write.

The OrderedDict broke differently. Its size check held in every run. But if key in data followed by data.move_to_end(key) is two steps, and another thread can evict the key in between.

The fix for both is one lock held for the whole of each public method.

functools.lru_cache handles this for you. Its docs promise that "the underlying data structure will remain coherent during concurrent updates." They also spell out the catch: "It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached."

Predict

One lock around the whole cache becomes the bottleneck. What's the usual next step?

Pick an answer above to see the rest

Key a function call so the same call always gets the same key

The second practice problem starts with a cache used the way functools.lru_cache is: it wraps a function, and the key is the call. A call arrives as a tuple args and a dict kwargs. The key has to be hashable, and the same every time for the same call. Here are three ways to build it:

import json


def flat(args, kwargs):
    return args + tuple(sorted(kwargs.items()))


def frozen(args, kwargs):
    return (args, frozenset(kwargs.items()))


def as_json(args, kwargs):
    return json.dumps([args, kwargs], sort_keys=True)


print(flat((1,), {"b": 2}), flat((1, ("b", 2)), {}))
try:
    hash(frozen(([1, 2],), {}))
except TypeError as error:
    print(error)
print(as_json((1, 2), {}), as_json((1,), {"b": 2}))
print(as_json((), {"a": 1, "b": 2}), as_json((), {"b": 2, "a": 1}))
print(as_json(((1, 2),), {}), as_json(([1, 2],), {}))
Predict

flat((1,), {"b": 2}) and flat((1, ("b", 2)), {}): one call with a keyword, one with a tuple. Same key?

Pick one to see what it prints.
Pick an answer above to see the rest

Survive a crash: log every use, and replay the log

The rest of the second practice problem asks for this, so here are the ideas, not the code. Keep an append-only log: one line per operation, written before the call returns. On restart, replay the lines in order through a fresh cache. Four things decide whether that works.

Log the hits. Replay has to rebuild the order, not only the contents:

Predict

The log holds put a, put b, get a. Replay it into a capacity-2 cache. Which key goes at the next eviction?

Pick an answer above to see the rest
Predict

The crash cut line 2 short. You append the next record without cutting line 2 off first. How many records are lost?

Pick an answer above to see the rest

Each step toward the disk costs more: write, flush, fsync

What durability costs per call, timed on the laptop's SSD under macOS, median of 5 runs of 2,000 appends of that 118-byte record:

import json
import os
import time

# 118 bytes
record = json.dumps({"op": "put", "key": "k" * 16, "value": "v" * 64}) + "\n"


def per_append(path, flush, fsync, n=2_000):
    with open(path, "a") as f:
        start = time.perf_counter()
        for _ in range(n):
            f.write(record)
            if flush:
                f.flush()
            if fsync:
                os.fsync(f.fileno())
        return (time.perf_counter() - start) / n
Predict

A plain write of the 118-byte record takes 0.21 µs. About how long with flush and os.fsync too?

Pick an answer above to see the rest

When values vary in size, bound memory in bytes, not only in entries

capacity counts entries, but a cache of 1,000 small strings and a cache of 1,000 images are not the same size. When values vary, keep a running total of their sizes, and evict until the total fits a byte budget.

Count the structure too. At 100,000 entries the measured overhead per entry was 84 to 180 bytes before any value is stored. And the stale heap entries from the sweep add up if nothing rebuilds the heap.

In the editor, write evict_to_fit(sizes, budget): pop the least recently used entries until the total size fits budget, and return their keys. sizes maps each key to its size in bytes.

Other eviction policies can win on other traffic

LRU bets that what was used recently will be used again. Three other policies:

  • FIFO evicts the oldest write.
  • LFU, least frequently used, evicts the entry with the fewest hits.
  • Random evicts a key picked at random.
Predict

Popularity moves to 1,000 new keys every 10,000 requests. Which policy's hit rate collapses?

Pick an answer above to see the rest

Spread it over machines with a hash every process agrees on

Pick the machine for a key with a hash that every process agrees on. Python's own hash() of a string changes from one interpreter to the next: hash('user:42') % 4 in six fresh interpreters gave 1, 2, 0, 3, 0 and 1. zlib.crc32(b"user:42") % 4 is 2 every time.

Plain modulo has its own problem when the cluster grows.

Predict

Keys go to machine crc32(key) % 4. You add a fifth machine and switch to % 5. About what share of keys move?

Pick an answer above to see the rest

Where this shows up

The reports behind this lesson, each with its source.

Senior+ Software Engineer in Ads, IC5 (interviewed Oct 2026, rejected): the phone screen was a key-value store with TTL.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-10-14Source

Hello Interview's Netflix timeline has the same question from a Senior candidate in early October 2026.

Prep site·Hello Interview (prep site; candidate timeline note)Source

Practice

Sources (9)
  1. collections: OrderedDict objects · Python 3.12 documentation · Oct 26, 2026
    “Move an existing key to either end of an ordered dictionary.”
  2. time: time.monotonic · Python 3.12 documentation · Oct 26, 2026
    “The clock is not affected by system clock updates.”
  3. heapq: Heap queue algorithm · Python 3.12 documentation · Oct 26, 2026
    “Removing the entry or changing its priority is more difficult because it would break the heap structure invariants.”
  4. functools: lru_cache · Python 3.12 documentation · Oct 26, 2026
    “It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached.”
  5. os: os.fsync · Python 3.12 documentation · Oct 26, 2026
    “first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.”
  6. fsync(2) · Mac OS X manual pages, Apple Developer Documentation Archive · Jun 4, 1993
    “For applications that require tighter guarantees about the integrity of their data, Mac OS X provides the F_FULLFSYNC fcntl.”
  7. EXPIRE: How Redis expires keys · Redis documentation · Sep 18, 2026
    “Redis keys are expired in two ways: a passive way and an active way.”
  8. Key eviction · Redis documentation · Sep 11, 2026
    “The Redis LRU algorithm uses an approximation of the least recently used keys rather than calculating them exactly.”
  9. Redis persistence · Redis documentation · Sep 30, 2026
    “With the default policy of fsync every second, write performance is still great.”