Skip to main content

HTTP Caching Explained: Cache-Control, ETags, CDNs, and Service Workers

Master HTTP caching from the browser to the CDN. Learn Cache-Control directives, ETags and conditional requests, Vary, stale-while-revalidate, CDN cache keys and purging, and service worker caching strategies with practical examples.

Table of Contents

Introduction

The fastest network request is the one you never make. HTTP caching lets browsers, proxies, and CDNs reuse responses they’ve already received, cutting latency, bandwidth, and server load in a single move. A well-cached site feels instant on repeat visits and survives traffic spikes that would otherwise flatten its origin.

Caching is also one of the most misunderstood parts of web development. no-cache doesn’t mean “don’t cache”. max-age behaves differently in browsers and CDNs. A single Vary: Cookie header can quietly drop your CDN hit rate to zero, and one wrong Cache-Control on an HTML page can leave users stuck on an old deployment for a week.

Caching happens in layers:

  • The browser’s HTTP cache: private to one user, on their device
  • Shared caches: CDNs and reverse proxies that serve many users
  • Service workers: programmable caches you control with JavaScript
  • Application caches: framework data caches, Redis, in-memory memoization

This guide covers the first three: the HTTP-level caches that every web app relies on. You’ll learn what each Cache-Control directive actually does, how revalidation with ETags works, how CDNs build cache keys, and how service workers fit on top. By the end, you’ll have a set of copy-pasteable caching recipes and know how to debug caching when it goes wrong.


How HTTP Caching Works

Every cached response has two possible states:

  • Fresh: the cache can serve it directly, without contacting the server
  • Stale: the cache must check with the server (revalidate) before using it, unless directives allow serving stale content

The server controls the transition between these states through response headers.

The Request Lifecycle

When the browser needs a resource, it walks through these steps:

Request for /app.js
↓
Is there a cached copy?
├── No → Fetch from network → Store (if cacheable) → Use
└── Yes → Is it fresh?
├── Yes → Use cached copy (no network request)
└── No → Revalidate with server (conditional request)
├── 304 Not Modified → Refresh metadata, use cached copy
└── 200 OK → Replace cached copy, use new one

There are three outcomes, from best to worst:

  1. Fresh hit: zero network requests. The response comes from memory or disk in milliseconds.
  2. Revalidation (304): one round trip, but only headers come back. Much cheaper than a full download for large files.
  3. Miss (200): a full round trip and the full response body.

The goal of a caching strategy is to push as many requests as possible toward the top of that list without ever serving content that’s dangerously out of date.

Freshness Lifetime

A response’s freshness lifetime is how long it stays fresh. Caches compute it from these headers, in order of priority:

  1. Cache-Control: s-maxage=N (shared caches only)
  2. Cache-Control: max-age=N
  3. Expires: <date> (legacy, ignored when max-age is present)
  4. Heuristic freshness, used when none of the above are present

The response’s age is how long it has existed since the origin generated it. A response is fresh while age < freshness lifetime. When a CDN serves a cached response, it adds an Age header so downstream caches know how much of the lifetime is already used up:

HTTP/1.1 200 OK
Cache-Control: max-age=600
Age: 240

The browser receiving this response considers it fresh for another 360 seconds, not 600.

Heuristic Caching: The Hidden Default

If you send no freshness information at all, caches are allowed to guess. The HTTP spec (RFC 9111) suggests using 10% of the time since Last-Modified:

HTTP/1.1 200 OK
Last-Modified: Mon, 01 Sep 2025 00:00:00 GMT
# No Cache-Control, no Expires

If this file was last modified 50 days ago, a browser may cache it for about 5 days without checking back. This is a common source of “why are users seeing the old version?” bugs. Always send an explicit Cache-Control header, even if it’s just no-cache.


Cache-Control Directives

Cache-Control is the main tool for controlling caching. Directives are comma-separated and can be combined:

Cache-Control: public, max-age=31536000, immutable

Freshness Directives

DirectiveMeaning
max-age=NResponse is fresh for N seconds (all caches)
s-maxage=NOverrides max-age for shared caches (CDNs, proxies) only
immutableResponse will never change while fresh; skip revalidation even on reload
stale-while-revalidate=NAfter expiry, serve stale for up to N seconds while revalidating in the background
stale-if-error=NAfter expiry, serve stale for up to N seconds if the origin errors

