← Back to Python, page 4

python-0065 · Hard senior

Design an in-process cache with time-to-live expiry and a size limit.

Use an OrderedDict keyed by the cache key, storing the value with its expiry time. On get, drop the entry if it has expired, otherwise move it to the end to mark it recently used. On set, insert or update and evict from the front while the cache exceeds its size. Add a lock if threads share it, and inject the clock for tests.

Full answer
python
from collections import OrderedDict

class TTLCache:
    def __init__(self, maxsize, ttl, clock):
        self.maxsize, self.ttl, self.clock = maxsize, ttl, clock
        self.data = OrderedDict()
    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires = item
        if self.clock() >= expires:
            del self.data[key]
            return default
        self.data.move_to_end(key)
        return value
    def set(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        while len(self.data) > self.maxsize:
            evicted, _ = self.data.popitem(last=False)
            print("evicted", evicted)

now = [0]
c = TTLCache(maxsize=2, ttl=10, clock=lambda: now[0])
c.set("a", 1); now[0] = 5; c.set("b", 2)
now[0] = 11
print(c.get("a"), c.get("b"))
c.set("c", 3); c.set("d", 4)
print(list(c.data))

Output:

text
None 2
evicted b
['c', 'd']

The fake clock makes expiry deterministic. At time 11, 'a' (stored at time 0 with a TTL of 10) has expired, so get returns None and deletes it, while 'b' is still valid. Adding 'c' fills the two slots, and adding 'd' evicts 'b', the least recently used entry, leaving 'c' and 'd'.

Points to discuss:

  • Complexity: OrderedDict gives O(1) get, set, move and pop.
  • Concurrency: guard operations with threading.Lock; for asyncio, avoid awaiting inside critical sections.
  • Stampedes: when a popular key expires, many callers recompute at once; a per-key lock or 'serve stale while refreshing' helps.
  • Memory: size limits by count are simple; limits by bytes need size estimates.
  • Multiple processes or servers need a shared cache such as Redis instead.

functools.lru_cache has no TTL, which is why a custom structure or a library like cachetools is used when expiry matters.

python
from collections import OrderedDict

class TTLCache:
    def __init__(self, maxsize, ttl, clock):
        self.maxsize, self.ttl, self.clock = maxsize, ttl, clock
        self.data = OrderedDict()
    def get(self, key, default=None):
        item = self.data.get(key)
        if item is None:
            return default
        value, expires = item
        if self.clock() >= expires:
            del self.data[key]
            return default
        self.data.move_to_end(key)
        return value
    def set(self, key, value):
        self.data[key] = (value, self.clock() + self.ttl)
        self.data.move_to_end(key)
        while len(self.data) > self.maxsize:
            evicted, _ = self.data.popitem(last=False)
            print("evicted", evicted)

now = [0]
c = TTLCache(maxsize=2, ttl=10, clock=lambda: now[0])
c.set("a", 1); now[0] = 5; c.set("b", 2)
now[0] = 11
print(c.get("a"), c.get("b"))
c.set("c", 3); c.set("d", 4)
print(list(c.data))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • OrderedDict gives O(1) LRU operations
  • Store expiry with each value
  • Inject the clock for testing
  • Lock for thread safety
  • Plan for stampedes

Common mistakes

  • Scanning all entries on every access
  • Using real time in tests

Follow-ups

  • How would you add stale-while-revalidate?
  • When would you move to Redis?

Tips

  • Show eviction order