Does your server ever answer 304? Test ETag and Last-Modified revalidation in Python
When a crawler comes back to a page it already has, the cheapest answer a server can give is 304 Not Modified with no body. The crawler keeps its copy, your server skips the transfer, and nobody pays for bytes that did n
When a crawler comes back to a page it already has, the cheapest answer a server can give is 304 Not Modified with no body. The crawler keeps its copy, your server skips the transfer, and nobody pays for bytes that did not change. Whether that happens depends on two things you control: whether the server sends a validator (an ETag or a Last-Modified header), and whether it actually respects the validator when it comes back.
This post is a short, dependency-free Python script that tests both. For one URL it makes up to six requests: two plain ones to see whether the validators stay stable, then conditional ones that send the validators back, plus two negative controls that send a validator that cannot match. It is part of my series on small Python checks for technical SEO. It pairs with the sitemap lastmod audit, which compares sitemap dates with the same Last-Modified header, and with the redirect tracer, because the URL you test should be the final one.
What Google documents about HTTP caching
I looked these up on 12 November 2026:
- Google's crawling infrastructure supports
ETagwithIf-None-MatchandLast-ModifiedwithIf-Modified-Since, as defined by the HTTP caching standard. - If a response carries both, Google's crawlers use the
ETag. Google recommendsETagfor its crawlers because it has no date formatting issues, and it also suggests setting both headers, because other applications such as CMSes use them. - A
Last-Modifieddate has to follow the HTTP format. Google's example isFri, 4 Sep 1998 19:15:56 GMT. -
Cache-Control: max-ageis optional but suggested. It is the expected number of seconds the content will stay unchanged, and it helps crawlers decide when to recrawl. Other HTTP caching directives are not supported. - Individual Google crawlers may or may not use caching, depending on the product they serve. Googlebot supports it when it recrawls URLs for Google Search.
I could not find anything in Google's pages about how often Googlebot sends conditional requests to a given site, or what share of recrawls end in a 304. So this post makes no claim about crawl budget or rankings. What a 304 saves for certain is server work and bandwidth.
What the HTTP standard adds
Four rules in RFC 9110 shape the script. I checked each of them in the RFC text:
- A recipient must ignore
If-Modified-Sincewhen the request also hasIf-None-Match. The script therefore sends the two validators in separate requests, because a server that respects only one of them would hide the failure of the other. -
If-Modified-Sinceis also ignored when its value is not a valid HTTP date, so a page with a brokenLast-Modifiedcannot be revalidated that way. -
If-None-Matchuses the weak comparison function, soW/"v1"and"v1"match. - A 304 ends at the end of the headers and cannot contain a body. The server must repeat the header fields that a 200 would have carried, including
ETag,Cache-ControlandVary.
What the script checks
It sends GET requests without following redirects and without compression (Accept-Encoding: identity, which keeps the byte counts simple). For each URL it:
-
Looks for validators on the first 200 response. With no
ETagand noLast-Modifiedit warns and stops after one request, because every recrawl then has to download the full page. -
Checks their format: the
ETagshould be a quoted string ("abc"orW/"abc"), andLast-Modifiedshould be a valid HTTP date that is not later than the response's ownDateheader and not within two seconds of it. The last rule is a heuristic for pages that print the current time as their modification date. - Tests stability with a second plain request. If the body is identical but a validator changed, revalidation can never match. If the body itself differs between two requests made moments apart (a timestamp, a nonce, a random block), no validator can stay valid.
-
Tests revalidation. It sends the
ETagback inIf-None-Match, then the date back inIf-Modified-Since, as separate requests, and expects304. A200means the validator is sent but ignored, and the warning says how many bytes were sent again. -
Runs two negative controls: an
ETagthe server never issued, and a date from 1970. A304for either is an error, because a crawler that receives it would keep an outdated copy. -
Reports
Cache-Control. Amax-ageis an OK, a missing one is information, andno-storeis flagged so you can confirm that it is intended.
The exit code is 1 when any URL has an error. Add --strict to fail on warnings as well, and --delay 1 to wait a second between requests.
The script
Save it as cache_check.py. It uses only the standard library.
#!/usr/bin/env python3
"""Check whether a URL answers conditional requests the way crawlers use them.
Usage:
python cache_check.py https://example.com/page
python cache_check.py --file urls.txt --csv report.csv
python cache_check.py --strict --delay 1 URL [URL ...]
"""
import argparse
import csv
import hashlib
import http.client
import re
import sys
import time
import urllib.parse
from email.utils import parsedate_to_datetime
USER_AGENT = "cache-check/1.0"
NO_MATCH_ETAG = '"cache-check-no-such-version"'
OLD_DATE = "Thu, 01 Jan 1970 00:00:00 GMT"
ETAG_FORMAT = re.compile(r'^(W/)?"[^"]*"$')
DATE_FORMAT = re.compile(
r"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{1,2} "
r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$")
REDIRECTS = {301, 302, 303, 307, 308}
RANK = {"OK": 0, "INFO": 1, "WARN": 2, "ERROR": 3}
def get(url, headers=None, timeout=15):
"""Send one GET without redirects or compression. Returns a dict, never raises."""
parts = urllib.parse.urlsplit(url)
if parts.scheme not in ("http", "https") or not parts.hostname:
return {"error": f"not an absolute http(s) URL: {url}"}
https = parts.scheme == "https"
path = urllib.parse.quote(parts.path or "/", safe="/%:@!$&'()*+,;=-._~")
if parts.query:
path += "?" + urllib.parse.quote(parts.query, safe="%:@!$&'()*+,;=/?-._~")
sent = {"User-Agent": USER_AGENT, "Accept": "*/*", "Accept-Encoding": "identity"}
sent.update(headers or {})
conn_class = http.client.HTTPSConnection if https else http.client.HTTPConnection
conn = conn_class(parts.hostname, parts.port or (443 if https else 80), timeout=timeout)
try:
conn.request("GET", path, headers=sent)
response = conn.getresponse()
body = response.read()
return {"status": response.status,
"headers": {k.lower(): response.getheader(k) for k, _ in response.getheaders()},
"size": len(body),
"digest": hashlib.sha256(body).hexdigest()}
except (OSError, http.client.HTTPException) as exc:
return {"error": f"{type(exc).__name__}: {exc}"}
finally:
conn.close()
def http_date(value):
"""Parse a well-formed HTTP date such as 'Fri, 4 Sep 1998 19:15:56 GMT', else None."""
if not value or not DATE_FORMAT.match(value.strip()):
return None
try:
return parsedate_to_datetime(value.strip())
except (TypeError, ValueError):
return None
def review_headers(headers, note):
"""Judge the validators and Cache-Control on the first 200 response."""
etag = headers.get("etag")
if etag and not ETAG_FORMAT.match(etag.strip()):
note("WARN", f"ETag is not a quoted string: {etag}")
last_modified = headers.get("last-modified")
if last_modified:
modified = http_date(last_modified)
served = http_date(headers.get("date"))
if modified is None:
note("WARN", f"Last-Modified is not a valid HTTP date: {last_modified}")
elif served and modified > served:
note("WARN", "Last-Modified is later than the server's own Date header")
elif served and (served - modified).total_seconds() <= 2:
note("WARN", "Last-Modified is within 2 seconds of the response time, so it may "
"be generated per request, which defeats If-Modified-Since")
directives = [d.strip() for d in (headers.get("cache-control") or "").lower().split(",")]
max_age = next((d for d in directives if d.startswith("max-age=")), None)
if max_age:
note("OK", f"Cache-Control has {max_age}, which Google says helps crawlers schedule recrawls")
else:
note("INFO", "no Cache-Control max-age; Google calls it optional but useful for recrawl scheduling")
if "no-store" in directives:
note("INFO", "Cache-Control: no-store tells browsers and shared caches not to keep the page; "
"check that this is intended")
def review_stability(first, second, note):
"""Two plain requests for the same page: validators must not move if the body does not."""
if "error" in second or second["status"] != 200:
shown = second.get("error") or f"status {second['status']}"
note("WARN", f"the second plain request failed ({shown}), so stability was not tested")
elif first["digest"] != second["digest"]:
note("WARN", "the body differs between two requests made moments apart (timestamp, "
"nonce or random block?), so no validator can stay valid")
else:
for name, label in (("etag", "ETag"), ("last-modified", "Last-Modified")):
before, after = first["headers"].get(name), second["headers"].get(name)
if before != after:
note("WARN", f"{label} changed between two requests for the same body "
f"({before} then {after}), so revalidation cannot match")
def judge_revalidation(got, what, first, note):
"""Expect 304 for a request that carries a matching validator."""
if "error" in got:
note("WARN", f"{what}: request failed ({got['error']})")
elif got["status"] == 304:
note("OK", f"{what} returns 304 Not Modified")
missing = [n for n in ("etag", "cache-control", "vary")
if first["headers"].get(n) and not got["headers"].get(n)]
if missing:
note("INFO", f"the 304 leaves out {', '.join(missing)}; RFC 9110 says a 304 must "
"repeat the header fields the 200 would have carried")
elif got["status"] == 200:
note("WARN", f"{what} is ignored: the server answered 200 and re-sent {got['size']} bytes")
else:
note("WARN", f"{what} got status {got['status']} instead of 304")
def review_conditionals(send, first, note):
"""Send validators back: matching ones should get 304, non-matching ones a full 200."""
etag = first["headers"].get("etag")
last_modified = first["headers"].get("last-modified")
if etag:
judge_revalidation(send({"If-None-Match": etag}), "If-None-Match with the ETag", first, note)
if send({"If-None-Match": NO_MATCH_ETAG}).get("status") == 304:
note("ERROR", "the server answers 304 to an ETag it never issued, so a crawler "
"could keep an outdated copy")
if http_date(last_modified):
judge_revalidation(send({"If-Modified-Since": last_modified.strip()}),
"If-Modified-Since with the Last-Modified date", first, note)
if send({"If-Modified-Since": OLD_DATE}).get("status") == 304:
note("ERROR", "the server answers 304 to a date from 1970, so a crawler "
"could keep an outdated copy")
def check(url, fetch=get, delay=0.0):
"""Run every check for one URL and return a result dict."""
result = {"url": url, "status": None, "etag": None, "last_modified": None,
"cache_control": None, "findings": []}
requests = []
def note(level, text):
result["findings"].append((level, text))
def send(headers=None):
if requests and delay:
time.sleep(delay)
requests.append(headers)
return fetch(url, headers)
first = send()
if "error" in first:
note("ERROR", f"request failed: {first['error']}")
return result
result["status"] = first["status"]
if first["status"] in REDIRECTS:
note("ERROR", f"the URL redirects (status {first['status']}); check the final URL instead")
return result
if first["status"] != 200:
note("ERROR", f"status {first['status']}: only a 200 response can be checked")
return result
headers = first["headers"]
result.update(etag=headers.get("etag"), last_modified=headers.get("last-modified"),
cache_control=headers.get("cache-control"))
review_headers(headers, note)
if not (result["etag"] or result["last_modified"]):
note("WARN", "no ETag and no Last-Modified, so crawlers must download the full page "
"on every recrawl")
return result
review_stability(first, send(), note)
review_conditionals(send, first, note)
return result
def worst(result):
"""The most serious level among a result's findings."""
return max((level for level, _ in result["findings"]), key=RANK.get, default="OK")
def print_report(result, out=None):
out = out or sys.stdout
print(result["url"], file=out)
if result["status"] is not None:
print(f" status {result['status']} ETag {result['etag'] or '-'} "
f"Last-Modified {result['last_modified'] or '-'}", file=out)
for level, text in result["findings"]:
print(f" [{level}] {text}", file=out)
def csv_row(result):
findings = " | ".join(f"{level}: {text}" for level, text in result["findings"])
return [result["url"], result["status"], result["etag"], result["last_modified"],
result["cache_control"], worst(result), findings]
def read_urls(path):
with open(path, encoding="utf-8") as handle:
return [line.strip() for line in handle
if line.strip() and not line.lstrip().startswith("#")]
def main(argv=None):
parser = argparse.ArgumentParser(description="Test ETag/Last-Modified revalidation.")
parser.add_argument("urls", nargs="*", help="pages to check")
parser.add_argument("--file", help="text file with one URL per line")
parser.add_argument("--csv", help="write one row per URL to this CSV file")
parser.add_argument("--strict", action="store_true", help="exit 1 on warnings too")
parser.add_argument("--delay", type=float, default=0.0, help="seconds between requests")
args = parser.parse_args(argv)
urls = list(args.urls) + (read_urls(args.file) if args.file else [])
if not urls:
parser.error("give at least one URL or --file")
results = []
for url in urls:
results.append(check(url, delay=args.delay))
print_report(results[-1])
if args.csv:
with open(args.csv, "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["url", "status", "etag", "last_modified", "cache_control",
"worst", "findings"])
writer.writerows(csv_row(r) for r in results)
limit = RANK["WARN" if args.strict else "ERROR"]
return 1 if any(RANK[worst(r)] >= limit for r in results) else 0
if __name__ == "__main__":
sys.exit(main())
Run it on test URLs
I ran it against a small local server that I wrote for the tests, with five invented pages: a correct one, one that sends validators and ignores them, one with no validators, one whose ETag changes on every request, and one that answers 304 to everything.
python cache_check.py http://127.0.0.1:8099/good http://127.0.0.1:8099/ignores http://127.0.0.1:8099/none http://127.0.0.1:8099/unstable-etag http://127.0.0.1:8099/always304
http://127.0.0.1:8099/good
status 200 ETag "v1" Last-Modified Tue, 03 Mar 2020 08:00:00 GMT
[OK] Cache-Control has max-age=3600, which Google says helps crawlers schedule recrawls
[OK] If-None-Match with the ETag returns 304 Not Modified
[OK] If-Modified-Since with the Last-Modified date returns 304 Not Modified
http://127.0.0.1:8099/ignores
status 200 ETag "v1" Last-Modified Tue, 03 Mar 2020 08:00:00 GMT
[INFO] no Cache-Control max-age; Google calls it optional but useful for recrawl scheduling
[WARN] If-None-Match with the ETag is ignored: the server answered 200 and re-sent 663 bytes
[WARN] If-Modified-Since with the Last-Modified date is ignored: the server answered 200 and re-sent 663 bytes
http://127.0.0.1:8099/none
status 200 ETag - Last-Modified -
[INFO] no Cache-Control max-age; Google calls it optional but useful for recrawl scheduling
[WARN] no ETag and no Last-Modified, so crawlers must download the full page on every recrawl
http://127.0.0.1:8099/unstable-etag
status 200 ETag "v1" Last-Modified Tue, 03 Mar 2020 08:00:00 GMT
[INFO] no Cache-Control max-age; Google calls it optional but useful for recrawl scheduling
[WARN] ETag changed between two requests for the same body ("v1" then "v2"), so revalidation cannot match
[WARN] If-None-Match with the ETag is ignored: the server answered 200 and re-sent 663 bytes
[OK] If-Modified-Since with the Last-Modified date returns 304 Not Modified
http://127.0.0.1:8099/always304
status 200 ETag "v1" Last-Modified Tue, 03 Mar 2020 08:00:00 GMT
[INFO] no Cache-Control max-age; Google calls it optional but useful for recrawl scheduling
[OK] If-None-Match with the ETag returns 304 Not Modified
[ERROR] the server answers 304 to an ETag it never issued, so a crawler could keep an outdated copy
[OK] If-Modified-Since with the Last-Modified date returns 304 Not Modified
[ERROR] the server answers 304 to a date from 1970, so a crawler could keep an outdated copy
That output comes from my own test server, not from a live site. The exit code was 1 because of the last page. Add --csv report.csv to get one row per URL with the validators, the worst level and every finding, for a spreadsheet.
Reading the results
-
[OK]lines need nothing. The first page above is what you want: validators that match, a 304 for both, and amax-age. -
No validators. For static files, web servers normally generate them. For pages built by an application, the application, the CMS or a cache in front of it has to produce them, and Google's advice is to ask your hosting or CMS provider. A sensible
ETagfor dynamic HTML is a hash of the final HTML, or a version value that changes when the content does. -
A validator that is ignored. The server sends the header and never compares it. The layer that adds the
ETag(web server, CDN, framework middleware) may not be the layer that answers conditional requests, so check which one is missing. -
A validator that is unstable. Look for values that differ between requests or between machines behind a load balancer. If the body changes too, something in the HTML itself is dynamic. Google's crawlers use the
ETagwhen both headers exist, so a workingLast-Modifiednext to a brokenETag(the fourth page above) may not help. That last part is my reading of the documentation, not a statement from Google. -
Last-Modifiedequal to the request time. The page reports "now" as its modification date. Use the content's real date, such as anupdated_atvalue from the database, or drop the header and rely onETag. - A 304 for something that cannot match. This is the most serious result. Look for a rule that forces 304 (a cache setting, a rewrite or application code) before a crawler keeps an outdated copy of a page you have changed.
- Headers missing from the 304. Informational. RFC 9110 asks for them, but I would fix the warnings first.
What I tested, and what I did not
I ran 30 tests against a real HTTP server on localhost, written with http.server. They cover: a correct page, pages with only an ETag or only a Last-Modified, a weak ETag, no validators (and that only one request is sent), validators that are ignored, only If-Modified-Since ignored, a server that always answers 304, an ETag or a Last-Modified that changes for the same body, a body that changes (reported once, not twice), a Last-Modified equal to the request time, in the future or not a valid date, an unquoted ETag, a 304 that drops headers, no-store, a redirect (not followed), 404 and 500, a refused connection, a non-HTTP URL, a non-ASCII path, the request headers, the pacing with --delay, the date parser, the exit codes and the CSV output. I also broke the script eight ways (for example: no error for a 304 to an unknown ETag, compression switched on, both validators sent together, no early stop when there are no validators) and confirmed that a test failed each time.
I did not test HTTPS and real certificates, any live site, CDNs that answer conditional requests from an edge cache with different validators than the origin, HEAD requests, If-None-Match lists or *, servers that treat Googlebot's user agent differently, or compressed responses.
Limitations
-
It downloads the page up to six times. Use
--delay, and only run it on sites you are allowed to test. -
It asks for uncompressed responses. Googlebot advertises compression. Some servers change the
ETagwhen they compress, often to a weak one, so a clean result here does not prove that the compressed version revalidates. - It is not Googlebot. Servers and CDNs can answer by user agent, cookie or country. Your access logs show what verified Googlebot requests actually received, and the first post in this series shows how to verify real Googlebot hits. Count the 304s there.
- Pages that legitimately change on every load (a random related-posts block, a per-session token in the HTML) will trigger the body warning. That is a true finding for caching, but it may be intended.
- A 304 only helps when the crawler already holds a copy and asks for it. Passing this check says your server is ready, not that Google will recrawl more.
Sources
- Overview of Google crawlers and fetchers, HTTP caching section (page last updated 2026-06-12 UTC)
- RFC 9110: HTTP Semantics, sections 13.1.2, 13.1.3 and 15.4.5
I'm Hanin, an SEO specialist working on technical SEO, GEO and entity building. I write small, checkable scripts like this one for the series "Python checks for technical SEO". If you run it on a messy site, tell me what it caught.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.