Storage Directives

DirectiveMeaning
no-storeDon’t store the response anywhere
no-cacheStore it, but revalidate with the server before every use
privateOnly the browser may store it; shared caches must not
publicAny cache may store it, even if it would normally be uncacheable (e.g., responses to requests with Authorization)

Revalidation Directives

DirectiveMeaning
must-revalidateOnce stale, never serve without successful revalidation (no serving stale on errors)
proxy-revalidateSame as must-revalidate, but only for shared caches

no-cache vs no-store

This is the single most confused pair of directives:

# Cached, but always checked with the server first.
# Fast when unchanged: the server returns a small 304.
Cache-Control: no-cache
# Never written to any cache. Every request is a full download.
Cache-Control: no-store

Use no-cache when content changes unpredictably but you still want cheap 304s. Use no-store only for genuinely sensitive data, such as banking pages or responses containing personal information, because it gives up all caching benefits.

max-age=0 vs no-cache

These look identical but differ in one edge case:

Cache-Control: max-age=0
Cache-Control: no-cache

Both make the response stale immediately. However, with max-age=0, a cache that can’t reach the origin is allowed to serve the stale copy (with a warning). no-cache forbids using the stored response without successful validation. In practice, prefer no-cache because its intent is clearer.

private vs public

# User-specific data: browser only, never at the CDN
Cache-Control: private, max-age=60
# Shared content: OK at the CDN and in the browser
Cache-Control: public, max-age=3600

You rarely need public explicitly. Responses with max-age are already cacheable by shared caches. The main exception is responses to requests carrying an Authorization header, which shared caches won’t store unless you say public (or s-maxage).

Separate Browser and CDN Lifetimes with s-maxage

s-maxage lets you cache aggressively at the CDN, where you can purge, while keeping the browser cache short, where you can’t:

Cache-Control: public, max-age=60, s-maxage=86400

Browsers keep this response for 1 minute. The CDN keeps it for 1 day. When content changes, you purge the CDN and every user sees the update within a minute.

immutable

When a browser user hits reload, browsers traditionally revalidate the page’s subresources, even if they’re still fresh. For fingerprinted assets that can never change, those revalidations are pure waste:

Cache-Control: public, max-age=31536000, immutable

immutable tells the browser that the response won’t change during its freshness lifetime, so there’s no need to revalidate on reload. Firefox and Safari honor it, and Chrome already skips revalidating fresh subresources on a normal reload. Only use immutable with URLs that contain a content hash. The URL itself must change when the content does.


Validation: ETags and Last-Modified

When a cached response goes stale, the cache doesn’t have to download it again. It can ask the server, “Has this changed since I last saw it?” This is a conditional request.

ETags

An ETag (entity tag) is an opaque identifier for a specific version of a resource, usually a hash of its contents:

HTTP/1.1 200 OK
Cache-Control: no-cache
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Content-Type: application/json
{"products": [...]}

On the next request, the browser sends the ETag back in If-None-Match:

GET /api/products HTTP/1.1
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"

If the resource hasn’t changed, the server responds with no body:

HTTP/1.1 304 Not Modified
Cache-Control: no-cache
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"

If it has changed, the server sends a normal 200 with the new body and a new ETag.

Strong vs Weak ETags

ETag: "abc123" # Strong: byte-for-byte identical
ETag: W/"abc123" # Weak: semantically equivalent, bytes may differ

Weak ETags are useful when the same content can be encoded differently (e.g., gzip vs Brotli) or includes insignificant changes like a timestamp in a comment. Many servers and CDNs convert strong ETags to weak ones when they compress a response on the fly, because the compressed bytes no longer match the original hash.

Last-Modified

Last-Modified is the older, date-based validator:

HTTP/1.1 200 OK
Last-Modified: Tue, 20 Jan 2026 14:00:00 GMT
GET /report.pdf HTTP/1.1
If-Modified-Since: Tue, 20 Jan 2026 14:00:00 GMT

It has two weaknesses: one-second resolution, and it relies on file timestamps that often change on every deploy even when contents don’t. Prefer ETags based on content hashes. If both are present, servers should evaluate If-None-Match and ignore If-Modified-Since.

Generating ETags in Node.js

