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

Time-Based Expiration (TTL)

Using time-to-live values to automatically expire cached data after a fixed duration.

Time-Based Expiration (TTL)

What you'll learn: How to automatically remove stale cached data using expiration timers.

The Core Idea

Time-Based Expiration, commonly called TTL (Time-To-Live), sets an automatic expiration timer on cached data. When you store something in cache, you specify how long it should remain valid. Once that time elapses, the cached entry is either automatically deleted or marked as expired and ignored on the next access.

Think of it like milk in your refrigerator with an expiration date stamped on the carton. You don't need to taste-test it every day—the date tells you when it's no longer fresh. Similarly, TTL tells your cache when data is "expired" without needing to check the original source constantly.

How TTL Works

When writing data to cache, you include an expiration time:

  • Absolute time: "Expire at 3:00 PM today"
  • Relative duration: "Keep this for 5 minutes from now"

Most caching systems use relative durations (e.g., TTL=300 means 300 seconds). When the time expires, the cache either removes the entry immediately or marks it as invalid so the next read request fetches fresh data from the source.

Why Use TTL?

TTL solves the Cache Invalidation Problem you learned about earlier by providing a simple, time-based invalidation strategy. Instead of manually tracking when data changes, you let time automatically expire potentially stale data. This works well for data that changes predictably or when eventual consistency is acceptable.

For example: weather data might have a 10-minute TTL, user profile data might use 1 hour, and product pricing might use 5 minutes.

Key Takeaway: TTL automatically expires cached data after a configured duration, providing a simple solution to cache invalidation without manual tracking—though you must carefully balance freshness needs against cache effectiveness.