Course contentsShow
← Web Development
Lesson 2424 of 2,98243. Service Workers Deep DiveFree lesson

Runtime Cache Expiration

Learn strategies for expiring runtime cached items: max entries, max age, and cache-first with network fallback.

Runtime Cache Expiration

What you'll learn: How to automatically remove stale or excess items from your runtime cache to keep storage lean and content fresh.

While precaching handles versioned assets that update with your service worker, runtime caches grow indefinitely as users browse—unless you implement expiration strategies. Without limits, your cache can bloat with outdated API responses, old images, or hundreds of pages the user visited once.

Why Expiration Matters

Think of runtime cache expiration like a refrigerator: you can't keep adding groceries forever. You need rules for what stays (freshness date) and how much fits (shelf space).

Three Key Expiration Strategies

1. Max Entries

Limit how many items a cache can hold. When exceeded, the oldest entries are removed (FIFO - first in, first out).

// Example pattern (conceptual, based on earlier Cache API lessons)
// Keep only the 50 most recent images
const imageCache = await caches.open('images-v1');
const keys = await imageCache.keys();
if (keys.length > 50) {
  await imageCache.delete(keys[0]); // Remove oldest
}

2. Max Age

Delete entries older than a specified time (e.g., 7 days). Useful for API data that becomes stale.

3. Cache-First with Network Fallback

Serve cached content first, but if it's missing or expired, fetch fresh from the network. This combines performance with freshness.

Putting It Together

You typically configure expiration when registering runtime routes:

  • Images: max 100 entries, 30-day age limit
  • API calls: max 50 entries, 5-minute age limit
  • Pages: max 10 entries, no age limit

Without expiration, runtime caches become digital hoarders—slow, bloated, and unreliable.

Key Takeaway: Runtime cache expiration uses max entries, max age, and cache-first-with-fallback strategies to automatically prune stale or excessive cached data, keeping storage efficient and content fresh.