import { createHash } from "node:crypto";
import express from "express";
const app = express();
app.get("/api/products", async (req, res) => {
const products = await db.products.findMany();
const body = JSON.stringify(products);
// Hash the serialized body to produce a strong validator
const etag = `"${createHash("sha1").update(body).digest("hex")}"`;
res.setHeader("Cache-Control", "no-cache");
res.setHeader("ETag", etag);
if (req.headers["if-none-match"] === etag) {
return res.status(304).end();
}
res.type("application/json").send(body);
});

Express actually generates weak ETags and handles 304s for you by default (app.set("etag", ...)), but doing it by hand shows the mechanics. Note that this approach still runs the database query on every request. It saves bandwidth, not server work. To save server work too, derive the ETag from something cheaper, such as a updated_at timestamp or a version counter:

app.get("/api/products", async (req, res) => {
// Cheap query: just the latest modification time
const { version } = await db.query(
"SELECT max(updated_at) AS version FROM products",
);
const etag = `W/"products-${version.getTime()}"`;
res.setHeader("Cache-Control", "no-cache");
res.setHeader("ETag", etag);
if (req.headers["if-none-match"] === etag) {
return res.status(304).end(); // Skip the expensive query entirely
}
const products = await db.products.findMany();
res.json(products);
});

The Vary Header and Cache Keys

A cache stores responses under a cache key. By default, the key is the request method plus the URL. But some responses differ based on request headers, and caches need to know about that.

How Vary Works

Vary lists the request headers that affect the response:

HTTP/1.1 200 OK
Content-Encoding: br
Vary: Accept-Encoding

This tells caches to store separate copies for different Accept-Encoding values, so a client that doesn’t support Brotli never gets a Brotli-compressed response.

Common Vary Values

# Good: low cardinality, few possible values
Vary: Accept-Encoding
# Fine if you serve different formats (e.g., AVIF vs WebP images)
Vary: Accept
# Dangerous: one cache entry per unique value
Vary: User-Agent
Vary: Cookie

Vary: User-Agent creates a separate cache entry for every browser version string in existence, which effectively destroys your shared cache hit rate. Vary: Cookie does the same per user. If you need per-user responses, use Cache-Control: private instead and let the browser cache handle it.

Vary: *

Vary: *

This means “the response varies on things outside the request headers”, and effectively makes it uncacheable. Avoid it.


Stale Content: stale-while-revalidate and stale-if-error

Strict freshness forces a trade-off: short lifetimes mean frequent slow revalidations, while long lifetimes mean outdated content. The stale directives soften this trade-off.

stale-while-revalidate

Cache-Control: max-age=60, stale-while-revalidate=300

The timeline looks like this:

0s ──────────── 60s ───────────────────────── 360s ──────────→
Fresh: serve Stale: serve immediately, Too stale:
from cache revalidate in background block on network

For the first 60 seconds, the response is served from cache. Between 60 and 360 seconds, the cache returns the stale copy immediately and refreshes it in the background, so the next request gets the new version. After 360 seconds, the cache must wait for the origin.

The user never waits for revalidation, as long as requests keep arriving within the window. This is the same idea behind ISR in Next.js and the default behavior of TanStack Query. Major CDNs support it, and it’s supported in Chromium-based browsers and Firefox. Treat browser support as a progressive enhancement.

stale-if-error

Cache-Control: max-age=60, stale-if-error=86400

If the origin returns a 5xx error or is unreachable after the response expires, the cache may serve the stale copy for up to a day instead of showing an error. This turns your CDN into a safety net during outages. Support is strongest at the CDN level, so it’s most useful alongside s-maxage.

Combining Them

A good default for content that changes occasionally but must stay available:

Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=600, stale-if-error=86400

Browsers always revalidate. The CDN serves fresh content for 5 minutes, then stale content with background refresh for 10 more minutes, and falls back to day-old content if the origin goes down.


CDN Caching

CDNs are shared caches distributed around the world. They follow the same HTTP rules as browsers, plus a few extras.

CDN-Specific Headers

Sometimes you want a CDN to cache something that browsers should not, without relying on s-maxage (which also affects any intermediate proxy). RFC 9213 defines CDN-Cache-Control, which CDNs read and then strip before the response reaches the browser:

Cache-Control: no-cache
CDN-Cache-Control: max-age=3600

