HTTP, TLS & Web Performance

ETags and Conditional Requests

Learn how validators save bandwidth with 304 responses and stop two editors from overwriting each other's changes.

Key takeaways

  • A GET with If-None-Match lets the server answer 304 Not Modified without sending the body again.
  • If-Match on an update makes the server reject the change if someone else modified the resource first.
  • Strong ETags promise byte-for-byte identity, while weak ones, prefixed W/, only promise equivalent content.
  • ETags save transfer but still cost a round trip, so they work best alongside sensible cache lifetimes.
  • Servers behind a load balancer must generate the same tag for the same content.

An ETag, short for entity tag, is a label the server attaches to a specific version of a resource. Later, the client sends that label back and says "only act if this still matches" or "only send the data if it doesn't". These conditional requests save bandwidth on unchanged content and protect against lost updates when several clients edit the same thing.

The server decides what goes into the tag. The client treats it as an opaque string to be returned exactly as received.

The basic exchange

On the first request, the server includes the tag in its response:

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-cache
ETag: "v7-9c41"

The quotation marks are part of the value. When the client wants the resource again, and its copy is no longer fresh, it asks conditionally:

GET /api/products/42 HTTP/1.1
Host: example.com
If-None-Match: "v7-9c41"

If the current tag matches, the server replies 304 Not Modified with headers and no body. If it doesn't match, the server sends a normal 200 with the new content and its new tag.

Revalidating a cached resource
Browser Server GET /logo.svg 1 200 with body and ETag A 2 GET again, If-None-Match: A 3 304 Not Modified, no body 4 Later, If-None-Match: A 5 200 with new body and ETag B 6 The file has changed Browser Server GET /logo.svg 1 200 with body and ETag A 2 GET again, If-None-Match: A 3 304 Not Modified, no body 4 Later, If-None-Match: A 5 200 with new body and ETag B 6 The file has changed

Browsers do this automatically for cached responses. You only need to send the validator and handle the conditional request on the server, which most web servers already do for static files.

Freshness comes first

A browser doesn't revalidate while its copy is still fresh. Cache-Control: max-age=600 means ten minutes of reuse with no request at all. After that, or immediately if the response said no-cache, the validator comes into play. The two mechanisms divide the work, and Cache-Control headers explains the freshness half.

A 304 saves the body, which can be large, but not the round trip. On a high-latency connection, fifty small revalidations can feel slow even though little data moves. For files with versioned names, skip revalidation with a long lifetime.

Last-Modified, the date-based validator

Last-Modified gives the time the resource last changed, and the client returns it in If-Modified-Since. It's simple and widely supported, but its resolution is one second, and timestamps can change without the content changing, for example when files are copied during a deployment.

You can send both. When a request contains both If-None-Match and If-Modified-Since, a server that follows RFC 9110, which defines HTTP semantics, evaluates the ETag condition and ignores the date.

Strong and weak tags

A strong ETag such as "abc123" identifies exact bytes. A weak one such as W/"abc123" says two representations are equivalent in meaning, even if some bytes differ.

Weak tags are fine for cache revalidation with If-None-Match. They can't be used where exact bytes matter, such as combining partial downloads, and If-Match requires a strong comparison.

Compression introduces a subtlety. The gzip, Brotli and plain versions of a file are different byte sequences, so a strong tag should differ between them. Some servers handle this by adding a suffix, others by weakening the tag when they compress on the fly. nginx does the latter. See compression with gzip and Brotli.

Preventing lost updates

Say two people open the same record in an editing tool. Each changes a different field and saves. Without a check, the second save silently replaces the first.

With ETags, each save states which version it was based on:

PUT /api/articles/17 HTTP/1.1
Host: example.com
Content-Type: application/json
If-Match: "rev-5"

The server compares rev-5 with the current tag. If they match, it applies the update and returns the new tag. If someone else has saved in between, it returns 412 Precondition Failed. The client then fetches the latest version and lets the user merge or retry. This approach is called optimistic concurrency, since nothing is locked while people work.

Optimistic concurrency with If-Match
1 Read Fetch the record and keep its ETag. 2 Edit Work locally without locking anything. 3 Write Send changes with If-Match. 4 Compare Server checks the current version. 5 Resolve On 412, reload, merge and try again. Read Fetch the record and keep its ETag. 1 Edit Work locally without locking anything. 2 Write Send changes with If-Match. 3 Compare Server checks the current version. 4 Resolve On 412, reload, merge and try again. 5

A server can insist on this by answering unconditional updates with 428 Precondition Required, a status defined in RFC 6585. To create something only if it doesn't exist yet, send If-None-Match: * with the PUT.

