Performance & Debugging

Implement HTTP Caching with Correct Validators and Cache Keys

Use Cache-Control, ETag, Last-Modified, and deliberate cache keys to reduce latency without serving the wrong representation.

Implement HTTP Caching with Correct Validators and Cache Keys

Overview

Build HTTP caching policies around freshness, validation, privacy, and the dimensions that actually change a response.

Separate public and private responses

Static assets with content-hashed filenames can use long-lived immutable caching because a changed asset receives a new URL. Public pages may use short freshness lifetimes and validators. Responses containing account data, private dashboards, or user-specific information need conservative policies such as private or no-store, depending on the sensitivity and desired browser behavior.

Use validators for revalidation

An ETag identifies a representation. A client can send it in If-None-Match; if the resource is unchanged, the server can return 304 Not Modified without retransmitting the body. Last-Modified and If-Modified-Since provide a time-based alternative, though timestamps can be less precise.

Cache-Control: public, max-age=300, stale-while-revalidate=60
ETag: "article-v42"
Vary: Accept-Encoding

Make cache keys explicit

A cache key commonly includes the URL and may include selected request headers. Use Vary only for headers that genuinely affect the representation. Unbounded variation, such as varying on arbitrary cookies, can destroy cache efficiency. Ensure language, compression, and device variants are represented consistently if they change the response.

Verify behavior end to end

Inspect browser and CDN response headers, test conditional requests, and confirm that a user-specific response cannot enter a shared cache. Purge or version assets deliberately during deployment. A cache policy is correct only when freshness and privacy remain correct under real navigation and authentication flows.

Implementation checklist

  • Define the expected behavior and supported environments.
  • Keep security, accessibility, and failure states in the design.
  • Measure the result with representative user journeys.
  • Document operational assumptions and review them after changes.
Share this page Help other developers discover this resource.