Browsers see no-cache and always revalidate. The CDN caches for an hour. Some providers have their own variants as well, such as Cloudflare-CDN-Cache-Control and Surrogate-Control (Fastly and others). Check your provider’s documentation for precedence rules.

Cache Keys at the CDN

CDNs build cache keys from the URL by default, often including the full query string. This leads to subtle problems:

/products?utm_source=twitter
/products?utm_source=newsletter
/products?ref=homepage

These are three separate cache entries for the same page. Most CDNs let you customize the cache key to ignore marketing parameters, sort query parameters, or include specific headers or cookies. A focused cache key is one of the biggest levers for improving hit rate.

Default Behavior Varies by CDN

Don’t assume your CDN caches everything. Many CDNs only cache certain file extensions (images, CSS, JS) by default and pass HTML through unless you configure it. Others respect Cache-Control fully. Always check with response headers (see Debugging Caching) rather than guessing.

Purging and Invalidation

Unlike browser caches, CDN caches can be cleared on demand. There are three common styles:

Terminal window
# Purge a single URL
curl -X POST "https://api.cdn.example/purge" \
-H "Authorization: Bearer $CDN_TOKEN" \
-d '{"files": ["https://example.com/blog/http-caching"]}'
# Purge by tag (also called surrogate keys or cache tags)
curl -X POST "https://api.cdn.example/purge" \
-H "Authorization: Bearer $CDN_TOKEN" \
-d '{"tags": ["product-42"]}'
# Purge everything (use sparingly: causes a stampede to your origin)
curl -X POST "https://api.cdn.example/purge" \
-H "Authorization: Bearer $CDN_TOKEN" \
-d '{"purge_everything": true}'

Tag-based purging is the most powerful. The origin labels each response with the entities it contains:

HTTP/1.1 200 OK
Cache-Control: public, s-maxage=86400
Cache-Tag: product-42, category-shoes, homepage

When product 42 changes, you purge product-42 and every page that displays it is invalidated: the product page, category listings, the homepage. This lets you use very long CDN lifetimes with near-instant updates. The header name varies by provider (Cache-Tag, Surrogate-Key, and so on).

Caching at the Edge with Workers

Edge runtimes like Cloudflare Workers give you programmatic access to the CDN cache:

export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const cache = caches.default;
// Check the edge cache first
let response = await cache.match(request);
if (response) return response;
// Miss: fetch from origin
response = await fetch(request);
// Only cache successful GET responses
if (request.method === "GET" && response.ok) {
response = new Response(response.body, response);
response.headers.set("Cache-Control", "public, s-maxage=600");
// Store without delaying the response to the user
ctx.waitUntil(cache.put(request, response.clone()));
}
return response;
},
};

Service Worker Caching

Service workers sit between your page and the network, intercepting every request. Unlike HTTP caching, which is driven by headers, service worker caching is driven by your JavaScript, which means you can implement any strategy you want, including full offline support.

How Service Workers Interact with the HTTP Cache

The layers stack like this:

Page → Service Worker → Browser HTTP Cache → Network (CDN → Origin)

When a service worker calls fetch(), that request still goes through the browser’s HTTP cache. This is easy to forget: if app.js has max-age=31536000, the service worker’s “network” fetch may still return a cached copy. Design your headers and service worker together.

The Cache API

Service workers store responses with the Cache API:

const CACHE_NAME = "static-v3";
const PRECACHE_URLS = ["/", "/offline.html", "/styles/main.css", "/app.js"];
// Precache core assets on install
self.addEventListener("install", (event: ExtendableEvent) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS)),
);
});
// Clean up old caches on activate
self.addEventListener("activate", (event: ExtendableEvent) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
),
);
});

Entries in the Cache API never expire on their own. Cache-Control headers on the stored responses are ignored. You’re responsible for versioning and cleanup.

Strategy 1: Cache First

Serve from cache; fall back to the network. Best for fingerprinted static assets and fonts.

async function cacheFirst(request: Request): Promise<Response> {
const cached = await caches.match(request);
if (cached) return cached;
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
}

Strategy 2: Network First

Try the network; fall back to the cache when offline. Best for HTML and API data where freshness matters but offline access is valuable.

async function networkFirst(request: Request): Promise<Response> {
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
} catch {
const cached = await caches.match(request);
return cached ?? (await caches.match("/offline.html"))!;
}
}

