TTL, eviction and invalidation
Overview
A cache is only useful if it holds the right data, and only safe if it doesn’t hold wrong data for too long. Data leaves a cache in three ways: it expires (TTL), it’s evicted to make room, or it’s invalidated because the source changed. Getting these right is what people mean when they joke that cache invalidation is one of the two hard problems in computer science.
TTL: expiry by time
Every entry can carry a time to live. After it passes, the entry is treated as missing and reloaded on the next read.
- Short TTLs (seconds to minutes) keep data fresh but lower the hit rate and raise database load.
- Long TTLs (hours to days) give high hit rates but serve stale data longer.
Pick the TTL from the question “how stale is acceptable?” rather than from performance alone. A product description can be an hour old; a flight price perhaps two minutes; stock at checkout, not at all.
Add jitter. If 100,000 keys were cached at the same moment with the same TTL, they all expire together and the database gets hit at once. Use ttl = base ± random(10%) to spread expirations.
Sliding expiration resets the TTL on each access, which suits sessions: active users stay logged in, idle sessions expire.
Eviction: when memory is full
Caches have a fixed amount of memory. When a new entry doesn’t fit, something must go. Common eviction policies:
- LRU (least recently used): drop the item not accessed for the longest time. A great general default because recent use predicts future use.
- LFU (least frequently used): drop the item accessed least often. Better when some items are steadily popular and a burst of one-off reads (a crawler, a batch job) would otherwise push them out of an LRU cache.
- FIFO / random: simpler, occasionally good enough.
- TTL-based: evict entries closest to expiry first.
Redis exposes these as maxmemory-policy settings such as allkeys-lru, allkeys-lfu and volatile-ttl. If evictions are frequent, the cache is too small for the working set, and the hit rate suffers.
Invalidation: when the source changes
TTL alone means users may see old data until expiry. To show changes quickly, invalidate explicitly:
- Delete on write: after updating the database, delete the cache key (previous lesson). Simple and the most common.
- Event-driven invalidation: the service that changes data publishes an event (“product 42 updated”); cache owners delete their entries. Using the database’s change data capture stream makes sure no write path is forgotten.
- Versioned keys: include a version in the key (
product:42:v17). Changing the data bumps the version, so readers naturally move to the new key and the old one expires on its own. Also used for whole caches: bumpcatalog_versionto invalidate everything at once. - CDN purge: call the CDN’s API to purge a URL or a tag after content changes, or use versioned URLs for assets so purging isn’t needed.
Why it’s hard
- Many copies: the same data may be cached under several keys (the product, a category page that lists it, a search result). Each needs invalidating; tracking dependencies is error-prone.
- Many layers: local caches on 200 servers, Redis, the CDN and browsers. A local cache can’t be cleared remotely without a broadcast mechanism (pub/sub), so give local caches short TTLs.
- Races: concurrent reads and writes can put old data back after a delete.
A robust approach combines both: explicit invalidation for speed, TTL as a safety net so that any missed invalidation heals itself.
Negative caching
If many requests ask for something that doesn’t exist (a deleted product, a bad ID), each one misses the cache and hits the database. Cache the “not found” result too, with a short TTL. This also blunts attacks that request random IDs.
In an interview
State three things for each cache: “TTL of 10 minutes with jitter; LRU eviction; invalidated by deleting the key when the product is updated.” If the data appears in several cached views, mention how you’d handle that, for example with short TTLs on aggregated pages.
Recap
TTLs bound staleness and should be chosen by how stale data may be, with jitter to avoid synchronised expiry. Eviction policies such as LRU and LFU decide what to drop when memory runs out. Invalidation keeps caches fresh after changes, by deleting keys, reacting to change events or versioning keys. Use explicit invalidation for speed and TTLs as a backstop.
Set the expiry rules
A travel site caches: (a) the list of airports (changes a few times a year); (b) flight search results for a route and date (prices change every few minutes); (c) a hotel's details page (edited by hotel staff a few times a month, and edits should show within a minute); (d) a user's session. Choose a TTL and an invalidation approach for each, and an eviction policy for the Redis cluster as a whole.
(a) Airports:
(b) Flight search results:
(c) Hotel details:
(d) Session:
Eviction policy:(a) Airports: long TTL (e.g. 24 h) or keep in a local in-memory cache on each server,
refreshed on deploy or by a version key. Rare changes can trigger a manual purge.
(b) Flight search results: short TTL (e.g. 2-5 minutes) with jitter. Prices are
re-checked at booking time anyway, so brief staleness in search is acceptable.
(c) Hotel details: TTL of a few hours as a backstop, plus explicit invalidation: when
staff save an edit, delete the cache key (or publish an event that does), so the
change appears within seconds.
(d) Session: TTL equal to the session lifetime (e.g. 30 minutes idle, refreshed on
each request with a sliding expiry). Deleting the key logs the user out.
Eviction policy: allkeys-lru (or allkeys-lfu) for a pure cache, so the least useful
keys go first when memory fills. If sessions share the cluster and must not be
evicted, keep them in a separate Redis instance or use volatile-* policies carefully.Summary
- A TTL (time to live) makes an entry expire automatically; it bounds how stale data can get.
- When memory is full, an eviction policy decides what to drop: LRU (least recently used) is the common default; LFU keeps frequently used items.
- Invalidation removes or updates entries when the source changes: delete on write, events from the database, or versioned keys.
- Add random jitter to TTLs so many keys don't expire at the same moment.
- Combine explicit invalidation for freshness with a TTL as a safety net.