22/37
Part 4 of 6 · Time limitsLearn and do

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