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 [Source:https://dev.to/hanin_mp/does-your-server-ever-answer-304-test-etag-and-last-modified-revalidation-in-python-41ljRelated posts
What a Framer site looks like as an Astro project
Making a site readable to search engines and AI assistants in 2027
Sanity and Next.js for a B2B marketing site: what to look for

How I made Adobe Illustrator 60x faster for AI agents
No dead ends: how I prove every board in my mahjong solitaire can be cleared
