Measure Link Rot: A Local Sampler for Your Oldest URLs
Build a small local sampler that re-checks your oldest scraped URLs, measures 404 and redirect rates, and tells you when a dataset needs refreshing.
On this page
Scraped Data Rots Quietly: Why Your Stored URLs Stop Resolving
Scraped datasets age faster than most teams realize. You build a corpus of fifty thousand product pages, park it in Parquet or Postgres, and eighteen months later someone joins a field from it to a live table and the numbers look wrong. Half the time the pipeline is fine — the URLs underneath it simply stopped resolving. Pages get deleted, CMS migrations rename paths, marketing campaigns retire their landing pages. None of that touches your stored HTML, which is exactly the problem: your dataset looks pristine while its foundation rots.
The fix is not a full re-crawl every quarter. That’s expensive and mostly redundant. What you want is a cheap, repeatable local check: pull a sample of your oldest URLs, fire HEAD requests at them, classify what comes back, and turn the result into a handful of rates that tell you whether the dataset needs refreshing. This post builds that sampler end to end.
Define Link Rot: What 404s, 410s, and Redirects Mean for an Aging Dataset
Before writing any code, agree with yourself on a taxonomy. “Link rot” gets used loosely, but for measurement you need buckets, because a 301 to a renamed product page and a 301 to a parked domain are completely different events. Here is the mapping I use:
| Status class | What it usually means | Link-rot interpretation | Refresh urgency |
|---|---|---|---|
| 200 | Page still serves | Alive | None |
| 301 / 308 | Permanent move | Alive only if destination matches original content | Low, but record the destination |
| 302 / 307 | Temporary redirect, soft redirect to hub | Ambiguous — often rot in disguise | Medium |
| 404 | Gone, no forwarding | Dead | High |
| 410 | Explicitly gone | Dead, and the server is telling you it won’t come back | High |
| 5xx | Server-side failure | Unknown — could be transient or permanent | Retry before judging |
| Timeout / DNS failure | Host or path unreachable | Dead or blocked; check from a second vantage point | High |
The contested row is the redirect one. A lot of tooling treats any 2xx-or-3xx response as “healthy.” I don’t. A 301 from /article/2019/report to the site homepage is a content loss: the article is gone and the server is politely papering over it. A 301 to the same article under a new slug is fine. That distinction is what the redirect-chain classification later in this post is for.
Encoded as a sampler config, the buckets look like this:
STATUS_BUCKETS = {
"alive": lambda code: code == 200,
"redirect": lambda code: code in (301, 302, 303, 307, 308),
"dead_404": lambda code: code == 404,
"dead_410": lambda code: code == 410,
"server_error": lambda code: 500 <= code < 600,
# timeouts / DNS errors get their own bucket before classification
}
def classify(code: int) -> str:
"""Map an HTTP status code to its link-rot bucket.
Unknown codes (e.g. 403 from an anti-bot layer) fall through to
"other" so they never silently count as alive or dead.
"""
for bucket, test in STATUS_BUCKETS.items():
if test(code):
return bucket
return "other"
Keep the buckets boring. Every judgment call — is a 302 to a category page rot? — should live in one classification function, not scattered across the codebase.
Load Your Oldest URLs: Querying the Crawl Database by First-Seen Date
The sampler only works on the aging slice of your data. There’s no point re-checking pages you crawled last week; you want the URLs that have been sitting still the longest, because they carry the most decay. Assuming your crawl table records when each URL was first seen, the query is trivial:
SELECT url, first_seen, last_checked
FROM crawl_pages
WHERE url LIKE 'https://store.example.com/%'
ORDER BY first_seen ASC
LIMIT 500;
If you’re working from a Parquet or DataFrame layout instead of a database, the pandas equivalent:
import pandas as pd
df = pd.read_parquet("crawl_pages.parquet")
oldest = (
df[df.url.str.startswith("https://store.example.com/")]
.sort_values("first_seen")
.head(500)
[["url", "first_seen", "last_checked"]]
)
Sample output from the store subdomain:
url first_seen last_checked
https://store.example.com/old-page 2023-... NULL
Hold on — don’t paste literal timestamps into your tooling. The point is the shape:
url first_seen last_checked
https://store.example.com/p/1001 (oldest) NULL
https://store.example.com/p/1002 (oldest) NULL
https://store.example.com/cat/spring-clearance (oldest) NULL
... ... ...
Two practical notes. First, 500 URLs is a good sample size for a weekly check — small enough to finish in minutes at a polite rate, large enough that a 404 percentage is meaningful (at n=500, one dead URL moves the rate by 0.2 points, so you’re not chasing noise). Second, sample deterministically, not randomly: the oldest 500 by first_seen is a stable cohort, which means week-over-week deltas measure actual decay rather than sampling variance. If you resample randomly each run, your trend line will wobble for reasons that have nothing to do with the target site.
Build the HEAD-Request Sampler with Concurrency and Politeness Limits
The core checker is an async loop with a hard concurrency cap and a per-request timeout. I use httpx because its async API is clean and follow_redirects is explicit, but aiohttp works identically:
import asyncio
import httpx
MAX_CONCURRENCY = 5
REQUEST_TIMEOUT = httpx.Timeout(15.0)
sem = asyncio.Semaphore(MAX_CONCURRENCY)
async def check_url(client: httpx.AsyncClient, url: str) -> dict:
async with sem:
try:
r = await client.head(
url,
timeout=REQUEST_TIMEOUT,
follow_redirects=True,
)
except (httpx.TimeoutException, httpx.ConnectError) as e:
return {"url": url, "bucket": "unreachable", "error": str(e)}
# Some servers answer HEAD with 404 but serve GET fine
# (misconfigured routing, not a missing page).
if r.status_code == 404:
r = await client.get(
url,
timeout=REQUEST_TIMEOUT,
follow_redirects=True,
)
return {
"url": url,
"bucket": classify(r.status_code),
"final_url": str(r.url),
"status": r.status_code,
"hops": len(r.history),
}
The concurrency cap of 5 is deliberate, and I’d argue for going lower rather than higher. This is a health check against a site you scraped once — you have no ongoing relationship with it, and blasting 500 parallel HEAD requests at a host you haven’t touched in a year is a good way to get your office IP range blocked. Five concurrent connections with no artificial delay finishes 500 URLs in a couple of minutes on most targets. That’s fast enough.
The GET-on-404 fallback deserves its own comment. HEAD support is spotty in the wild: some frameworks route HEAD requests to a different handler than GET, some CDNs strip the verb, and a 404 on HEAD is occasionally a routing artifact rather than a dead page. The fallback costs you one extra request per 404 — cheap insurance against false positives. In my runs, roughly one in ten HEAD-404s turns out to be a live page on GET.
One honest limitation of the local approach: your sampler’s exit IP is your own. If the target has since deployed an anti-bot layer that serves 403s or block pages to datacenter or office IPs, the sampler will report rot that isn’t there. That’s why the “unreachable” bucket exists — treat it as unknown, not dead. When I need a second vantage point, I re-run the same URL list through a scraping API as a spot-check. FineData’s scrape endpoint is asynchronous, so a spot-check is two calls: submit the job, then poll its status — a plain request with no rendering flags:
import requests
resp = requests.post(
"https://api.finedata.ai/api/v1/async/scrape",
headers={"Authorization": "Bearer fd_your_api_key"},
json={
"url": "https://store.example.com/old-page",
"formats": ["rawHtml"],
},
timeout=120,
)
job_id = resp.json()["job_id"]
# Poll the job until it completes, then read the result
status = requests.get(
f"https://api.finedata.ai/api/v1/async/jobs/{job_id}",
headers={"Authorization": "Bearer fd_your_api_key"},
timeout=30,
)
That’s a confirmation tool, not the default path — the local sampler stays the primary because it’s free and fast. If you want the full argument on that trade-off, I wrote about re-scrape versus change-detection strategies separately.
Classify Redirect Chains and Capture Final Destinations
A single follow_redirects=True gives you the final status, but not the story. You need the hops, because the difference between a healthy redirect and rot is often only visible in the chain. A 301 to a new slug is fine; a 301 to an interstitial to a category page to a 404 is rot wearing a costume.
To capture the chain, disable auto-follow and walk it manually. Each hop uses a HEAD request — same rationale as the sampler above — with a GET fallback for servers that answer HEAD with a 404 or 405 instead of routing it to the real handler:
from urllib.parse import urljoin
MAX_HOPS = 10
async def trace_redirects(client: httpx.AsyncClient, url: str) -> dict:
hops = []
current = url
for _ in range(MAX_HOPS):
try:
r = await client.head(
current,
timeout=REQUEST_TIMEOUT,
follow_redirects=False,
)
except (httpx.TimeoutException, httpx.ConnectError) as e:
return {"origin": url, "hops": hops, "final": current,
"final_status": None, "hops_exceeded": False,
"error": str(e)}
# HEAD fallback: some servers 404/405 on HEAD but serve GET fine
if r.status_code in (404, 405):
r = await client.get(
current,
timeout=REQUEST_TIMEOUT,
follow_redirects=False,
)
if r.status_code in (301, 302, 303, 307, 308) and "location" in r.headers:
nxt = urljoin(current, r.headers["location"])
hops.append({"from": current,
"status": r.status_code,
"to": nxt})
current = nxt
continue
return {"origin": url, "hops": hops, "final": current,
"final_status": r.status_code, "hops_exceeded": False,
"error": None}
# Hit MAX_HOPS without a terminal response: a redirect loop or a
# chain longer than anything legitimate. Signal it explicitly
# rather than inventing a fake status code.
return {"origin": url, "hops": hops, "final": current,
"final_status": None, "hops_exceeded": True,
"error": "too many hops"}
Note the urljoin — Location headers are frequently relative, and a naive chain walker will crash or produce garbage destinations. This is the same class of bug as relative URLs in scraped links: the header is not a contract, it’s a hint.
Also note the hops_exceeded flag on the loop-exhaustion path. An earlier version of this code returned a made-up 310 as the “final status” there; don’t do that. 310 is not a status any server sent you, and downstream code that switches on status codes will mis-handle it. final_status: None plus an explicit flag is unambiguous: the chain never terminated, and the caller should treat it as rot pending a manual look.
Here’s what a rotting chain looks like in the sampler’s output:
origin: https://example.com/article/2019/report
hop 1: 301 -> https://example.com/articles/report
hop 2: 301 -> https://example.com/articles
hop 3: 302 -> https://example.com/search?q=report
final: https://example.com/search?q=report
final_status: 200
verdict: ROT (content redirected away from origin; final page is a search)
The final status is 200. A naive checker that only looks at the last response calls this URL alive. It isn’t — the content is gone, and three hops of redirects landed on a search page. My classification rule: any chain whose final URL is not a plausible content destination (same path stem, or a recorded canonical) counts as rot. For product pages I additionally check that the final URL still matches the product ID. Automate that judgment; don’t eyeball 500 chains.
Compute Rot Rates: 404 Percentage, Redirect Rate, and Domain-Level Breakdown
Raw per-URL results aren’t actionable. What you want is a small set of rates, broken down by subdomain, because rot is rarely uniform — the marketing site’s blog decays while the product catalog holds steady, and averaging them hides both.
from collections import defaultdict
import statistics
def compute_metrics(results: list[dict]) -> dict:
by_host = defaultdict(list)
for r in results:
host = r["url"].split("/")[2]
by_host[host].append(r)
report = {}
for host, rows in by_host.items():
n = len(rows)
dead = [r for r in rows if r["bucket"] in ("dead_404", "dead_410", "rot_redirect")]
redirected = [r for r in rows if r["hops"] > 0]
chains = [r["hops"] for r in redirected] or [0]
report[host] = {
"sampled": n,
"dead_rate": round(len(dead) / n, 4),
"redirect_rate": round(len(redirected) / n, 4),
"chain_length_mean": round(statistics.mean(chains), 2),
"unreachable": sum(1 for r in rows if r["bucket"] == "unreachable"),
}
return report
A realistic printout from a 500-URL run across two subdomains:
== example.com ==
sampled: 180
dead_rate: 0.2056 (37 dead)
redirect_rate: 0.5278
chain_length_mean: 1.90
unreachable: 4
== store.example.com ==
sampled: 320
dead_rate: 0.0750 (24 dead)
redirect_rate: 0.3625
chain_length_mean: 1.20
unreachable: 2
Read that the way you’d read any sampled metric. A dead rate of 7.5% on the store subdomain means roughly one in thirteen of your oldest URLs points at nothing. The redirect rate of 36% means over a third of your stored URLs no longer resolve to the page you actually scraped — any downstream consumer joining on URL will silently miss. The unreachable counts stay small and get re-tested, because five timeouts out of 500 is a network blip, not a signal.
Set Refresh Thresholds: Deciding When the Dataset Needs a Full Re-Crawl
Metrics without a decision rule are a dashboard, and dashboards get ignored. Put the thresholds in config, next to the code, so changing them is a one-line diff instead of an argument in a meeting:
# rot_thresholds.yaml
sample_size: 500
thresholds:
dead_rate:
spot_check: 0.05 # 5% dead -> investigate the worst paths
full_refresh: 0.10 # 10% dead -> re-crawl the affected subdomain
redirect_rate:
spot_check: 0.30
full_refresh: 0.50
chain_length_mean:
spot_check: 2.0 # chains drifting away from content
unreachable_rate:
retest: 0.03 # >3% unreachable -> re-run before deciding
And pair the config with an explicit decision table, because the combinations matter more than any single number:
| dead_rate | redirect_rate | chain_length_mean | Action |
|---|---|---|---|
| < 0.05 | < 0.30 | < 1.5 | No action. Log and move on. |
| < 0.05 | > 0.30 | < 1.5 | Spot-check redirected URLs; update stored destinations, no re-crawl. |
| 0.05–0.10 | any | any | Spot-check the dead paths; look for a pattern (retired category, CMS migration). |
| > 0.10 | any | any | Full re-crawl of that subdomain. Don’t patch a dataset that’s a tenth gone. |
| any | any | > 2.0 | Content is being redirected away. Re-crawl even if dead rate is low — your stored HTML no longer matches what the URLs serve. |
Here’s where I’ll take a position some teams disagree with: I’d trigger a full refresh on a redirect rate above 50% even if the dead rate is under 5%. Redirects mean your URLs are lying about what they point to, and every downstream join, dedup, and diff keyed on URL is quietly wrong. A dataset with 5% dead URLs and 55% redirected ones is less healthy than one with 12% dead and no redirects, in my book. Dead URLs fail loudly; redirected ones fail silently.
The counter-argument is cost — a re-crawl of a large subdomain isn’t free, and if you only use the dataset for aggregate statistics, URL-level accuracy may not matter. That’s a legitimate call, but make it consciously, with these numbers in front of you, not by default because nobody looked.
Schedule the Sampler Locally: Cron, Logging, and a Rot Trend Log
One run tells you a snapshot. A weekly run tells you a velocity — whether rot is creeping at half a percent a month or accelerating after a site redesign. The trend is the actual product; the weekly numbers are just its inputs.
Cron entry, nothing exotic:
# Weekly: Monday 06:00, sampler over the oldest 500 URLs
0 6 * * 1 /usr/bin/python3 /opt/sampler/rot_sampler.py >> /var/log/rot_sampler.log 2>&1
The sampler appends each run’s metrics to a small SQLite trend table — CSV works too, but SQLite gives you dates and deltas in one query:
import sqlite3
from datetime import date
def append_trend(db_path: str, report: dict) -> None:
con = sqlite3.connect(db_path)
con.execute("""
CREATE TABLE IF NOT EXISTS rot_trend (
run_date TEXT,
host TEXT,
dead_rate REAL,
redirect_rate REAL,
chain_length_mean REAL,
unreachable INTEGER
)
""")
for host, m in report.items():
con.execute(
"INSERT INTO rot_trend VALUES (?, ?, ?, ?, ?, ?)",
(date.today().isoformat(), host, m["dead_rate"],
m["redirect_rate"], m["chain_length_mean"], m["unreachable"]),
)
con.commit()
# Delta versus the previous run for this host.
# ORDER BY run_date DESC returns the newest row first, so the
# current run is prev[0] and the previous run is prev[1] —
# unpack in that order or every delta prints with the sign flipped.
for host in report:
prev = con.execute("""
SELECT run_date, dead_rate, redirect_rate FROM rot_trend
WHERE host = ? ORDER BY run_date DESC LIMIT 2
""", (host,)).fetchall()
if len(prev) == 2:
(d_now, dead_now, _), (d_prev, dead_prev, redir_prev) = prev
print(f"[rot-trend] {host}: dead_rate={dead_now:.3f} "
f"({dead_now - dead_prev:+.3f} vs {d_prev}), "
f"redirect_rate delta "
f"{report[host]['redirect_rate'] - redir_prev:+.3f}")
con.close()
Sample log line from a run where things got worse:
[rot-trend] store.example.com: dead_rate=0.120 (+0.014 vs previous run),
redirect_rate delta +0.041
A dead rate creeping up 1.4 points a week on a stable cohort is your early warning. When that line crosses your full_refresh threshold, the cron log is the evidence you hand to whoever approves the re-crawl budget — “the oldest cohort went from 6% to 12% dead in six weeks” is a much stronger argument than “the dataset feels stale.”
Wrapping Up
The whole sampler is maybe 150 lines of Python: a HEAD checker with a concurrency cap, a manual redirect-chain walker, a classifier with explicit buckets, an aggregation step, and a weekly cron appending to a trend table. The value isn’t in any one piece — it’s in the loop. Every week you get three numbers per subdomain, and those numbers have a defined path to a decision: spot-check, re-test, or full refresh.
Three gotchas before you ship it. First, the GET-on-404 fallback matters more than it looks; skip it and your dead rate runs hot. Second, resist the urge to grow the sample — 500 polite requests weekly is invisible to most targets, 10,000 is not, and the marginal statistical value past a few hundred URLs is small. Third, keep “unreachable” separate from “dead” in every report; conflating them turns network blips into re-crawl triggers.
If you want to go further after the sampler is running, the natural next steps are a per-path-prefix breakdown (which category is rotting fastest), joining dead URLs against your dataset’s usage stats to prioritize re-crawls by downstream value, and a cost ledger so the refresh decision includes the price tag. But start with the weekly trend line. It answers the question that actually matters: is this dataset still trustworthy, and how fast is that changing?
Related Articles
Audit Field Fill Rates: Measure Extraction Quality Locally
Build a local audit script that scores scraped datasets by field fill rate, null clusters, and stale values before bad rows reach your warehouse.
TechnicalMap Your Throughput Curve: Find the Concurrency Sweet Spot
Run a local harness that logs pages per minute at rising worker counts. Plot your throughput curve and find where extra concurrency stops paying.
TechnicalCount the Requests Behind Every Rendered Page
Log every subrequest a rendered page fires with a local network listener. Measure request fan-out per URL, spot bloat, and find hidden data endpoints.