Build an Expiry-Aware LRU Cache Without Scanning Every Key
Data Structure DesignModel answerLast updated
Design an in-memory cache that enforces capacity with LRU eviction and per-entry TTL, keeping expiration efficient without iterating all keys.
Expiry-Aware LRU Cache
Build an in-memory cache that enforces three policies simultaneously:
- Capacity limit — when the cache is full, the least-recently-used entry is evicted to make room.
- TTL expiration — every entry carries a deadline; once the current monotonic time reaches or passes that deadline, the entry is logically dead and must never be returned to callers.
- Efficient expiry cleanup — background or lazy cleanup must not scan the entire key set on every cycle.
API contract
put(key, value, ttl_ms) # insert or overwrite; ttl_ms > 0
get(key) → value | None # returns None if missing or expired;
# a hit refreshes recency but does NOT extend TTL
A successful get moves the key to the most-recently-used position. An overwriting put resets both the value and the TTL deadline and also refreshes recency.
Constraints and edge-case rules
- Capacity is measured in number of entries. An entry that has expired but has not yet been reclaimed still occupies a slot until cleaned up; it must be counted against capacity only if your chosen design would otherwise return a stale result. State your choice explicitly.
- Expired entries must never be returned, even if background cleanup has not run yet.
- Zero or negative TTL on a
putis invalid; you may throw or return an error — just state your choice. - All public operations must be safe for concurrent access across threads. State what level of consistency you guarantee (linearizable vs. something weaker) and how you achieve it.
Part 1 — Core data structures and read/write behavior
Describe the structures you use to support:
- O(1) average-case lookup, insertion, and LRU eviction.
- Separate tracking of recency order and expiration order.
- Atomic removal from every relevant structure when an entry is evicted or expired.
Walk through what happens during a get that finds an expired key, and during a put that triggers LRU eviction.
Part 2 — Expiration without a full-table scan
Propose a structure — a min-heap, timing wheel, or equivalent — that lets a background thread (or lazy get/put path) reclaim expired entries without iterating every key.
Address the following specifically:
- How do you detect and discard stale expiry records when a key has been overwritten and its old deadline entry is still queued?
- What are the memory costs and timing precision trade-offs of your chosen approach?
- How does the cleanup path interact safely with concurrent reads and writes?
Hints
Hint 1
For O(1) LRU you need two structures working together: a hash map for lookup and a doubly-linked list for recency order. Think about what node the map should store a reference to, and why that makes moving a node to the front cheap.
Hint 2
A min-heap ordered by deadline lets you check only the front element to know whether anything has expired yet. The tricky part is overwritten keys: the heap may still hold the old deadline. Store a version counter or the expected deadline alongside each heap entry so you can skip records that no longer match the live entry.
Hint 3
Locking the entire cache on every operation is correct but contention-heavy. Consider whether you can separate the lock on the recency list from other state, or use a read-write lock for gets vs. puts, and be ready to explain the trade-offs of each.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1 — Core structures
Hash map + doubly-linked list for LRU.
The standard LRU building block is a dict (or HashMap) mapping each key to a node in a doubly-linked list. The list keeps entries in recency order, with the most-recently-used node at the head and the least-recently-used at the tail. Because the map holds a direct pointer to the node, moving a node to the head after a hit is O(1): splice it out of its current position and prepend it, with no search.
Per-entry deadline field.
Each node stores (key, value, deadline) where deadline is an absolute monotonic timestamp (time.monotonic_ns() in Python, System.nanoTime() in Java). The deadline is set at insert time as now + ttl_ms * 1_000_000 and is never extended by reads.
Read path (get):
- Look up the key in the map. If absent → return
None. - Check
now >= node.deadline. If expired, remove the node from the list and the map → returnNone. This is lazy expiration; the entry is reclaimed on the access that discovers it. - Otherwise move the node to the head of the list, return its value.
Write path (put):
- If the key already exists, update
valueanddeadlinein-place and move the node to the head. This covers the overwrite case. - If the key is new and
len(map) >= capacity, remove the tail node from both the list and the map (LRU eviction), then insert the new node at the head.
Removing a node always touches both the linked list and the hash map. Keeping those two operations inside a single critical section ensures no caller ever sees a key that exists in the map but not in the list, or vice versa.
Common mistake: refreshing the TTL on a read. The contract says reads update recency, not deadline. Conflating the two means a hot key can live forever.
Part 2 — Expiration without a full-table scan
Why lazy expiration alone isn't enough.
Lazy expiration (checking the deadline on every get) handles correctness but doesn't reclaim memory for keys that are never accessed again. A cache full of cold, expired entries will reject all new writes via LRU eviction even though those slots could be freed. A background cleanup pass is needed.
Min-heap of deadlines.
Maintain a min-heap where each record is (deadline, key, version). The heap is ordered by deadline, so the front element is always the entry that expires soonest. A background thread (or a housekeeping step at the start of each put) checks the heap front:
while heap not empty and heap[0].deadline <= now:
record = heappop(heap)
node = map.get(record.key)
if node and node.version == record.version:
remove node from list and map
# else: stale record from an overwritten key — discard silently
Handling overwritten keys (the stale-record problem).
When put overwrites an existing key, the old deadline record is already queued in the heap and cannot be cheaply removed (heap removal is O(n) without an index). The fix is a version counter: each node carries a monotonically increasing integer. When a key is overwritten, the node's version increments and a new heap record is pushed with the new deadline and new version. When the old record surfaces at the heap front, the version mismatch signals that it's stale and it's discarded without touching the map.
An alternative is storing the expected deadline in the heap record and comparing it against the node's current deadline instead of a version integer — same idea, slightly less bookkeeping.
Memory and timing trade-offs.
| Approach | Memory overhead | Timing precision | Stale-record cost |
|---|---|---|---|
| Min-heap | O(n) extra heap records (bounded by total puts) | Exact to heap-pop resolution | One version check per pop |
| Timing wheel | O(buckets + entries) | Quantized to bucket width | Need back-pointer or version |
| Sorted set (e.g., Redis ZSET) | O(n log n) | Exact | Key overwrite updates in O(log n) |
A min-heap is the simplest correct choice for a single-process cache. Stale records accumulate at most one extra entry per overwrite; the heap grows at most by a constant factor, so memory stays O(total live entries + overwrites since last cleanup). If overwrites are frequent, a timing wheel with a back-pointer into each bucket is more memory-stable.
Concurrency.
All mutations — list splices, map updates, heap pushes/pops — must happen under the same lock to stay consistent. A single ReentrantLock (Java) or threading.Lock (Python) wrapping each public operation is correct and simple. For higher throughput, a read-write lock allows concurrent reads as long as no write is in progress; writes and the background cleanup thread take an exclusive lock. The background thread should acquire the same write lock when it processes the heap, so it doesn't race with concurrent put calls that might be removing or reinserting the same key.
Cleanup backlog. To bound the work done per operation, limit the background pass to a fixed number of heap pops per wakeup (e.g., 100 entries). This prevents a large expiry wave from stalling foreground operations while still making steady forward progress.
Edge cases to call out explicitly:
- Zero-capacity cache: every
putimmediately evicts, which is valid but useless. Reject in the constructor or document the behavior. - Zero or negative TTL: reject at the
putcall site with anIllegalArgumentExceptionor equivalent. - Expired entries counting against capacity: with lazy eviction they do until a
getor background pass reclaims them. State this clearly; some designs eagerly evict at expiry time instead, which changes the LRU eviction order.