Strategy 3: Stale While Revalidate

Serve from cache immediately and update the cache in the background. Best for content where slightly outdated data is acceptable, such as avatars or non-critical API responses.

async function staleWhileRevalidate(
request: Request,
event: FetchEvent,
): Promise<Response> {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(request);
const networkFetch = fetch(request).then((response) => {
if (response.ok) cache.put(request, response.clone());
return response;
});
if (cached) {
// Keep the service worker alive until the background update finishes
event.waitUntil(networkFetch.catch(() => {}));
return cached;
}
return networkFetch;
}

Routing Requests to Strategies

self.addEventListener("fetch", (event: FetchEvent) => {
const { request } = event;
const url = new URL(request.url);
// Only handle same-origin GET requests
if (request.method !== "GET" || url.origin !== self.location.origin) return;
if (request.mode === "navigate") {
event.respondWith(networkFirst(request));
} else if (url.pathname.startsWith("/assets/")) {
event.respondWith(cacheFirst(request));
} else if (url.pathname.startsWith("/api/")) {
event.respondWith(staleWhileRevalidate(request, event));
}
});

Use Workbox in Production

Hand-written service workers are great for learning, but production apps should usually use Workbox, which handles expiration, cache size limits, precache manifests, and many edge cases:

import { registerRoute } from "workbox-routing";
import {
CacheFirst,
NetworkFirst,
StaleWhileRevalidate,
} from "workbox-strategies";
import { ExpirationPlugin } from "workbox-expiration";
registerRoute(
({ request }) => request.mode === "navigate",
new NetworkFirst({ cacheName: "pages" }),
);
registerRoute(
({ request }) => request.destination === "image",
new CacheFirst({
cacheName: "images",
plugins: [
new ExpirationPlugin({
maxEntries: 100,
maxAgeSeconds: 30 * 24 * 60 * 60,
}),
],
}),
);
registerRoute(
({ url }) => url.pathname.startsWith("/api/"),
new StaleWhileRevalidate({ cacheName: "api" }),
);

Caching Recipes for Common Resources

Most sites need only a handful of caching policies. Here’s a reference you can adapt.

Fingerprinted Static Assets

Files with a content hash in the name, such as app.3f9a2c.js or main.b81d.css. Bundlers like Vite, webpack, and Astro produce these automatically.

Cache-Control: public, max-age=31536000, immutable

Cache for a year. When the file changes, its URL changes, so stale copies are never requested again.

HTML Pages

HTML references the fingerprinted assets, so it must update promptly after deploys:

# Always revalidate in the browser; CDN caches with purge on deploy
Cache-Control: no-cache
CDN-Cache-Control: max-age=86400

Or, if you don’t purge on deploy:

Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300

Never put a long max-age on HTML. If a browser caches index.html for a week, users will run last week’s app for a week, and there’s nothing you can do to reach them.

Non-Fingerprinted Static Files

Files with stable URLs, like /favicon.ico, /robots.txt, or /og-image.png:

Cache-Control: public, max-age=86400, stale-while-revalidate=604800

A moderate lifetime with background refresh is a good balance.

Public API Responses

Cache-Control: public, max-age=30, s-maxage=300, stale-while-revalidate=60
ETag: "v42"

User-Specific API Responses

Cache-Control: private, no-cache
ETag: "user-123-v7"

The browser can store it and get cheap 304s, while the CDN never stores it.

Sensitive Data

Cache-Control: no-store

Summary Table

ResourceCache-Control
Hashed JS/CSS/fonts/imagespublic, max-age=31536000, immutable
HTMLno-cache (+ CDN caching with purge)
Stable-URL static filespublic, max-age=86400, stale-while-revalidate=604800
Public APIpublic, max-age=30, s-maxage=300, stale-while-revalidate=60
Per-user APIprivate, no-cache + ETag
Sensitive datano-store

Implementing Caching on the Server

Express

import express from "express";
const app = express();
// Fingerprinted assets: cache for a year
app.use(
"/assets",
express.static("dist/assets", {
maxAge: "1y",
immutable: true,
}),
);
// Everything else in dist: always revalidate
app.use(
express.static("dist", {
setHeaders(res) {
res.setHeader("Cache-Control", "no-cache");
},
}),
);
app.get("/api/me", requireAuth, (req, res) => {
res.setHeader("Cache-Control", "private, no-cache");
res.json(req.user);
});

