Definition
stale-while-revalidate (SWR) is a strategy where a Service Worker (a browser script that intercepts fetch between the page and the network) returns a response from Cache Storage first and updates the cache in the background with a network request. It waits for the network only on cache miss.
Why it matters
Large, repeatedly fetched resources such as documents and images feel slow if every view waits on the network. "Cache only" leaves stale files; "network only" delays first paint. SWR aims for fast first paint, freshness in the background.
The browser Cache Storage API does not provide a default byte cap or LRU eviction. Byte budgets and metadata must be managed by the application.
How it works
Key rules:
- Store only successful GET responses. Do not cache
Range,HEAD,PUT, etc. to avoid partial or corrupted responses. - 404 and 410 signal original deletion — remove existing cache entries too.
- Cache keys strip auth queries only, per presigned-url-cache-key-normalization.
- Capacity: store image body plus
{key, bytes, lastAccess}metadata separately; when total bytes exceed budget (e.g. 100MB), evict by LRU. - On hit, update
lastAccess— byte sum rather than entry count is fairer when image sizes vary widely.
Practical application
- Routing external object storage URLs through a same-origin proxy simplifies SW scope and cookie control.
- Do not use immediate SWR return for sensitive images (pre-mask originals) — follow cache-generation-stale-write-guard and deletion ACK ordering.
Trade-offs
- SWR may show slightly stale content briefly — acceptable for ordinary document images, not right after PII masking.
- SW registration, update, and debugging have cost. Libraries like Workbox reduce boilerplate but policy understanding is still required.
- Background revalidate races with deletion — without a generation guard, deleted originals can reappear.
When not to use
- Auth tokens, payment results, and other API responses that must always be fresh.
- Media where
Rangestreaming and video seek are core (partial cache pollution). - When targeting only environments without SW — first check whether server CDN cache and HTTP
Cache-Controlalone suffice.
Common mistakes
- Stripping the entire presigned URL query from the key so masked and original collide on one entry.
- Deleting cache without blocking in-flight revalidate.
- Count-only limits so one large image consumes the budget, or only small thumbnails survive LRU.
- Page sends delete message only before SW control and waits forever — use timeout and direct
caches.deletein parallel.
Related concepts
- presigned-url-cache-key-normalization — strip signature queries, preserve semantic queries
- cache-generation-stale-write-guard — prevent stale writes after deletion
- server-image-proxy-transcoding-cache — role split with server proxy LRU