Sub topic 9
Expiring Entries with TTL
This chapter assumes you know the cache-aside pattern from the previous chapters. You should also be comfortable with Python and with the idea of a cache hit and a miss.
What TTL does
A TTL (time to live) is the number of seconds an entry may be served after it is stored. When the TTL runs out, the entry is expired. The next read treats it as a miss and loads fresh data from the source.
TTL bounds staleness without any coordination. If you cache a user profile for 60 seconds, a reader sees data at most 60 seconds old, even if an invalidation message is lost or a writer forgets to clear the entry.
TTL in cache-aside
The cache stores each value with an expiry time. A read checks the time before it trusts the entry.
import time
cache = {} # key -> (value, expires_at)
TTL_SECONDS = 60
def get_user(user_id, db):
key = f"user:{user_id}"
entry = cache.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0] # cache hit
value = db.fetch_user(user_id) # cache miss: read from the source
cache[key] = (value, time.monotonic() + TTL_SECONDS)
return value
def update_user(user_id, data, db):
db.save_user(user_id, data)
cache.pop(f"user:{user_id}", None) # invalidate after the writeThe code uses time.monotonic() instead of time.time(). A monotonic clock never jumps backward when the system clock is adjusted, so expiry checks stay correct.
The write path also deletes the entry. TTL is a safety net, and explicit invalidation keeps the common case fresh.
Lazy and active expiry
Expired entries do not disappear on their own. Caches use two strategies, often together:
- Lazy expiry: check the expiry time on read, as the code above does. It is cheap, but entries that are never read again stay in memory.
- Active expiry: a background task scans for expired entries and removes them. This reclaims memory but costs CPU.
Redis combines both: it checks on access and also samples keys with TTLs in the background.
Choosing a TTL
There is no universal value. Pick it from how much staleness the data tolerates and how expensive a miss is.
| Data | Typical TTL | Reason |
|---|---|---|
| Static assets with versioned names | Days to a year | Content never changes under that name |
| Product catalog | Minutes | Small staleness is acceptable |
| Account balance | Seconds, or no caching | Wrong values cause real harm |
| Negative results ("not found") | Short | A new record should appear soon |
A longer TTL raises the hit ratio and lowers load on the source, but it increases staleness. A shorter TTL does the reverse.
Common errors
- Synchronized expiry. If many entries are loaded together with the same TTL, they expire together and the source gets a burst of misses. Add jitter, a small random offset, such as
TTL_SECONDS + random.uniform(0, 10). - Hot key expiry. When a popular key expires, many requests miss at once. The stampede chapter covers this.
- No TTL at all. An entry without a TTL can stay stale forever if invalidation fails. Give every entry some TTL.
- Treating TTL as a refresh schedule. A TTL only limits maximum age. It does not guarantee the entry is refreshed at that time.
Exercise
A cache fills 10,000 product entries at startup, all with a 300-second TTL. Five minutes later the database load spikes. What caused it, and how do you fix it?
Show answer
All entries expire at the same moment, so the next requests all miss and hit the database together. Add random jitter to each TTL, for example 300 plus a random 0 to 60 seconds, so expiry times spread out.