# Stale-While-Revalidate, Stale-If-Error and Asset Fingerprinting — Caching Strategies & CDN Design

Source: https://www.skillbyai.com/en/caching-strategies/h-swr

> Serve fast stale content safely and version static assets for long caching.

## Fast responses even at expiry

Two extensions (from RFC 5861) make caches more forgiving. **`stale-while-revalidate=N`** lets a cache serve a stale response for up to N seconds **while it fetches a fresh one in the background**, so users never wait on revalidation; it is ideal for content where a little staleness is fine. **`stale-if-error=N`** lets a cache serve stale content for up to N seconds if the origin returns errors or is unreachable, turning an origin outage into slightly old pages instead of error pages. For **static assets**, the best strategy is **fingerprinting** (also called cache busting): build tools put a content hash in the file name (`main.8c2e1f.css`), the HTML references the new name whenever content changes, and the file itself can be cached for a year with `immutable`. The HTML that references the assets is then given a short TTL or revalidation, so users pick up new asset names quickly.

## Fingerprinted assets and short-lived HTML

Long caching for hashed files; quick updates through the HTML that names them.

```html
<!-- index.html: Cache-Control: public, max-age=0, must-revalidate (or a short s-maxage at the CDN) -->
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" href="/assets/main.8c2e1f.css">
  </head>
  <body>
    <div id="app"></div>
    <script src="/assets/app.3f9a1c.js" defer></script>
  </body>
</html>
<!-- /assets/*: Cache-Control: public, max-age=31536000, immutable -->
```

## Never cache index.html for a year

If the HTML that references your fingerprinted assets is cached for a long time, users keep loading old asset names and never see the new release. Long caching belongs on hashed files only.

**Quiz:** What does stale-if-error allow a cache to do?

- [x] Serve stale content for a limited time if the origin is failing
- [ ] Delete content when the origin errors
- [ ] Ignore Cache-Control headers
- [ ] Return errors faster

*Answer:* Serve stale content for a limited time if the origin is failing. stale-if-error keeps serving the last good copy during origin failures, within the stated window.
