Skip to content

Web & Internet

HTTP Caching (ETag)

O(n) to compute a fingerprint over content of length n, but a cache hit then costs O(1) to confirm — no resending the content at all.

The idea, in plain English

HTTP (HyperText Transfer Protocol) caching is like leaving a dated sticky note on your fridge. Once you've checked the milk and it's fine, the note lets you skip re-checking it every time you open the door — you just glance at the note. An ETag (short for 'Entity Tag') is a short fingerprint the server calculates from a piece of content. It works the same way for a web page or file. The server hands your browser a fingerprint of the content. Next time, your browser says 'I already have the copy with fingerprint X — did it change?' If the server computes that same fingerprint again, it can say 'nope, still good' without resending the whole thing.

How it works

  1. 1The server computes a fingerprint, the ETag, from the content it's about to send, and attaches it to the response.
  2. 2The browser stores the content and its ETag together in its local cache.
  3. 3Next time the browser wants that same resource, it sends the ETag it already has along with the request, instead of assuming it needs a fresh copy.
  4. 4The server recomputes the current content's fingerprint and compares it to the one the browser sent.
  5. 5If the fingerprints match, the server replies '304 Not Modified' with no body, and the browser reuses its cached copy. If they differ, the server sends the full new content along with a new ETag.

When you'd use it

This applies to images, stylesheets, scripts, and API (Application Programming Interface) responses that don't change on every request — anywhere re-downloading identical data would waste bandwidth and time.

Common beginner mistakes

  • Don't assume a cached response means 'old' or 'stale' data. A fresh 304 check confirms the content is still current, so a cache hit can be exactly as up to date as a full re-download, just faster.
  • Don't use a fingerprint function whose output stays the same even when the content changes. If even a tiny edit doesn't produce a new ETag, browsers keep serving stale content by mistake.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
First request status: 200 etag: etag-1206 body: Welcome home!
Second request (same etag) status: 304 etag: etag-1206 body: (empty)
Third request (content changed) status: 200 etag: etag-2062 body: Welcome home! (updated)

Not sure this is the right topic? See the learning paths → or where this leads →