AAI Agentic Handbook
Problem 71 · Object & System Design

In-Memory Key-Value Store with TTL (Lazy + Active Expiry)

MediumClassic DSA & systems
01Problem

Build a KV store with set(key, value, ttl=None), get(key), delete(key), and sweep() that actively reclaims expired keys. Expired keys must never be returned.

02Key insight

Lazy expiry on read guarantees correctness; active expiry via a min-heap of (expire_at, key) bounds memory for keys never read again. Heap entries can be stale after overwrites, so validate against the live record before deleting.

03Solution

Try it first.

TimeO(1) get; O(log n) set; O(k log n) sweep
SpaceO(n + heap entries)
tests.py · 3 passing
tests.pypython10 lines
clock = [0.0]
s = TTLStore(now=lambda: clock[0])
s.set("a", 1, ttl=5); s.set("b", 2, ttl=10); s.set("c", 3)
clock[0] = 5
assert s.get("a") is None and s.get("b") == 2
s.set("b", 22, ttl=100)          # overwrite makes old heap entry stale
clock[0] = 50
assert s.sweep() == 0 and s.get("b") == 22 and len(s) == 2
clock[0] = 200
assert s.sweep() == 1 and s.get("c") == 3 and len(s) == 1
04Staff-level follow-up

Heap grows with overwrites; at scale Redis instead samples 20 random TTL keys per cycle and repeats if >25% expired, trading precision for O(1) memory overhead. A timing wheel is another option.