TTL, eviction and invalidation

Topic 3 of 9 in Week 4: Caching, queues and content delivery9 min readIntermediateFree course

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

Eviction with LRU. The cache holds user:42 (most recent), feed:7, post:9, user:3 and post:1 (least recent). A GET for post:5 misses, so post:5 is inserted at the front and the least recently used key, post:1, is evicted. Policies: LRU evicts the least recently used key and suits most workloads; LFU evicts the least frequently used key and suits stable popular items.

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: bump catalog_version to 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.

Exercise

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.

Text
(a) Airports:
(b) Flight search results:
(c) Hotel details:
(d) Session:

Eviction policy:

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.