Cache Size Management
What you'll learn: How to monitor storage limits, implement smart eviction policies, and prevent your service worker cache from growing out of control.
Why Cache Size Matters
Browser storage isn't infinite. Each origin gets a quota (often several hundred megabytes to a few gigabytes, depending on the browser and available disk space). If your service worker caches too many resources without cleanup, you'll hit storage limits, causing cache writes to fail silently or triggering automatic eviction of all your data.
Think of cache management like a closet: without organization, it fills up with clothes you never wear, leaving no room for what you actually need.
Monitoring Storage Usage
Use the StorageManager API to check your quota:
if (navigator.storage && navigator.storage.estimate) {
const {usage, quota} = await navigator.storage.estimate();
const percentUsed = (usage / quota) * 100;
console.log(`Using ${percentUsed.toFixed(2)}% of storage`);
}
LRU Eviction (Least Recently Used)
Implement a LRU strategy by tracking access timestamps. When adding new items, remove the oldest if you're near capacity:
// In your fetch handler
const cache = await caches.open('my-cache-v1');
await cache.put(request, response.clone());
// Track access
const accessLog = await getAccessLog(); // from IndexedDB
accessLog[request.url] = Date.now();
await saveAccessLog(accessLog);
// Evict if needed
if (await isNearQuota()) {
await evictLRU(cache, accessLog);
}
Prevention Strategies
- Set hard limits on cache entries (e.g., max 100 images)
- Prioritize critical assets – never evict HTML/CSS/JS shells
- Use cache versioning to cleanly remove old caches during activation
- Implement size-aware caching – skip caching huge video files
Key Takeaway: Proactively monitor cache size, implement LRU eviction to remove stale resources, and set limits per cache to prevent quota exhaustion and ensure critical assets remain available.