TTL and Invalidation
Keeping caches fresh.
There's a famous joke. There are only two hard things in computer science. Cache invalidation, and naming things. Keeping cached data fresh really is tricky.

- Two hard things
- Cache invalidation
- And naming things
Time to live
The simplest tool is a TTL, a time to live. Each cached value expires after a set time, and the next read reloads it. Here the TTL is two seconds, and we use a pretend clock. Run it. At zero and one second, the cached price is used. At three seconds, it has expired, so we reload, and see the new price.
TTL = 2
cache = {}
db = {"mug": 10}
def get_price(item, now):
if item in cache and now - cache[item][1] < TTL:
return cache[item][0], "cache"
cache[item] = (db[item], now)
return db[item], "database"
print("t=0", get_price("mug", 0))
db["mug"] = 12 # price changes
print("t=1", get_price("mug", 1))
print("t=3", get_price("mug", 3))t=0 (10, 'database') t=1 (10, 'cache') t=3 (12, 'database')
Choosing freshness
So how long should the TTL be? It depends how stale the data can safely be. A product description can be an hour old. A price, maybe a minute. Stock levels at checkout should not be cached at all. For important changes, combine a TTL with deleting the key when the data changes.
| key | value |
|---|---|
| Descriptions | an hour is fine |
| Prices | about a minute |
| Checkout stock | don't cache |
| Best | TTL + delete on change |
Summary
ATTL makes cached values expire, and deleting keys on change keeps important data fresh. Choose freshness per type of data. Next, what happens when many requests miss at once.
Key takeaways- TTL expires values
- Delete on change
- Freshness per data type