Build an Expiring LRU Cache with an Injectable Clock
Data Structure DesignModel answerLast updated
Design a fixed-capacity cache with least-recently-used eviction and per-entry expiry, and justify your data structures, tests and complexity.
Expiring LRU Cache
You are asked to design and implement a small in-memory cache in Python. Walk through your approach before coding, explain why you chose your data structures, and finish with unit tests and a complexity analysis.
Required behavior
- The cache is created with a fixed capacity, and optionally a default lifetime for entries.
put(key, value, ttl=None)stores a value that becomes invalidttlseconds after it was written. Ifttlis omitted, the cache default applies. If neither is set, the entry never expires.get(key, default=None)returns the stored value, ordefaultif the key is absent or its entry has expired.- When an insert would push the cache over capacity, the least recently used entry is evicted.
- Both
getandputcount as a "use" and refresh an entry's recency. - Overwriting an existing key replaces the value and restarts its lifetime.
- A non-positive capacity or a negative TTL must raise
ValueError. - Target scale is up to about 100,000 entries, so every operation should be O(1) on average.
What to deliver
- A short statement of the questions you would clarify and your assumptions.
- The design: data structures and the trade-offs behind them.
- Clean, modular Python with type hints. Time must be injectable so tests do not need
sleep. - Unit tests covering normal use and edge cases, plus a short sample run.
- Time and space complexity for each operation.
- A brief discussion of how the design would change for thread safety and for eager (proactive) expiry.
Hints
Hint 1
Which structure gives you O(1) lookup and also O(1) 'move to most-recent' and 'remove oldest'? Think about what Python's collections module offers.
Hint 2
Store an absolute expiry timestamp next to each value instead of a remaining duration, and only check it when the key is accessed. Pass the clock in as a parameter so tests can control time.
Hint 3
Decide what happens at the exact expiry instant, whether an expired entry still occupies a slot, and whether overwriting resets recency and lifetime. Write tests for each of those cases.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarify first
Confirm the contract before coding:
getandputboth refresh recency.- Overwriting a key resets its lifetime.
- Invalid capacity or TTL raises
ValueError. - Thread safety is out of scope initially, but discuss it at the end.
- Scale is around 10^5 entries, with O(1) operations.
- An entry is expired when
now >= expires_at. State this boundary choice out loud.
Design
Ordering and lookup. LRU needs a hash map plus an order that supports "move to the back" and "pop from the front" in O(1). Python's OrderedDict provides this through move_to_end and popitem(last=False). It is a hash map combined with a doubly linked list internally.
Expiry. Store (value, expires_at) per key, where expires_at is an absolute timestamp or None. Expiry is lazy: an entry is checked, and deleted if stale, only when accessed. That keeps every operation O(1).
Clock. The cache accepts a clock callable defaulting to time.monotonic. Monotonic time cannot jump backwards the way wall-clock time can. Tests supply a fake clock with an advance() method, which makes expiry tests deterministic and instant.
Trade-offs to state
| Choice | Pros | Cons |
|---|---|---|
OrderedDict | Short, well tested, O(1) | Hides pointer logic; offer to hand-roll a dict plus linked list if asked |
| Lazy expiry | All ops O(1), simple | Dead entries can hold slots, so a live entry may be evicted while a dead one stays |
| Eager expiry via min-heap | Dead entries removed promptly | put becomes O(log n); must skip stale heap entries after overwrites |
Code
import time
from collections import OrderedDict
from typing import Any, Callable, Hashable, Optional, Tuple
_Entry = Tuple[Any, Optional[float]] # (value, expires_at or None)
class ExpiringLRUCache:
def __init__(
self,
capacity: int,
default_ttl: Optional[float] = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
if capacity <= 0:
raise ValueError("capacity must be positive")
self._check_ttl(default_ttl)
self._capacity = capacity
self._default_ttl = default_ttl
self._clock = clock
self._data: "OrderedDict[Hashable, _Entry]" = OrderedDict()
def get(self, key: Hashable, default: Any = None) -> Any:
entry = self._data.get(key)
if entry is None:
return default
value, expires_at = entry
if self._expired(expires_at):
del self._data[key]
return default
self._data.move_to_end(key)
return value
def put(self, key: Hashable, value: Any, ttl: Optional[float] = None) -> None:
ttl = self._default_ttl if ttl is None else ttl
self._check_ttl(ttl)
expires_at = None if ttl is None else self._clock() + ttl
if key in self._data:
self._data.move_to_end(key)
self._data[key] = (value, expires_at)
if len(self._data) > self._capacity:
self._data.popitem(last=False)
def delete(self, key: Hashable) -> bool:
return self._data.pop(key, None) is not None
def purge_expired(self) -> int:
stale = [k for k, (_, exp) in self._data.items() if self._expired(exp)]
for k in stale:
del self._data[k]
return len(stale)
def __len__(self) -> int:
return len(self._data)
def _expired(self, expires_at: Optional[float]) -> bool:
return expires_at is not None and self._clock() >= expires_at
@staticmethod
def _check_ttl(ttl: Optional[float]) -> None:
if ttl is not None and ttl < 0:
raise ValueError("ttl must be non-negative")
Tests
import unittest
class FakeClock:
def __init__(self): self.now = 0.0
def __call__(self): return self.now
def advance(self, s): self.now += s
class TestCache(unittest.TestCase):
def setUp(self):
self.clock = FakeClock()
self.cache = ExpiringLRUCache(2, clock=self.clock)
def test_missing_returns_default(self):
self.assertIsNone(self.cache.get("x"))
self.assertEqual(self.cache.get("x", -1), -1)
def test_get_refreshes_recency(self):
self.cache.put("a", 1); self.cache.put("b", 2)
self.cache.get("a")
self.cache.put("c", 3) # evicts b
self.assertIsNone(self.cache.get("b"))
self.assertEqual(self.cache.get("a"), 1)
def test_overwrite_refreshes_recency_and_value(self):
self.cache.put("a", 1); self.cache.put("b", 2)
self.cache.put("a", 10)
self.cache.put("c", 3) # evicts b
self.assertEqual(self.cache.get("a"), 10)
self.assertIsNone(self.cache.get("b"))
def test_expiry_boundary(self):
self.cache.put("a", 1, ttl=5)
self.clock.advance(4.999)
self.assertEqual(self.cache.get("a"), 1)
self.clock.advance(0.001)
self.assertIsNone(self.cache.get("a"))
def test_overwrite_resets_ttl(self):
self.cache.put("a", 1, ttl=5)
self.clock.advance(4)
self.cache.put("a", 2, ttl=5)
self.clock.advance(4)
self.assertEqual(self.cache.get("a"), 2)
def test_invalid_arguments(self):
with self.assertRaises(ValueError):
ExpiringLRUCache(0)
with self.assertRaises(ValueError):
self.cache.put("a", 1, ttl=-1)
def test_purge(self):
self.cache.put("a", 1, ttl=1)
self.clock.advance(2)
self.assertEqual(self.cache.purge_expired(), 1)
self.assertEqual(len(self.cache), 0)
Sample run: with capacity 2, put("a",1), put("b",2), get("a"), put("c",3) leaves a and c; get("b") returns None.
Complexity
get,put,delete: O(1) average time.purge_expired: O(n) time, O(k) extra space for k stale keys.- Space: O(capacity), since at most
capacityentries are stored.
Extensions
- Thread safety: wrap each public method in a
threading.Lock. Every method mutates the order (evenget), so a reader-writer lock gives no benefit. For heavy contention, shard keys across several independent caches, each with its own lock. - Eager expiry: add a min-heap of
(expires_at, key). On eachputorget, pop heap entries whose time has passed and delete the matching key only if its storedexpires_atstill matches, which skips stale heap items left by overwrites.putbecomes O(log n) and memory grows with the number of overwrites unless the heap is periodically rebuilt. - Background sweeper: a timer thread calling
purge_expiredbounds how long dead entries linger, at the cost of lock contention.
Common mistakes
- Using
time.time()instead of a monotonic clock. - Forgetting that
getmust refresh recency. - Not resetting the TTL when overwriting a key.
- Evicting before inserting an existing key, which wrongly removes an entry on an overwrite at full capacity.
- Testing expiry with
sleep, which makes tests slow and flaky. - Giving no justification for lazy versus eager expiry.