27/37
Part 5 of 6 · Both limitsLearn and do

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.