Time-Based Expiration (TTL)
What you'll learn: How to use time-to-live (TTL) to automatically remove cached data after a fixed duration.
The Core Idea
Time-To-Live (TTL) is a simple yet powerful caching mechanism where you assign each cached item an expiration timestamp. After the specified duration elapses, the cache automatically discards that item. The next request for that data will miss the cache and fetch fresh data from the source.
Think of TTL like the expiration date on milk in your refrigerator. Once that date passes, you throw it out and buy fresh milk—you don't keep using potentially stale data.
How It Works
When you store data in the cache, you also specify how long it should remain valid:
cache.set(key="user:123", value=user_data, ttl=300) # expires in 5 minutes
The cache automatically tracks when each item was added and removes it when the TTL expires. If you request user:123 after 6 minutes, you'll get a cache miss—the item is simply gone.
When to Use TTL
TTL works best when:
- Data becomes stale predictably over time
- You can tolerate slightly outdated information
- The cost of serving stale data is low
- Traffic patterns are consistent enough that items get refreshed naturally
For example, product prices might have a 60-second TTL, user profile data might last 10 minutes, and configuration settings could persist for an hour.
The Trade-off
Short TTLs keep data fresh but increase cache misses and database load. Long TTLs improve performance but risk serving outdated information. Choose TTL values based on how quickly your data changes and how important freshness is to your users.
Key Takeaway: TTL provides automatic cache expiration by setting a fixed lifetime for each cached item—simple to implement, easy to reason about, and effective when data staleness follows predictable time patterns.