A Reusable Middleware

import type { RequestHandler } from "express";
type CachePolicy = "immutable" | "page" | "public-api" | "private" | "none";
const POLICIES: Record<CachePolicy, string> = {
immutable: "public, max-age=31536000, immutable",
page: "public, max-age=0, s-maxage=60, stale-while-revalidate=300",
"public-api": "public, max-age=30, s-maxage=300, stale-while-revalidate=60",
private: "private, no-cache",
none: "no-store",
};
export function cache(policy: CachePolicy): RequestHandler {
return (_req, res, next) => {
res.setHeader("Cache-Control", POLICIES[policy]);
next();
};
}
// Usage
app.get("/api/products", cache("public-api"), listProducts);
app.get("/api/cart", cache("private"), getCart);
app.post("/api/payment", cache("none"), createPayment);

Centralizing policies in one place keeps headers consistent and makes them easy to audit.

Static Hosts and Frameworks

Many hosts and frameworks let you declare headers in config. For example, Netlify and Cloudflare Pages support a _headers file:

/assets/*
Cache-Control: public, max-age=31536000, immutable
/*
Cache-Control: public, max-age=0, must-revalidate

Frameworks also set caching headers for you. Next.js, for instance, emits s-maxage and stale-while-revalidate for pages that use time-based revalidation. Check what your framework sends before layering your own headers on top. If you’re deciding between rendering approaches, our guide to SSR, SSG, ISR, and streaming covers how each strategy interacts with caching.


Debugging Caching

Inspect Headers with curl

Terminal window
# Show response headers only
curl -sI https://example.com/assets/app.3f9a2c.js
# Test a conditional request
curl -sI https://example.com/api/products \
-H 'If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4"'
# Compare compressed vs uncompressed responses
curl -sI https://example.com/ -H "Accept-Encoding: br"

Read CDN Status Headers

Most CDNs add a header that reports what happened:

CF-Cache-Status: HIT # Cloudflare
X-Cache: Hit from cloudfront # CloudFront
X-Cache: HIT, MISS # Fastly (one entry per cache layer)
Age: 1834 # Seconds the response has been cached

If you see MISS on every request, check for Vary: Cookie, a Set-Cookie header on the response, unique query strings, or private/no-store directives.

Chrome DevTools

In the Network panel:

  • The Size column shows (memory cache), (disk cache), or (ServiceWorker) for cache hits
  • A 304 status indicates successful revalidation
  • Disable cache (checked by default in many setups!) bypasses the HTTP cache while DevTools is open, so uncheck it when testing caching
  • Application → Cache Storage shows service worker caches; Application → Service Workers lets you update or unregister workers

Understand Reload Behavior

How you load the page changes caching behavior:

ActionBehavior
Navigate via link or address barNormal caching rules
Normal reloadRevalidates the main document; fresh subresources are generally reused
Hard reload (Cmd/Ctrl+Shift+R)Bypasses the cache for the page and its subresources
Back/forward navigationMay restore the entire page from the back/forward cache

When testing, use normal navigation to see what real users experience.


Common Pitfalls and Solutions

❌ Pitfall 1: Long max-age on HTML

# ❌ Users may run a stale app for a week after you deploy
Cache-Control: max-age=604800
# ✅ Always revalidate HTML; cache hashed assets long-term
Cache-Control: no-cache

Browser caches can’t be purged. Once a response with a long max-age is out there, it stays until it expires or the user clears their cache.

❌ Pitfall 2: Long-Caching Non-Fingerprinted URLs

# ❌ /js/app.js changes on every deploy, but the URL doesn't
GET /js/app.js
Cache-Control: max-age=31536000, immutable
# ✅ Put a content hash in the URL
GET /js/app.3f9a2c.js
Cache-Control: max-age=31536000, immutable

Query-string versioning (app.js?v=42) also works, but some proxies and CDN configurations ignore query strings in cache keys. A hash in the filename is more reliable.

❌ Pitfall 3: Caching Personalized Responses at the CDN

# ❌ The CDN serves Alice's dashboard to Bob
GET /dashboard
Cache-Control: public, max-age=300
# ✅ Keep per-user content out of shared caches
GET /dashboard
Cache-Control: private, no-cache

This is a security bug, not just a performance bug. Audit every route that reads cookies or session data and make sure it’s private or no-store. For more on protecting user data, see our guide to web security best practices.

# ❌ Every cached copy hands out the same session cookie
HTTP/1.1 200 OK
Cache-Control: public, s-maxage=3600
Set-Cookie: session=abc123

Many CDNs refuse to cache responses with Set-Cookie (killing your hit rate), and the ones that do may hand the same cookie to every visitor. Don’t set cookies on pages you want to cache publicly. Move session creation to a separate request or to uncached routes.

❌ Pitfall 5: Thinking no-cache Means “Don’t Cache”

# ❌ Intended: "never store this sensitive page"
Cache-Control: no-cache
# ✅ no-store is what actually prevents storage
Cache-Control: no-store

❌ Pitfall 6: Inconsistent ETags Across Servers

If ETags are derived from file inode numbers or modification times (as some servers do by default), each server behind a load balancer may generate a different ETag for the same file. Every revalidation that lands on a different server becomes a full 200 download. Use content-based ETags, or let your CDN handle validation.

❌ Pitfall 7: Forgetting the Service Worker

A service worker using cache-first for HTML will keep serving the old app after a deploy, regardless of your HTTP headers. Use network-first for navigations, version your caches, and clean up old ones in the activate event. If you need an emergency escape hatch, the Clear-Site-Data header can wipe a site’s caches and storage:

Clear-Site-Data: "cache", "storage"

Note that "storage" includes service worker registrations, local storage, and IndexedDB, so use it with care.


Best Practices

✅ Practice 1: Always Send an Explicit Cache-Control

Never rely on heuristic caching. Every response from your server should declare its policy, even if that policy is no-cache.

✅ Practice 2: Fingerprint Everything You Can

Content-hashed filenames are what make max-age=31536000, immutable safe. Let your bundler do it, and keep only HTML and a few well-known files at stable URLs.

✅ Practice 3: Cache Long at the CDN, Short in the Browser

Use s-maxage or CDN-Cache-Control for long shared caching, and purge on deploy or content change. Keep browser lifetimes short for anything that isn’t fingerprinted, because browser caches can’t be purged.

✅ Practice 4: Use stale-while-revalidate Generously

For most content, a few seconds or minutes of staleness is invisible to users, and serving instantly from cache is a large win for Core Web Vitals like LCP and TTFB.

✅ Practice 5: Keep Cache Keys Small

Avoid Vary: Cookie and Vary: User-Agent, strip tracking query parameters at the CDN, and don’t put per-user data in URLs that should be shared.

✅ Practice 6: Centralize Caching Policies

Define a small set of named policies (immutable, page, private, and so on) and apply them consistently, rather than writing ad hoc headers in every route handler.

✅ Practice 7: Monitor Your Hit Rate

Track your CDN’s cache hit ratio and origin request volume. A sudden drop usually means a new Set-Cookie, Vary, or query parameter slipped into a hot path.


Conclusion

HTTP caching is a layered system, and each layer has its own job. Browsers give each user instant repeat visits. CDNs absorb traffic and bring content close to users. Service workers add programmable control and offline support. Getting the headers right ties all three together.

Key Takeaways:

  • Fresh responses are served without a network request; stale responses need revalidation, which ETags and 304 Not Modified make cheap
  • no-cache means “revalidate before use”, while no-store means “never store”
  • Fingerprinted assets should be cached for a year with immutable; HTML should almost always be no-cache in the browser
  • s-maxage and CDN-Cache-Control let you cache aggressively at the CDN, where you can purge, while keeping browser caches short
  • stale-while-revalidate removes revalidation latency from the user’s path, and stale-if-error keeps you online during outages
  • Vary and cache keys determine hit rate, so keep them small and never vary on cookies or user agents in shared caches
  • Personalized responses must be private or no-store. Caching them publicly is a security bug.
  • Service workers sit on top of the HTTP cache and need their own versioning and cleanup

Start by auditing the headers your site sends today with curl -I. Fix any HTML with a long max-age, make sure your hashed assets are cached for a year, and check that no personalized routes are publicly cacheable. Those three changes alone resolve most real-world caching problems.

For more on related topics, check out our guides on web performance optimization, server-side rendering strategies, and API design best practices.