Time-Based Cache Invalidation (TTL)
What you'll learn: How to automatically expire cached data after a predetermined time period using time-to-live (TTL) settings.
The Core Idea
Time-To-Live (TTL) is the simplest and most common cache invalidation strategy. When you store data in cache, you assign it an expiration timestamp—after that time elapses, the cache automatically removes or marks the entry as invalid. Think of TTL like the "best before" date on food packaging: once that date passes, you know it's time to get fresh supplies.
How TTL Works
When inserting data into cache, you specify a TTL value (in seconds, minutes, or hours). The cache system tracks when each entry was created and automatically evicts it when the TTL expires. On the next request, the cache miss triggers a fresh fetch from the source.
For example, if you cache product pricing with a 5-minute TTL, prices older than 5 minutes are automatically purged. This ensures users see reasonably current prices without manual invalidation.
When to Use TTL
TTL works best when:
- Data changes predictably (weather forecasts, stock prices, dashboards)
- Slight staleness is acceptable (user profiles, product catalogs)
- Invalidation logic is complex (easier to set "expire everything after 10 minutes" than track dependencies)
Trade-offs
Short TTLs mean fresher data but more cache misses and higher load on your data source. Long TTLs improve hit rates but risk serving stale data. The sweet spot depends on your specific consistency requirements and update patterns.
TTL pairs well with other strategies—you might use TTL as a safety net while also invalidating explicitly when critical data changes.
Key Takeaway: Time-based cache invalidation (TTL) automatically expires cached entries after a fixed duration, balancing freshness with performance by controlling how long data remains valid without manual intervention.