← Building blocks

Let browsers and proxies cache

Networking & deliveryfundamental

Clients re-download unchanged resources on every visit.

Say it like this

Most of what a client fetches has not changed, so I version static assets by content hash and cache them for a year, and give everything else a validator so the client can revalidate with a 304 instead of re-downloading.

Basic solution

Set Cache-Control with long max-age for versioned assets, ETag / Last-Modified for revalidation, and immutable for content-addressed files.

Cache-ControlETagcontent-hashed filenames

Immutable assets, revalidated pages

Hashed assets are served from the browser cache for a year with no request. HTML and API responses carry an ETag and return a 304 when unchanged. Tracked redirects are no-store so every click reaches the server.

How it works

  1. The server sets a Cache-Control header on each response that tells browsers and intermediate caches how long they may reuse it. For a content-hashed asset: public, max-age=31536000, immutable, meaning anyone may cache it for a year and it will never change. For an API response or HTML page: no-cache (store it, but check with the server before reusing) or a short max-age, plus private if the body is specific to one user.
  2. The server also attaches a validator, a small value that identifies this exact version of the body: an ETag (typically a hash of the content) or a Last-Modified timestamp.
  3. The browser, and any proxy or CDN between it and the server, stores the response together with those headers. While max-age has not elapsed, a repeat request for the same URL is answered from the local copy with no network traffic at all.
  4. After max-age elapses, or on every request for a no-cache response, the client sends a conditional request: the same GET plus an If-None-Match header carrying the stored ETag. If the server's current version has the same ETag, it replies 304 Not Modified with no body, and the cache marks its copy fresh again. If not, the server sends the full new response.
  5. When content changes, the two kinds of resource behave differently. A hashed asset gets a new filename and therefore a new URL, so the old cached copy is simply never requested again. A mutable resource keeps its URL but gets a new ETag, so the next revalidation returns the new body.

The two directives people confuse

  • no-cache means store it but revalidate before using it. no-store means never store it at all. Private pages are usually private, no-cache; secrets and anything that must be observed on every request are no-store.

Worked example

URL shortener dashboard and redirects

  • The dashboard loads a 400 KB JavaScript bundle and 80 KB of CSS. With content-hashed names (app.3f9a1c.js) and max-age one year, a returning user makes zero asset requests until the next deploy, which changes the hash and therefore the URL.
  • 100K dashboard visits/day; 80% are returning users. Without caching: 100K × 480 KB ≈ 48 GB/day. With hashed assets: 20K × 480 KB ≈ 9.6 GB/day, and the HTML (3 KB, no-cache) revalidates with a 304 most of the time.
  • The stats API (GET /v1/urls/{alias}/stats) returns private, no-cache with an ETag computed from the last aggregation timestamp. Polling every 30 s from an open dashboard costs a 304 of about 200 B instead of a 20 KB body when nothing changed.
  • Redirect responses: a 302 is sent with Cache-Control: no-store so the browser asks every time and every click is counted; a 301 is cacheable by default and would hide repeat clicks.
  • CDN layer: the same headers drive the edge. Hashed assets hit at 99%+; the HTML revalidates against the origin every request, which is cheap because it is a 304 almost always.

Variants and when each wins

Content-hashed URLs with immutable caching

  • The build renames each file by a hash of its content and the HTML references the new names. It wins for static assets, because caching is perfect for a year and invalidation is simply a new URL.

Revalidation with ETag or Last-Modified

  • The URL stays stable and the client checks with the server before reusing its copy. It wins for HTML pages and API responses whose URL must not change; it costs a request per use but not a body when nothing changed.

stale-while-revalidate

  • The cache serves its expired copy immediately and fetches a fresh one in the background for the next request. It wins for semi-static data that tolerates a few seconds of staleness, because the user never waits on the revalidation round trip.

Service worker or application-level caching

  • The web app itself decides what to keep offline and when to refresh it, using a script that intercepts its own requests. It wins for mobile web apps that must work offline; the cost is a second cache layer to reason about.

Recommendation: hashed and immutable for assets, no-cache with ETags for HTML and APIs, stale-while-revalidate on semi-static API data, no-store on anything sensitive or that must be counted.

Failure modes

Users stuck on an old file after a deploy

  • A bug fix is live, but some users keep seeing the old behaviour. A long max-age was set on an unversioned URL such as app.js, so their browsers keep serving the cached copy without asking. Use content-hashed filenames so a deploy changes the URL, and never put a long max-age on a URL whose content can change.

Private data cached in a shared cache

  • One user sees another user's dashboard. An authenticated response was marked public, or carried no Cache-Control at all so a proxy applied its defaults and stored it for everyone. Mark every per-user response private, no-cache (or no-store), and add Vary: Cookie or Vary: Authorization where the body depends on those headers.

Weak ETags that change on every response

  • Revalidation never returns a 304, so every request downloads the full body. The ETag is computed from something that changes every time, such as a timestamp or a request id, instead of from the content. Derive the ETag from the body or from the data's version number only.

Redirects cached by accident

  • Click counts drop and edits to a link's target never take effect for some users. The redirect was a 301, or a 302 without no-store, so browsers and the CDN cached it and stopped asking the server. Serve trackable redirects as 302 or 307 with Cache-Control: no-store.

Vary header blowing up the cache

  • A public resource has a surprisingly low cache hit rate. The response says Vary: User-Agent or Vary: Cookie, so the cache keeps a separate copy for every distinct browser string or cookie even though the body is identical. Vary only on headers that actually change the body, which is normally just Accept-Encoding.

Interviewer follow-ups

Answer out loud before you open each one.

What is the difference between no-cache and no-store?

no-cache lets caches store the response but requires revalidation with the origin before each reuse, so you get 304s and bandwidth savings. no-store forbids storing it at all, which is right for secrets and for responses that must be observed every time, like a tracked redirect.

How does a 304 save bandwidth if the client still makes a request?

The request and the 304 are a few hundred bytes with no body. For a 20 KB API response or a 400 KB bundle that is a 50 to 1000× reduction while still guaranteeing freshness. The round trip remains, which is why assets use long max-age instead and only HTML and APIs revalidate.

Why do content-hashed filenames make invalidation trivial?

The old file is never invalidated; it is simply no longer referenced. The new HTML points at the new hash, so clients fetch the new file under a new URL and the old cached copy expires unused. Invalidation becomes a deploy of a 3 KB HTML file.

Should the shortener cache redirect responses at the CDN?

Only for links that are immutable and do not need per-click analytics. A cached redirect keeps sending users to a target after it was changed or deleted until the TTL or a purge. Most products keep redirects at the application layer behind Redis and use the CDN for assets and TLS.

Connections

In study paths
Video from upload to play
Pairs with
Serve static bytes from the edge · Pick the right redirect · Put a reverse proxy in front · Send fewer bytes · Invalidate the cache when data changes
Used in
Video Streaming Platform (YouTube / Netflix) · URL Shortener (TinyURL / bit.ly)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon CloudFrontCDN edgeCloud CDN, Media CDNAzure Front DoorCloudflare, Fastly, Akamai
Amazon EC2 Auto ScalingHTML / stats APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad