Sub topic 9
Handling Failures, Timeouts, and Retries
This chapter assumes you can read short Python programs and know HTTP status codes. It also assumes you have seen the fetch function and the per-host frontier from earlier chapters. Examples use Python 3.10 or later.
Why failure is the normal case
A crawler makes thousands of requests to servers it does not control. Some hosts are down, some are slow, and some answer with errors for a minute and then recover. Some send a body that never ends. If the crawl loop treats these as rare, one bad host can stall or crash the whole run.
Failure handling comes down to three questions for every failed fetch:
- Is the failure permanent or transient?
- If it is transient, when should the crawler try again?
- When should the crawler stop trying, for this URL or for the whole host?
Classifying failures
A transient failure may go away if you wait. A permanent failure will not. Retrying a permanent failure wastes requests and annoys the site owner.
| Failure | Class | Action |
|---|---|---|
| Connection timeout, read timeout | Transient | Retry with backoff |
| Connection reset, connection refused | Transient | Retry, a few times only |
| DNS lookup failure | Usually permanent | Retry once or twice, then drop |
| HTTP 408, 429, 500, 502, 503, 504 | Transient | Retry, honor `Retry-After` |
| HTTP 404, 410 | Permanent | Drop the URL |
| HTTP 401, 403 | Permanent for this crawler | Drop the URL, do not try to get around it |
| Redirect loop or too many redirects | Permanent | Drop the URL |
| Non-HTML content type | Permanent | Skip the body |
| Body larger than the size cap | Policy | Truncate or drop |
Treat a DNS failure with suspicion. It can mean a typo in a link, an expired domain, or a brief resolver outage. A small retry limit covers all three cases.
Timeouts
The timeout argument of urllib.request.urlopen is applied to each blocking socket operation. It is not a limit on the whole download. A server that sends one byte every nine seconds never trips a ten-second timeout, and a download like that can hold a worker for hours.
Add a total deadline of your own. Read the body in chunks and check the clock between chunks. Read in chunks for the size cap too, so a response with no Content-Length header cannot fill memory.
A fetch function that reports what happened
The function below returns an outcome instead of raising or returning None. The caller can then tell "done", "try later", and "give up" apart.
import http.client
import random
import socket
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
AGENT = 'MyCrawler'
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}
@dataclass
class Outcome:
kind: str # 'ok', 'retry', or 'permanent'
body: str | None = None
reason: str = ''
retry_after: float | None = None
def parse_retry_after(value):
"""Retry-After is either a number of seconds or an HTTP date."""
if not value:
return None
value = value.strip()
if value.isdigit():
return float(value)
try:
when = parsedate_to_datetime(value)
except (TypeError, ValueError):
return None
if when.tzinfo is None:
when = when.replace(tzinfo=timezone.utc)
return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
def try_fetch(url, timeout=10, max_bytes=2_000_000, total=30):
req = urllib.request.Request(url, headers={'User-Agent': AGENT})
stop = time.monotonic() + total
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
if resp.headers.get_content_type() != 'text/html':
return Outcome('permanent', reason='not html')
charset = resp.headers.get_content_charset() or 'utf-8'
chunks, size = [], 0
while size < max_bytes:
if time.monotonic() > stop:
return Outcome('retry', reason='total deadline exceeded')
chunk = resp.read(min(16384, max_bytes - size))
if not chunk:
break
chunks.append(chunk)
size += len(chunk)
data = b''.join(chunks)
try:
text = data.decode(charset, errors='replace')
except LookupError: # the server named an unknown charset
text = data.decode('utf-8', errors='replace')
return Outcome('ok', body=text)
except urllib.error.HTTPError as err:
if err.code in RETRYABLE_STATUS:
wait = parse_retry_after(err.headers.get('Retry-After'))
return Outcome('retry', reason=f'http {err.code}', retry_after=wait)
return Outcome('permanent', reason=f'http {err.code}')
except (urllib.error.URLError, OSError, http.client.HTTPException) as err:
return Outcome('retry', reason=type(err).__name__)
except ValueError as err:
return Outcome('permanent', reason=f'bad url: {err}')HTTPError is a subclass of URLError, so it must be caught first. urlopen follows up to 10 redirects by itself. A redirect loop surfaces as an HTTPError with code 302 or similar, which the function reports as permanent because 302 is not in the retryable set.
A truncated body is returned as ok. That is a policy choice. A cut-off page still yields useful links, but you may prefer to record that it was cut off.
Backoff with jitter
Retrying immediately usually hits the same problem. Retrying every five seconds from a hundred workers makes a struggling server worse. The standard answer is exponential backoff with jitter. The ceiling of the delay doubles with each attempt, and the actual delay is a random value below that ceiling.
import heapq
def backoff_delay(attempt, base=2.0, cap=300.0):
return random.uniform(0, min(cap, base * 2 ** attempt))
class RetryQueue:
def __init__(self, max_attempts=4):
self.max_attempts = max_attempts
self.attempts = {}
self.waiting = [] # heap of (due time, url)
def schedule(self, url, outcome):
n = self.attempts.get(url, 0) + 1
self.attempts[url] = n
if n >= self.max_attempts:
return False # out of attempts: give up
delay = max(backoff_delay(n), outcome.retry_after or 0.0)
heapq.heappush(self.waiting, (time.monotonic() + delay, url))
return True
def due(self):
now = time.monotonic()
ready = []
while self.waiting and self.waiting[0][0] <= now:
ready.append(heapq.heappop(self.waiting)[1])
return readyThe server's Retry-After value is a floor. The crawler never retries sooner than the server asked.
Where the retry goes
Do not call time.sleep inside the crawl loop and retry in place. The worker would idle while other hosts have work waiting. Put the URL in a retry queue and keep going.
When a URL comes due, put it back into the frontier. The frontier's add method ignores URLs already in the seen set, and a retried URL is always in that set. The frontier therefore needs a second entry point that skips the check:
# Add this method to the Frontier class
def requeue(self, url):
host = urlsplit(url).netloc
queue = self.queues.setdefault(host, deque())
if not queue:
heapq.heappush(self.ready, (self.next_time.get(host, 0.0), host))
queue.append(url)Requeueing through the frontier keeps the per-host delay in force, so a retry cannot jump ahead of the politeness rules.
Failing at the host level
Per-URL limits are not enough. If a host is down, each of its URLs spends its full set of attempts before giving up. With 10,000 queued URLs on that host, that is a lot of wasted requests.
Track consecutive failures per host. After a threshold, say five in a row, mark the host as unhealthy and pause it for a longer period, such as ten minutes. Pushing the host's next_time in the frontier forward does this. This pattern is called a circuit breaker. A single success resets the counter. A 429 or a 503 with Retry-After should move the whole host's next_time, not just the one URL.
Common mistakes
- Retrying 404 and 403 responses. These will not change in the next minute.
- Using only the socket timeout and no total deadline.
- Retrying on a fixed schedule with no jitter, so all workers retry at the same moment.
- Sleeping in the worker instead of rescheduling.
- Counting retries in the page budget. A page budget should count successful fetches, as the crawl loop in the earlier chapter does.
- Dropping URLs silently. Record the reason for each drop, because the counts are the main input to the monitoring chapter.
Exercise
A host returns HTTP 503 with the header Retry-After: 120 for every request. Your RetryQueue computes a backoff delay of 7 seconds for the next attempt. When is the URL retried, and what should the crawler also do for the other URLs from that host?
Show answer
The URL is retried after 120 seconds, because the delay is the larger of the backoff value and Retry-After. The crawler should also push the host's next allowed fetch time in the frontier at least 120 seconds ahead. Otherwise the host's other queued URLs would be fetched during that window and would probably receive 503 as well.
Exercise
Why does try_fetch check the clock between 16 KB reads instead of relying on the timeout argument alone?
Show answer
The timeout argument limits each blocking socket operation, not the whole download. A server that sends a few bytes just before each timeout expires would keep the worker busy indefinitely. Checking a total deadline between chunks bounds the time spent on one page.