AI Hints
Home›System Design Tutorial›Keeping Caches Healthy
System Design · Lesson 59 of 120

TTL and Invalidation

Keeping caches fresh.

⏱ 2 min read▶ Video at 1:10:11🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

TTL and Invalidation
From the video: TTL and Invalidation
  • 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.pypython
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))
Output
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.

keyvalue
Descriptionsan hour is fine
Pricesabout a minute
Checkout stockdon't cache
BestTTL + 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
Next up: Cache Stampedes — many misses at once