ETag vs Last-Modified: Debug HTTP 304 and Revalidation
Understand HTTP validators, If-None-Match precedence and bodyless 304 responses. Includes a local Python server and curl checks for conditional requests.
ETag identifies a selected representation; Last-Modified gives its modification time. A conditional GET can receive 304 when the validator still matches, allowing a cache to reuse its stored body. If-None-Match takes precedence over If-Modified-Since. A 304 has no response body and is not an HTTP redirect.
First decide whether the client needs a request at all
A browser shows an old response, a network panel shows 304, and an API client reports an empty body. These observations can describe three different behaviors. Start by separating a fresh cache hit, a conditional request that validates stored content, and an ordinary response with a new representation.
Freshness policy tells a cache when it may reuse a stored response without validation. A validator gives the server a way to compare the client’s stored version with the selected representation. An ETag does not, by itself, specify a freshness lifetime. A response can carry a validator and still require contact with the server before every reuse.
For example, an unqualified Cache-Control: no-cache permits storage but requires successful validation before reuse. It does not mean “never store.” Cache-Control: no-store is the separate storage prohibition. A private response is intended for a private cache rather than a shared cache; it is not a substitute for authentication or transport encryption.
| Observation | Interpretation | Evidence to inspect |
|---|---|---|
| No network exchange | May be a fresh cache hit or application storage | Cache policy, browser tools and application behavior |
| Conditional request, 304 | Stored representation was validated | Request validators, returned metadata and stored body |
| Conditional request, 200 | Server sends the selected representation | Body, validator and representation selection |
| 304 but client has no body | Client lacks usable stored content | Retry strategy and local cache state |
Choose a validator that describes the representation
An entity tag is an opaque quoted token supplied by the server. Treat it as a comparison value, not a timestamp, sequence number or universal checksum. A server may generate it from content bytes or another reliable version identity, provided it respects the required comparison semantics.
A strong validator distinguishes representation data changes relevant to byte-for-byte identity. A weak tag begins with W/ and allows semantic equivalence without asserting identical bytes. If-None-Match uses weak comparison for cache validation: the opaque tag can match even when one side has the weak prefix. That rule should not be generalized to strong preconditions or range handling.
Last-Modified is an HTTP date expressing when the selected representation was modified. Date is different: it concerns message origination. Do not generate Last-Modified from the current request time merely to make a header present. Modification times have limited precision and may be insufficient when several changes happen within the same second.
For a negotiated endpoint, identify which representation the tag describes. A gzip representation, an identity representation and a different language variant are not automatically interchangeable. Review Vary and cache selection alongside validator generation rather than assigning one strong tag to inconsistent byte sequences.
Source: MDN: ETag ↗
Read the conditional exchange in order
An initial GET can return 200 with a body, ETag, Last-Modified and cache-control metadata. A client that stores the representation can later send If-None-Match with the saved tag. If the selected representation matches for GET or HEAD, the server can return 304 instead of retransmitting the body.
With no If-None-Match, a client can use If-Modified-Since based on the stored Last-Modified value. When both request fields are present, If-None-Match controls the comparison and If-Modified-Since is ignored. A nonmatching tag must not become “not modified” merely because a supplied date looks recent.
A 304 has no message body. Its metadata helps a cache identify and update the stored response; the reusable content remains the previously stored body. It is not a redirect to another URL. A low-level HTTP client that manually sends a validator without storing a body must handle that situation explicitly instead of attempting to decode empty bytes as JSON.
Run a small loopback-only revalidation lab
Save the Python below as revalidate_lab.py and run python revalidate_lab.py in a disposable directory. It serves one fixed JSON representation on port 8765, computes its tag from those bytes and assigns a fixed modification time. If the port is occupied, choose another local port in both the script and client commands.
The server is an instructional fixture, not production middleware. It implements the GET/HEAD validation cases discussed here, including a tag list, weak tag comparison and invalid-date fallback. It does not implement authentication, negotiated variants, range requests, write preconditions or a persistent cache. Use a framework’s supported conditional-response mechanism for a real API.
The published fixture was exercised locally with a standard HTTP client and curl. Tests checked initial content, bodyless validation responses, tag/date precedence, weak tags, tag lists, invalid dates and a changed representation. These are deterministic protocol cases, not a browser-cache, CDN or performance test.
import hashlib
import re
from datetime import datetime, timezone
from email.utils import format_datetime, parsedate_to_datetime
from http.server import BaseHTTPRequestHandler, HTTPServer
BODY = b'{"version":1}\n'
MODIFIED = datetime(2026, 10, 1, tzinfo=timezone.utc)
def tag_matches(value, current):
value = value.strip()
if value == "*":
return True # This fixture's representation exists.
token = r'(?:W/)?"[\x21\x23-\x7e\x80-\xff]*"'
if not re.fullmatch(r'\s*' + token + r'(?:\s*,\s*' + token + r')*\s*', value):
return False
return any(t.removeprefix("W/") == current
for t in re.findall(token, value))
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
etag = '"' + hashlib.sha256(BODY).hexdigest() + '"'
inm = self.headers.get("If-None-Match")
unchanged = False
if inm is not None:
unchanged = tag_matches(inm, etag)
elif self.headers.get("If-Modified-Since"):
try:
since = parsedate_to_datetime(self.headers["If-Modified-Since"])
if since.tzinfo is None:
since = since.replace(tzinfo=timezone.utc)
unchanged = MODIFIED <= since
except (ValueError, TypeError, OverflowError):
pass
self.send_response(304 if unchanged else 200)
self.send_header("ETag", etag)
self.send_header("Last-Modified", format_datetime(MODIFIED, usegmt=True))
self.send_header("Cache-Control", "private, no-cache")
if not unchanged:
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
if not unchanged and self.command != "HEAD":
self.wfile.write(BODY)
do_HEAD = do_GET
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()Store the first body before sending its validator back
In a second terminal in the lab directory, run the commands below. The first request saves the ETag and body. The second sends the saved tag and is expected to show 304. Keep the first body file: curl’s validator-file options do not turn it into a general response cache that automatically reconstructs content from a 304.
The date-only request is expected to validate because it equals the fixture’s modification time. The final request deliberately combines a nonmatching tag with that same date and is expected to return 200. This makes precedence visible without relying on a browser cache. All requests stay on loopback and use synthetic data.
To test a representation change, stop the server, change BODY to a different JSON version, advance MODIFIED consistently and restart. The computed ETag changes with the bytes. Repeating the old ETag comparison should then return 200 with the new body; save the new tag only after handling that response.
curl --silent --show-error --dump-header first.headers \
--etag-save saved.etag --output first.json http://127.0.0.1:8765/
curl --silent --show-error --include \
--etag-compare saved.etag http://127.0.0.1:8765/
curl --silent --show-error --include \
--header 'If-Modified-Since: Thu, 01 Oct 2026 00:00:00 GMT' \
http://127.0.0.1:8765/
curl --silent --show-error --include \
--header 'If-None-Match: "different-version"' \
--header 'If-Modified-Since: Thu, 01 Oct 2026 00:00:00 GMT' \
http://127.0.0.1:8765/Diagnose unexpected 200, 304 and stale content separately
If a validator request always returns 200, first confirm that the request actually contains the saved field, including its quotes. Inspect the same URL, credentials and representation-selection headers. Then check whether the serving layer generates validators consistently. A changing request-specific token is not useful for validating unchanged content.
If changed content incorrectly receives 304, compare the tag-generation input with the bytes delivered to the client. A revision identifier that ignores template, locale or compression changes may describe the wrong representation. A timestamp that was not updated with the content can cause a similar problem for date validation.
If an application shows stale data while the origin behaves correctly, inspect the route through browser cache, service worker, CDN and origin. A fresh cached response may avoid revalidation entirely until its policy requires it. A 304 seen on one hop does not prove every layer stores the expected body or uses the same cache key.
For personalized data, review shared-cache eligibility and identity boundaries before tuning hit rates. Validators do not grant permission to reuse one user’s response for another. Keep cache-control policy, authentication and representation selection explicit. Troubleshooting should use safe test accounts and synthetic bodies rather than publishing cached private payloads.
Finish with a small, repeatable client contract
A client that manages validators itself needs a consistent association between URL, selected variant, body and validator. On 200, replace the stored representation and relevant metadata. On a usable 304, retain the body and update applicable metadata. If no body is available, recover with a normal retrieval according to the client’s supported mechanism instead of inventing an empty successful result.
Keep write-concurrency controls separate from this GET lab. Conditional retrieval explains whether a stored response remains reusable; it does not implement safe retries of a payment or prevent a lost update in a document editor. Those operations need their own method semantics and preconditions.
The useful success condition is not “we got a 304.” It is that unchanged content avoids retransmission, changed content reaches the client, and the stored representation is reused only under the intended policy. Preserve these cases as regression tests through the actual serving route when adding a proxy or changing representation generation.
Source: MDN: 304 Not Modified ↗
Your next steps
- Separate freshness from validation: a stored response may need revalidation before reuse.
- Keep validators tied to the selected representation and honor If-None-Match precedence; do not parse a 304 as a new JSON body.
- Test unchanged and changed representations through the same route, then inspect cache keys and intermediaries when production behavior differs.
Sources & official resources
Linked resources checked on 2026-10-25. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →