Course contentsShow
← System Design
Lesson 149 of 1,9194. Caching StrategiesFree lesson

Time-To-Live (TTL) Expiration

Automatically removing entries after a fixed time period, ensuring stale data doesn't persist indefinitely.

Time-To-Live (TTL) Expiration

What you'll learn: How TTL automatically removes cached entries after a set time period to prevent stale data from lingering.


What Is TTL Expiration?

Time-To-Live (TTL) is a cache eviction mechanism where each cached entry is assigned a maximum lifespan. Once that time expires, the entry is automatically removed from the cache, regardless of how frequently it's accessed or how much space is available.

Think of TTL like an expiration date on milk. Even if the carton is full and you haven't drunk much, once the date passes, you throw it out because it's no longer safe to consume. Similarly, cached data gets removed after its time is up, preventing stale information from being served.


How TTL Works

When you store data in the cache, you set a TTL value (e.g., 60 seconds, 5 minutes, 24 hours). The cache tracks when each entry was stored and automatically deletes it when the TTL period elapses.

Example scenario:

  • You cache user profile data with a TTL of 10 minutes
  • After 10 minutes, that profile data is removed
  • The next request must fetch fresh data from the database
  • This ensures users see updated information within 10 minutes

When to Use TTL

TTL is ideal when:

  • Your data changes predictably over time
  • You can tolerate some staleness (bounded by the TTL)
  • You want simple, time-based expiration without complex logic
  • You're caching API responses, session data, or frequently updated content

Unlike LRU or LFU (which evict based on usage), TTL prioritizes data freshness based on age alone.


Key Takeaway: TTL expiration automatically removes cached data after a fixed time period, guaranteeing that stale information doesn't persist beyond your defined threshold—trading some cache efficiency for predictable data freshness.