The cache stores a copy with a max-age and an SWR window; on a stale hit within the window, it serves the stale copy and fires one background revalidation; on a stale hit outside the window, it blocks until the fresh copy arrives.
The mechanism rests on three time values. max-age=N defines how long the entry is fresh: within N seconds, the cache serves without any check. stale-while-revalidate=W defines how long after freshness the cache may still serve stale while revalidating: within the W-second window after max-age, the cache serves the stale copy and fires a background request to the origin. Beyond max-age + W, the cache treats the entry as missing: the next request blocks on a synchronous revalidation, exactly as in default caching.
sequenceDiagram
participant C as Client
participant Cache
participant Origin
C->>Cache: GET /page
alt Fresh (age < max-age)
Cache-->>C: 200 (fresh)
else Stale within SWR window
Cache-->>C: 200 (stale)
Cache->>Origin: revalidate (async)
Origin-->>Cache: 304 or new content
else Stale beyond SWR window
Cache->>Origin: revalidate (sync)
Origin-->>Cache: 304 or new content
Cache-->>C: 200 (fresh)
end
The directive composes with stale-if-error. Cache-Control: max-age=60, stale-while-revalidate=600, stale-if-error=86400 means: fresh for 60s; serve stale and revalidate in the background for the next 600s; if the origin fails, continue serving the last known good copy for up to 24h. The three directives together define the cache's tolerance envelope: how long it can go without confirmation, and how long it can hide an outage.
Deploying stale-while-revalidate
Pick the max-age correctly
max-ageshould match how often the content actually changes, not how often you would like it to. A pricing page that changes hourly should not havemax-age=300.Set the SWR window to the outage window you can tolerate
If you can hide a 10-minute origin outage without user impact,
stale-while-revalidate=600. If the origin must recover faster, use a shorter window.Monitor the revalidation rate and stale hit rate
A healthy SWR deployment shows a steady trickle of revalidations, not a flood. A flood means SWR is not caching properly; a dry spell means nothing is expiring.
Combine with stale-if-error for full resilience
SWR hides origin latency; stale-if-error hides origin failures. They are complementary, and most production deployments should enable both.
Different caches implement SWR differently. Fastly and Cloudflare support it at the edge as a first-class feature. CloudFront supports it via cache policies. Browsers vary: Chrome and Firefox implement it for certain contexts; Safari has partial support. A cache that does not understand the directive treats the response as a normal max-age entry, which is safe but loses the optimization. That makes SWR a "gracefully degrading" feature — you get the benefit where it is supported, and the default behaviour where it is not.