Performance and memory · mid
Caching: functools, an LRU cache and its traps
cache and lru_cache save the result of a pure function with hashable arguments. In a long-running service they can keep objects alive, return shared mutable results and serve stale data.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- functools.cache is unbounded (3.9). lru_cache(maxsize=N) evicts the least recently used entry. cache_info() and cache_clear() show and reset it.
- Arguments must be hashable. A list or dict raises TypeError. f(1) and f(x=1) are separate entries.
- The cached object is shared. If a caller changes a returned list, every later caller gets the changed list. Return tuples or copies.
- On a method, the cache holds self, so instances stay alive (Ruff rule B019). cached_property is per instance.
- There is no expiry: prices and config go stale. Use a TTL cache (cachetools) or Redis. Each process has its own cache; nothing invalidates it across workers.
- On an async def it caches the coroutine object, so the second await fails with RuntimeError: cannot reuse already awaited coroutine.
- Writing your own LRU: collections.OrderedDict with move_to_end(key) on a hit and popitem(last=False) when over maxsize. All operations are O(1). A list for recency is O(n) per hit.
- Your own LRU needs: the key (args, tuple(sorted(kwargs.items()))), functools.wraps, a lock around the dict but not around the slow call, a TTL by storing the time, and edge cases for maxsize 0 or None.
The red pen
Common traps: mistake → fix
Mistake: @cache on a function that reads the database makes it fast
Fix: it also makes the data stale forever.
Mistake: Cache any function
Fix: only pure functions without side effects.
Mistake: lru_cache on async functions works like on sync ones
Fix: it caches the coroutine object, which can be awaited once.
Mistake: The cache is shared across all workers
Fix: each process has its own.
Easy to hard
Questions interviewers ask, easy to hard
- When would you use lru_cache?
- What can go wrong with a cache in a long-running service?
- Why can lru_cache on a method leak memory?
- Write an LRU cache decorator without functools. Which structure and what costs?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.