Time-to-Live (TTL) for Expired URLs
You'll learn how to synchronize cache expiration with URL lifetimes to automatically remove stale entries without manual intervention.
In a URL shortener, many short links have expiration dates—perhaps they're valid for 30 days, 6 months, or 1 year. When you cache these URLs for fast retrieval, you face a problem: what happens when a URL expires but still sits in your cache, consuming memory and potentially serving invalid redirects?
The solution is elegantly simple: set your cache's Time-to-Live (TTL) to match the URL's expiration time.
How It Works
When you store a URL mapping in cache (using the Cache-Aside Pattern you learned earlier), calculate the remaining lifetime of that URL:
cache_ttl = url_expiration_timestamp - current_timestamp
For example, if a short URL expires on January 15th and today is January 1st, set the cache TTL to 14 days. The cache automatically purges the entry after 14 days—exactly when the URL becomes invalid.
The Synchronization Benefit
This approach creates perfect alignment between your cache and database states. You don't waste cache memory on expired URLs, and you don't need background cleanup jobs scanning for stale entries. The cache infrastructure (like Redis or Memcached) handles eviction automatically based on each entry's individual TTL.
Edge Cases
For URLs without expiration dates (permanent links), you can set a very long TTL or rely on your cache eviction policy (LRU, LFU) to eventually remove unpopular entries when memory fills.
For recently-expired URLs already in cache, the next access attempt will miss the cache, hit the database, discover the expiration, and return an error—no invalid redirects served.
Key Takeaway:
Setting cache TTL equal to URL expiration time creates self-cleaning caches that automatically purge expired short codes without manual intervention or background jobs.