Sub topic 16
Where to go next: TTL and other policies
This chapter assumes you have the finished LRUCache from the earlier chapters: a dictionary mapping keys to nodes, plus a doubly linked list with sentinel nodes. It sketches three extensions and points to alternative eviction policies.
Adding a time to live
LRU removes entries only when the cache is full. A time to live (TTL) adds a second rule: an entry is stale after a fixed number of seconds, even if there is room. Caches of web responses or database rows usually need this, because the source data changes.
The Node class uses __slots__, so it can't hold a new field. The subclass below keeps deadlines in a separate dictionary instead. It checks expiry lazily, when a key is read, so no background thread is needed.
import time
class TTLLRUCache(LRUCache):
def __init__(self, capacity, ttl, clock=time.monotonic):
super().__init__(capacity)
self.ttl = ttl
self.clock = clock
self.expires = {} # key -> deadline
def _drop(self, key):
node = self.map.pop(key)
self.order.remove(node)
self.expires.pop(key, None)
def get(self, key):
deadline = self.expires.get(key)
if deadline is not None and self.clock() >= deadline:
self._drop(key)
return None
return super().get(key)
def put(self, key, value):
if key not in self.map and len(self.map) >= self.capacity:
self.expires.pop(self.order.tail.prev.key, None)
super().put(key, value)
self.expires[key] = self.clock() + self.ttl
now = [0]
cache = TTLLRUCache(2, ttl=10, clock=lambda: now[0])
cache.put("a", 1)
now[0] = 5
print(cache.get("a")) # 1
now[0] = 10
print(cache.get("a")) # NoneThe clock parameter lets a test replace real time with a fake counter, so tests don't need sleep. time.monotonic is the right default because it never jumps backward when the system clock changes.
Before super().put evicts the oldest entry, put removes that entry's deadline. Without this step, expires would keep growing.
Other eviction policies
Different access patterns call for different rules. The data structures change with them.
| Policy | Evicts | Typical structure |
|---|---|---|
| FIFO | Oldest inserted entry | Dictionary plus a queue. Reads don't reorder. |
| LFU | Least frequently used entry | Dictionary plus a list per access count |
| MRU | Most recently used entry | Same as LRU, but evict from the front |
| Random | A random entry | Dictionary plus an array for sampling |
| 2Q, ARC | Scan-resistant blend of recency and frequency | Several lists |
LRU's weak spot is a one-time scan over many keys, such as reading a whole table once. The scan pushes out the entries you actually reuse. LFU and 2Q resist this better, but they are more complex.
Further directions
- Size-based capacity. Count bytes instead of entries, and evict until the total fits.
- Hit and miss counters.
functools.lru_cacheexposes these throughcache_info(). Adding them to your class is a good way to tune capacity. - Distributed caches. Redis offers LRU, LFU, and TTL settings. It approximates LRU by sampling a few keys instead of tracking exact order.
Exercise
In TTLLRUCache, a key is read at time 9 with TTL 10, and the entry was stored at time 0. Does the read extend its lifetime? What small change would make a read extend the lifetime?
Show answer
No. get never updates expires, so the entry still expires at time 10. To make reads extend the lifetime, set self.expires[key] = self.clock() + self.ttl after a successful super().get(key). This gives sliding expiration instead of fixed expiration.