Sub topic 9
Expiring Entries with TTL
This chapter assumes you know what a cache is, how cache-aside works, and how to read basic Python. It covers how a time to live (TTL) works, how to choose one, and the errors that appear most often in practice.
What a TTL does
A TTL (time to live) is the number of seconds an entry may be served after it is stored. When the time runs out, the entry is expired. The next read treats it as a miss and loads fresh data from the source.
A TTL gives you a hard upper bound on staleness. Even if your code never invalidates an entry, or an invalidation message is lost, the wrong data cannot live past the TTL. For this reason, TTL is usually the safety net under every other invalidation rule.
The cost is that every expiry forces a trip to the source. A short TTL gives fresher data but a lower hit ratio and more load on the database. A long TTL does the opposite.
TTL in cache-aside
The cache-aside example stores each value with an expiry time and checks it on every read.
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 writeThree details matter here.
- The expiry is stored as an absolute time (
expires_at), not as a countdown. Checking it needs one comparison and no background work. - The code uses
time.monotonic(), which never moves backward.time.time()follows the wall clock, which can jump when the system clock is corrected, so entries could expire early or live too long. update_userdeletes the entry after saving. The TTL still applies to any copy the delete misses, for example one cached by another process.
Lazy and active expiry
A cache can remove expired entries in two ways.
| Method | How it works | Trade-off |
|---|---|---|
| Lazy expiry | Check the deadline when a key is read. If it has passed, treat the entry as a miss. | Cheap, but entries that are never read again stay in memory. |
| Active expiry | A background task scans for expired keys and deletes them. | Frees memory sooner, but costs CPU and must be rate-limited. |
The dictionary above uses only lazy expiry. A key that is read once and never again stays in memory forever. In a long-running process this is a memory leak. Production caches such as Redis combine both methods: they check on read and also sample keys in the background. Redis samples a subset of keys that have a TTL, so expired memory is reclaimed gradually and not all at once.
The practical rule is that an expired entry is never returned, but it may still occupy memory for a while. Combine TTL with a size limit and an eviction policy (see the next chapter) so memory stays bounded.
Choosing a TTL value
There is no universal value. Work from the data's behavior and from what a stale read costs.
- Ask how long a wrong answer is acceptable. A product description can be a day old. An account balance often cannot be stale at all.
- Ask how often the data really changes. If a record changes once a week, a 5-second TTL wastes most of the cache's value.
- Estimate the load a miss creates. If rebuilding an entry is expensive, prefer a longer TTL and explicit invalidation on writes.
- Check the hit ratio. Hit ratio is bounded by how many reads happen inside one TTL window. If a key is read once every 10 minutes, a 60-second TTL gives a hit ratio near zero for that key.
A common pattern is to set a long TTL, such as an hour, and rely on explicit invalidation for freshness, with the TTL as a backstop. Another is to use short TTLs, such as 5 to 30 seconds, for hot data that changes often, because even a short window absorbs most of a traffic spike.
Common errors
Synchronized expiry
If many entries are written at the same moment, for example when a cache is warmed at startup, they all expire together. The source then receives a burst of misses at once. The fix is jitter: add a small random amount to each TTL.
import random
def ttl_with_jitter(base_seconds, spread=0.1):
# spread=0.1 means up to 10% extra, so 60 becomes 60 to 66
return base_seconds * (1 + random.uniform(0, spread))Only add time, not subtract it, if the base TTL is your maximum staleness promise. Subtracting is fine when the base is only a target.
Hot key expiry
A single popular key expires, and many concurrent requests all miss and rebuild it. This is a cache stampede, and it is covered in its own chapter. The per-key lock is the standard fix for one process. Longer TTLs and refreshing an entry shortly before it expires also reduce the risk.
Caching absence
If a lookup finds no record and you do not cache that result, a client that keeps asking for a missing key sends every request to the database. Cache the "not found" result too, with a shorter TTL, such as 30 to 60 seconds. Use a sentinel that cannot be confused with a real value. In the earlier code, None is a poor choice if your loader can legitimately return None, because the fresh helper in the stampede example treats None as a miss.
Refreshing the TTL on read
Some caches offer a sliding TTL, where each read resets the clock. This keeps popular entries alive, but a key that is read often never expires, so it can stay stale indefinitely. Use sliding TTL only for data where staleness does not matter, such as sessions. For data from a source of truth, use a fixed TTL, or add an absolute maximum age on top of the sliding window.
Clock and unit mistakes
- Libraries differ on units. Redis
EXPIREtakes seconds, whilePEXPIREtakes milliseconds. A value that is 1000 times too long or too short is a frequent bug. - In a distributed cache, expiry is decided by the cache server's clock. Do not compare it to timestamps from application servers.
- A TTL of zero or a negative number means different things in different systems. Some delete the key immediately, and others mean no expiry. Check the documentation.
TTL and HTTP
The same idea appears in HTTP as Cache-Control: max-age=3600, which tells browsers and CDNs how many seconds the response is fresh. After that, the client revalidates instead of simply discarding the entry. That topic has its own chapter.
How expiry affects the request flow
Summary of decisions
- Always set a TTL, even when you also invalidate on writes.
- Choose the TTL from the cost of staleness, not from habit.
- Add jitter to spread out expiry.
- Cache negative results briefly.
- Use fixed TTLs for data that must eventually be correct.
Exercise
A service warms 10,000 product entries at startup, each with a 300-second TTL. Five minutes later, the database is overloaded. What happened, and how do you fix it?
Show answer
All entries were written at the same moment, so they all expired together and every request became a miss at once. Add jitter to each TTL (for example, 300 to 330 seconds chosen randomly) so expiries are spread over time. Warming the cache gradually also helps.
Exercise
A key is read once every 10 minutes. You set its TTL to 60 seconds. What is its hit ratio, and what would you change?
Show answer
Close to zero, because the entry always expires before the next read. Either raise the TTL above 10 minutes and use explicit invalidation on writes to keep it fresh, or accept that this key does not benefit from caching.