Dead-Letter Failed URLs, Then Replay Them Safely
Build a scraping pipeline that parks failed URLs in a dead-letter queue, inspects why each one failed, and replays them without losing rows or duplicating work.
On this page
The Problem: Failed URLs That Vanish Quietly
Every scraper eventually produces a URL that fails. A 502 from the target, a DNS blip, a page whose markup shifted overnight. What separates a pipeline you trust from one you babysit is not whether URLs fail — it is what happens to them next. The failure mode I see over and over in production code is the same: the fetch loop retries a few times, the exception eventually escapes, and the URL simply vanishes. No record. No way to replay it. Your dataset is now missing rows and you have no way to know which ones.
A dead-letter queue fixes this. Instead of dropping failed URLs, you park them in a durable table with the reason they failed, then replay them later under controlled conditions. This tutorial builds the whole loop: classification, storage, replay, pacing, escalation, and the metrics that tell you whether the pipeline is healthy. The patterns here work with any HTTP client; I’ll use a scraping API for the fetches because it handles proxies and retries server-side, but the dead-letter machinery is client-side and framework-agnostic.
Why a Plain Retry Loop Loses Rows: Anatomy of a Failed URL
Before you can dead-letter anything, you need a taxonomy. Not all failures are equal, and treating them identically is how pipelines waste money and lose data. Here is the classification I use:
| Failure class | Example | Retry? | Dead-letter? | Notes |
|---|---|---|---|---|
| Transient 5xx | 502, 503 from target | Yes, 3–5 attempts | Yes, after budget exhausted | Usually capacity or a flaky LB |
| Timeout | No response in N seconds | Yes, 2–3 attempts | Yes | Often resolves on replay |
| DNS failure | ENOTFOUND, resolver timeout | Yes, 1–2 attempts | Yes | Almost always local or transient |
| Connection reset | TCP RST mid-body | Yes | Yes | Can indicate blocking — check pattern |
| 4xx (404, 410) | Page deleted | No | Park immediately, low priority | Retrying a 404 is burning tokens |
| 403 / block page | 200 OK but challenge HTML | Escalate, don’t blind-retry | Yes | Same request will fail again — change strategy |
| Parse error | Selector returns nothing | No | Yes, tagged for selector review | Retrying the fetch cannot fix your selector |
| Validation drop | Parsed but failed schema check | No | Yes, with payload snapshot | Data quality issue, not a fetch issue |
The key insight is in the last three rows: some failures are not fetch failures at all. If your selector broke because the site redesigned, retrying the HTTP request a hundred times produces a hundred identical failures. Classify first, then decide. (If you want the longer version of this argument, see Your Scraper Died in a Redesign: An Extraction Escalation.)
Now here is the loop that loses rows. I have seen this pattern in real codebases more times than I can count:
import requests
def scrape_all(product_ids):
rows = []
for pid in product_ids:
url = f"https://store.example.com/product/{pid}"
for attempt in range(3):
try:
resp = requests.get(url, timeout=30)
resp.raise_for_status()
rows.append(parse_product(resp.text, pid))
break
except Exception:
if attempt == 2:
continue # "give up on this one"
return rows
Two bugs, both silent. First, when the inner loop exhausts, the continue moves to the next product with no record of which URL failed or why. Second, except Exception swallows everything — a KeyboardInterrupt-adjacent coding error, a parse bug, a 404 — into the same invisible hole. At the end of a 10,000-URL run you have 9,700 rows and no idea what the other 300 were. The fix is not more retries. The fix is a place to put the failures.
Designing the Dead-Letter Table: Schema That Captures the Why
A dead-letter queue is not a log line. Logs scroll away; a dead-letter entry is a row you can query, count, and re-drive. Treat it as first-class pipeline state: route every failure through one choke point, and design the write path so no row is dropped — the same durability your actual data table gets.
CREATE TABLE dead_letters (
id BIGSERIAL PRIMARY KEY,
url TEXT NOT NULL,
natural_key TEXT, -- e.g. 'product:42' for idempotent replay
failure_class TEXT NOT NULL, -- 'http_5xx', 'timeout', 'parse_error', ...
error_message TEXT,
http_status INTEGER,
attempts INTEGER NOT NULL DEFAULT 0,
next_retry_at TIMESTAMPTZ,
state TEXT NOT NULL DEFAULT 'queued', -- queued | replayed | poison
payload_snapshot JSONB, -- partial parse result, if any
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_dead_letters_state_retry
ON dead_letters (state, next_retry_at);
Every column earns its place. failure_class drives the retry policy. attempts and next_retry_at make the table itself the replay scheduler — no separate queue service required for modest volumes. natural_key is what makes replay safe, which we get to in the next section. payload_snapshot is the one people skip and later regret: if the parse half-succeeded (you got the title but not the price), keeping the partial output lets you debug the selector without re-fetching.
Writing a failure looks like this:
def park_failure(conn, url, natural_key, failure_class,
error_message, http_status=None, attempts=0, snapshot=None):
conn.execute("""
INSERT INTO dead_letters
(url, natural_key, failure_class, error_message,
http_status, attempts, next_retry_at, payload_snapshot)
VALUES (%s, %s, %s, %s, %s, %s, now() + interval '15 minutes', %s)
""", (url, natural_key, failure_class, error_message,
http_status, attempts, snapshot))
A concrete call after a failed fetch of https://store.example.com/item/42:
park_failure(
conn,
url="https://store.example.com/item/42",
natural_key="product:42",
failure_class="parse_error",
error_message="selector 'span.price' matched 0 nodes",
http_status=200,
attempts=1,
snapshot={"title": "Widget, Blue, 3-pack"}, # what we did get
)
That row is now replayable, debuggable, and countable. Note the 15-minute next_retry_at — I park transient failures with a delay rather than retrying in-process. The target that just returned a 502 usually needs minutes to recover, not the 200 milliseconds your in-loop sleep gives it. In-process retries are fine for genuine blips, but anything that smells like target-side trouble should go straight to the queue with a delay. This is an opinion, and it costs you latency on the happy-recovery path, but it protects the target and it keeps your worker threads from sitting in sleep loops doing nothing.
Routing Failures: A Wrapper That Classifies Before Parking
The dead-letter table is useless if exceptions can still escape. So the fetch-and-parse step gets wrapped in a single choke point where every exception is caught, classified, and routed. No except Exception: pass anywhere else in the codebase — this function is the only place allowed to swallow.
from dataclasses import dataclass
import requests
@dataclass
class Failure:
url: str
failure_class: str
error_message: str
http_status: int | None = None
snapshot: dict | None = None
def fetch_and_parse(url: str, natural_key: str, session: requests.Session):
"""Returns (row, None) on success or (None, Failure) on failure. Never raises."""
try:
resp = session.get(url, timeout=30)
resp.raise_for_status()
row = parse_product(resp.text, natural_key)
if not row.get("price"):
return None, Failure(url, "validation_drop",
"price missing after parse",
resp.status_code, snapshot=row)
return row, None
except requests.exceptions.Timeout as e:
return None, Failure(url, "timeout", str(e))
except requests.exceptions.ConnectionError as e:
return None, Failure(url, "dns_or_reset", str(e))
except requests.exceptions.HTTPError as e:
status = e.response.status_code
cls = "http_4xx" if status < 500 else "http_5xx"
return None, Failure(url, cls, str(e), status)
except (KeyError, ValueError) as e:
return None, Failure(url, "parse_error", f"parser raised {e!r}")
The caller does one thing with the result:
row, failure = fetch_and_parse(url, natural_key, session)
if row:
upsert_scraped_row(conn, row)
else:
park_failure(conn, failure.url, natural_key, failure.failure_class,
failure.error_message, failure.http_status,
snapshot=failure.snapshot)
That is the entire routing layer. Note the validation drop: a row that parses but fails a business rule (price missing) is a failure worth parking, not a row worth writing with NULL in it and hoping downstream code handles it. Bad data written is worse than data delayed.
The retry policy lives in config, not in code, because the right budget differs per failure class and you will want to tune it without redeploying:
retry_policy:
http_5xx:
max_attempts: 5
backoff: exponential
base_delay_seconds: 60
timeout:
max_attempts: 3
backoff: exponential
base_delay_seconds: 30
dns_or_reset:
max_attempts: 2
backoff: fixed
base_delay_seconds: 120
http_4xx:
max_attempts: 0 # park immediately, never auto-retry
backoff: none
parse_error:
max_attempts: 0 # retrying cannot fix a selector
backoff: none
validation_drop:
max_attempts: 1 # one re-fetch, in case of a truncated body
backoff: fixed
base_delay_seconds: 300
The 0 entries are deliberate. A 404 will still be a 404 in an hour. A parse error will still fail with the same selector. Auto-retrying those just inflates your spend and your dead-letter noise. Park them, tag them, and let a human or a selector-fix process decide.
Replaying Without Duplicating: Idempotency Keys and Upserts
Here is the question that stops most people from building replay: if I re-fetch a URL I already scraped, do I get two rows? If your write path is INSERT, yes — and now your dataset has duplicates that are hard to distinguish from real revisions. The answer is to make writes idempotent on a natural key, so replay is a replace rather than an append.
CREATE TABLE scraped_rows (
natural_key TEXT PRIMARY KEY,
url TEXT NOT NULL,
title TEXT,
price_cents INTEGER,
currency TEXT,
fetched_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
INSERT INTO scraped_rows (natural_key, url, title, price_cents, currency)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (natural_key) DO UPDATE
SET title = EXCLUDED.title,
price_cents = EXCLUDED.price_cents,
currency = EXCLUDED.currency,
fetched_at = EXCLUDED.fetched_at;
Now the same URL can be scraped twice, five times, twenty times, and the table stays correct. The fetched_at column tells you which version won, which is the latest, and — combined with the dead-letter table — how many attempts it took. If you need every historical version rather than just the latest, that is a different design: an append-only history table keyed on (natural_key, fetched_at), which I cover in Keep Every Version of a Page: Build an SCD History Table.
The replay worker itself is a small loop. It reads due entries from dead_letters, re-fetches through the scraping API, upserts, and updates the dead-letter state:
import time, requests
API = "https://api.finedata.ai"
HDRS = {"Authorization": "Bearer fd_your_api_key"}
def replay_due(conn, limit=50):
rows = conn.execute("""
SELECT id, url, natural_key, failure_class, attempts
FROM dead_letters
WHERE state = 'queued' AND next_retry_at <= now()
ORDER BY next_retry_at
LIMIT %s
""", (limit,)).fetchall()
for dl_id, url, natural_key, failure_class, attempts in rows:
resp = requests.post(f"{API}/api/v1/scrape", headers=HDRS, json={
"url": url,
"use_residential": True, # escalate past datacenter blocks
"use_antibot": True,
"formats": ["rawHtml"],
"timeout": 120,
})
if resp.status_code == 200:
page = resp.json()
row = parse_product(page.get("data", {}).get("rawHtml", ""), natural_key)
if row and row.get("price"):
upsert_scraped_row(conn, row)
mark_replayed(conn, dl_id)
else:
bump_attempt(conn, dl_id, attempts,
"parse_error", snapshot=row)
else:
bump_attempt(conn, dl_id, attempts, failure_class)
One subtlety worth calling out: on replay I escalate the request. The first fetch probably went out cheap — plain request, default settings. If it failed for blocking reasons, replaying the identical request is a waste. Bumping use_residential (or stealth_antibot for tougher pages) on the second attempt means each retry costs more but succeeds more often. You pay for the escalation only on URLs that have already proven difficult. This mirrors the escalation logic I described in Teach Your Agent to Escalate Its Own Fetches, just applied to a batch pipeline instead of an agent.
Backoff and Staggering: Replaying a 500-URL Queue Without Hammering the Target
Replay has a self-inflicted failure mode: the queue backs up during an outage, the target recovers, and your replay worker dumps 500 requests on it in ten seconds. Then you get rate limited, the replays fail, and the queue backs up further. The fix is pacing — exponential backoff per attempt, jitter to decorrelate, and a hard concurrency cap.
import asyncio, random
MAX_CONCURRENT = 5
async def replay_with_pacing(urls_and_keys, worker):
sem = asyncio.Semaphore(MAX_CONCURRENT)
async def bounded(url, key):
async with sem:
await worker(url, key)
await asyncio.gather(*(bounded(u, k) for u, k in urls_and_keys))
def next_delay(attempts, base=60, cap=1800):
"""Exponential backoff with full jitter: delay in [0, min(cap, base*2^n))."""
ceiling = min(cap, base * (2 ** attempts))
return random.uniform(0, ceiling)
Full jitter — picking a uniform random value in [0, ceiling) rather than ceiling ± 20% — matters more than people expect. Without it, every URL that failed at the same moment retries at the same moment, in a synchronized wave that repeats forever. With it, the retry load spreads out. If the target sends Retry-After headers, honor those instead of computing your own; I wrote a whole post about why ignoring that header keeps 429s alive: Your Backoff Ignores Retry-After.
What concurrency cap is right? Measure it, don’t guess. Here is a replay of 100 example.com URLs from a dead-letter queue, run locally three times at different caps:
| Concurrency | Wall-clock time | Failed replays | Notes |
|---|---|---|---|
| 1 | 96s | 0 | Polite, slow, fine for small queues |
| 5 | 21s | 0 | My default for a single target domain |
| 20 | 7s | 6 (429s) | Faster, then slower — 6 URLs re-queued |
Concurrency 20 finished the raw fetches in 7 seconds but then triggered rate limiting, and the six 429s went straight back into the dead-letter queue with bumped attempt counts. Net wall-clock to fully drained was worse than concurrency 5. That is the shape of the curve for most targets: aggressive caps feel faster and measure slower. Start at 5 concurrent per target domain, watch your error rate, and only push higher when the numbers say you can.
Handling URLs That Fail Forever: Escalation, Alerts, and Manual Review
Some URLs never recover. The page was deleted, the site restructured, or your selector is genuinely wrong. A dead-letter queue without a terminal state becomes a slow leak — entries retried forever, budget burned monthly, nobody noticing. You need a poison state.
MAX_ATTEMPTS_DEFAULT = 5
def bump_attempt(conn, dl_id, attempts, failure_class,
error_message=None, snapshot=None):
policy = RETRY_POLICY[failure_class]
max_attempts = policy["max_attempts"]
attempts += 1
if attempts >= max_attempts:
conn.execute("""
UPDATE dead_letters
SET state = 'poison', attempts = %s,
error_message = COALESCE(%s, error_message),
updated_at = now()
WHERE id = %s
""", (attempts, error_message, dl_id))
emit_alert(conn, dl_id, failure_class, attempts)
else:
delay = next_delay(attempts, base=policy["base_delay_seconds"])
conn.execute("""
UPDATE dead_letters
SET attempts = %s, next_retry_at = now() + (%s || ' seconds')::interval,
failure_class = %s,
error_message = COALESCE(%s, error_message),
payload_snapshot = COALESCE(%s, payload_snapshot),
updated_at = now()
WHERE id = %s
""", (attempts, delay, failure_class, error_message, snapshot, dl_id))
def emit_alert(conn, dl_id, failure_class, attempts):
conn.execute("""
INSERT INTO alerts (kind, payload, created_at)
VALUES ('dead_letter_poison', %s, now())
""", ({"dead_letter_id": dl_id,
"failure_class": failure_class,
"attempts": attempts},))
Poison rows are not garbage. They are your work queue for manual review: someone opens the URL, sees a 404 or a redesigned template, and either fixes the selector or marks the row as permanently skipped. I keep poison rows for at least 30 days before purging, because a cluster of poison rows with the same failure_class is almost always a selector bug — one fix re-drives all of them.
Alert thresholds belong in config next to the retry policy:
alerts:
dead_letter_rate:
warn_pct: 5 # dead-letters as % of batch size
window: daily
poison_count:
warn_any: true # any single poison row pages someone
attempt_ceiling:
warn_at: 5 # a URL hitting 5 attempts, even if not yet poison
The 5% threshold deserves a word. A dead-letter rate under 1% is background noise — transients doing what transients do. Between 1% and 5%, watch the trend. Above 5%, something structural is wrong: your IPs are burned, your selector drifted, or the target is degrading. That last case is where a circuit breaker beats any amount of retry logic, and I’d trip one before the dead-letter rate hits double digits: Trip a Circuit Breaker When Your Scrape Target Degrades.
Measuring the Pipeline: Dead-Letter Rate as a Health Metric
The dead-letter table closes the loop when you treat it as a telemetry source, not just a work queue. Two numbers tell you most of what you need: what fraction of fetches dead-letter (pipeline health), and what fraction of dead-letters recover on replay (failure taxonomy quality). If your replay success rate is high, your failures are transient and your policy is working. If it is low, you are dead-lettering things that replay cannot fix — probably parse errors and 4xx that should never have been retried.
SELECT
d.day,
d.dead_lettered,
s.fetched,
ROUND(100.0 * d.dead_lettered / NULLIF(s.fetched, 0), 1) AS dead_letter_pct,
d.replayed_ok,
d.poisoned,
ROUND(100.0 * d.replayed_ok / NULLIF(d.dead_lettered, 0), 1) AS replay_success_pct
FROM (
SELECT date_trunc('day', created_at) AS day,
COUNT(*) AS dead_lettered,
COUNT(*) FILTER (WHERE state = 'replayed') AS replayed_ok,
COUNT(*) FILTER (WHERE state = 'poison') AS poisoned
FROM dead_letters
GROUP BY 1
) d
JOIN (
SELECT date_trunc('day', fetched_at) AS day, COUNT(*) AS fetched
FROM scraped_rows
GROUP BY 1
) s ON s.day = d.day
ORDER BY d.day DESC;
Run that daily, and print it as a one-line report after each batch. Mine looks like this:
$ python report.py --last-batch
batch 05-01 06:00 UTC : 10,000 fetched, 312 dead-lettered (3.1%),
298 replayed OK (95.5%), 14 poisoned (0.1%)
top failure class: http_5xx (241)
One glance, four decisions. Dead-letter rate is trending up or down. Replay success tells me whether my retry policy matches my failure mix. Poison count tells me whether a human needs to look. Top failure class tells me where to look. When the 5xx count spikes, it is the target. When parse errors spike, it is us. That distinction takes about thirty seconds to make from this report, and it has saved entire mornings of guessing.
Wrap-Up and Gotchas
The full loop: classify every failure, park it with context in a durable table, replay with idempotent upserts, pace the replay, escalate or poison what never recovers, and measure all of it. The moving parts are small — one wrapper function, two tables, one replay worker, one report — and none of it requires a message broker. A plain Postgres table handles dead-letter volumes fine into the tens of thousands per day.
Gotchas I have hit:
- Poison rows with
max_attempts: 0classes. Parse errors and 4xx park with zero retries, so they go straight to poison on the first failure. That is correct, but your alerting must not treat them as emergencies — triage them as selector-review work, not incidents. - Replay storms after outages. If your target was down for an hour, thousands of entries share the same
next_retry_at. Jitter alone may not spread them enough — add a random skew of up to 30 minutes when scheduling the initial retry. - Snapshot bloat.
payload_snapshotwith full page HTML will blow up your table. Store the parsed dict, not the raw body; keep raw bodies in object storage keyed by URL if you need them. - Natural key discipline. Idempotent replay only works if the natural key is stable. Deriving it from the URL (
product:42) is fine. Deriving it from the page title is not — the day a product gets renamed, your upsert starts duplicating.
Next steps if you want to go further: move the replay worker onto the batch endpoints so a large queue submits as one unit with a callback, and add a change-detection layer so you stop re-scraping pages that have not changed. Both build cleanly on top of this design — the dead-letter table does not care what fetch mechanism refills it.
Related Articles
Keep Every Version of a Page: Build an SCD History Table
Re-scraping overwrites history. Build a merge step that keeps every record version with validity dates, so you can query past states of any scraped page.
TutorialGzip Says Unexpected EOF: Fix Truncated Page Bodies
Your scraper dies mid-decompression with 'unexpected end of file'. Trace the truncated gzip stream back to its cause and learn fixes that hold up at scale.
TutorialCertificate Verify Failed: Fix SSL Errors in Web Scrapers
Your scraper throws SSLError: certificate verify failed. Learn the real causes — TLS inspection, stale CAs — and fix verification without turning it off.