The comparison and the write must happen as one atomic step, for example a database update that includes the expected revision in its WHERE clause. Checking first and writing afterwards leaves a gap for another request to slip into. Methods and their expectations are covered in HTTP methods.

Conditional requests in your own API client

Browsers handle validators for cached responses, but scripts, mobile apps and server-to-server integrations often have to do it themselves. The pattern is small. Store the body and the tag together. On the next request, send the tag in If-None-Match. If the answer is 304, reuse the stored body. If it's 200, replace both.

Keep the two in step. Saving a new tag while failing to save the new body leaves a client convinced it's up to date when it isn't. Write them in one operation, and discard both if parsing fails.

This pays off in polling. An integration that checks a feed or a list every minute can receive a tiny 304 most of the time. Some APIs also count conditional requests differently against their rate limits, so read the provider's documentation. Polite polling habits are discussed in API rate limits and polite clients.

For updates, design the user experience around 412. Telling someone "your save failed" is unhelpful. Show what changed since they opened the record, keep their unsaved input and let them choose. When two edits touch different fields, an application can sometimes merge them safely, but it should do so only where the data model makes that unambiguous.

Resuming downloads

Range requests ask for part of a file. If-Range makes them safe: the client sends the range it wants along with the ETag or date of the part it already has. If the file hasn't changed, the server sends 206 Partial Content. If it has, the server sends the whole new file with 200, so the client doesn't stitch together two different versions.

How to generate a tag

Common choices include:

  • A hash of the response body. Accurate, but you have to build the whole response to compute it, which saves bandwidth only.
  • A version number or revision column. Cheap and lets you answer 304 before doing expensive rendering.
  • Modification time plus size. What many web servers use for static files.

If the page depends on several things, such as a template, a record and the signed-in user, all of them need to influence the tag. A tag that ignores one will keep stale content alive.

Consistency across servers

When several machines serve the same site behind a load balancer, identical content should produce identical tags. If tags include something specific to one machine, such as a file system inode number, or if each server has different file timestamps, clients bounce between mismatched tags and redownload everything. Apache's FileETag directive controls which attributes are used. Deploying the same build artifact with preserved timestamps, or using content hashes, avoids the problem.

Testing from the command line

curl -i https://example.com/logo.svg
curl -i -H 'If-None-Match: "paste-the-tag-here"' https://example.com/logo.svg

Copy the tag with its quotation marks, including any W/ prefix. The second command should show 304. In Windows PowerShell, use curl.exe, and watch the quoting rules; running from a Bash shell is often simpler.

Which status code to expect

Situation Request condition Result
Cached copy still current If-None-Match matches on GET 304 Not Modified
Cached copy outdated If-None-Match differs 200 with new body
Safe update If-Match matches The update proceeds
Someone else saved first If-Match differs 412 Precondition Failed
Create only if absent If-None-Match: * and it exists 412 Precondition Failed
Server requires a condition None sent 428 Precondition Required

Preconditions don't replace permission checks. The server should first decide whether this client may read or change the resource, and only then evaluate the condition. Otherwise a stranger could learn whether a guessed tag matches something they aren't allowed to see. For the wider picture of response codes, see status codes by family.

Adding ETags to an application

If your framework doesn't do it for you, start with one expensive, frequently read endpoint. Choose a value that changes exactly when the output changes, such as a revision number combined with the template or code version. Read it before doing the heavy work, compare it with the incoming header, and return early with 304 on a match. Remember that If-None-Match may list several tags separated by commas.

Then test the unhappy cases: a deployment that changes the page layout but not the data, a different language, and a signed-in user. Each should receive a different tag when the bytes it gets are meaningfully different.

What can go wrong

  • Tags that change on every request, often because a timestamp or random token sits in the body being hashed.
  • Proxies that strip or rewrite tags when they modify content.
  • A 304 with missing headers. Send ETag, Cache-Control and Vary as you would on the full response.
  • Privacy side effects. A unique tag per visitor could act as an identifier, so tags should describe content, not people.

Common questions

Do I need ETags if I use versioned filenames?

Rarely for those files, because they're never revalidated while fresh. HTML pages and API responses, whose addresses stay the same as content changes, benefit most.

Do conditional requests reduce server load?

They reduce transfer. Processing falls only if your server can determine the current tag cheaply, for instance from a stored revision number, without generating the full response first. For caching closer to visitors, see how a CDN speeds up a website.

Written for 4Internet with AI writing tools and not reviewed line by line by a person. Check anything you rely on with the maker, provider or standard concerned. Report an error.

Keep reading

All 45 articles in HTTP, TLS & Web Performance →

Latest news on this topic