Sub topic 9
Handling failures, timeouts, and retries
This chapter assumes you have read the chapters on fetching pages and on the URL frontier. You should know how urllib.request works, what HTTP status codes mean, and how the frontier hands out URLs.
A crawler talks to many servers you don't control. Some are slow, some are down, and some return errors on purpose. Without failure handling, one bad host can stall the whole crawl or silently lose pages.
Sort failures into two groups
Retrying only helps when the failure might go away. Sort each outcome before you decide what to do.
| Outcome | Kind | Action |
|---|---|---|
| Timeout, connection reset, DNS failure | Transient | Retry with backoff |
| 429, 503 | Transient | Retry, honoring `Retry-After` |
| 500, 502, 504 | Usually transient | Retry a few times |
| 404, 410 | Permanent | Drop the URL |
| 403, 401 | Permanent for a crawler | Drop the URL |
| Non-HTML type, body over the size cap | Permanent | Skip the page |
Always set a timeout
urlopen without a timeout can block forever. The timeout argument limits each blocking socket operation, not the whole download. A server that sends one byte every few seconds can still hold a worker. Cap the total size you read, as the fetch function does with max_bytes, and consider a wall-clock deadline in addition.
Retry with exponential backoff
Retrying immediately hits a struggling server again at the worst moment. Wait longer after each attempt, and add random jitter so many workers don't retry in lockstep.
import random
import time
import urllib.error
import urllib.request
RETRY_STATUS = {429, 500, 502, 503, 504}
def fetch_with_retry(url, attempts=3, base_delay=1.0, timeout=10):
for attempt in range(attempts):
try:
req = urllib.request.Request(url, headers={'User-Agent': 'MyCrawler'})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read(2_000_000)
except urllib.error.HTTPError as err:
if err.code not in RETRY_STATUS:
return None # permanent failure, such as 404
retry_after = err.headers.get('Retry-After', '')
delay = int(retry_after) if retry_after.isdigit() else None
except (urllib.error.URLError, TimeoutError, ConnectionError):
delay = None
if attempt == attempts - 1:
return None
if delay is None:
delay = base_delay * 2 ** attempt + random.uniform(0, 0.5)
time.sleep(delay)
return NoneHTTPError is a subclass of URLError, so it must be caught first. A numeric Retry-After header overrides the computed delay. The header can also hold a date, which this sketch ignores.
Keep retries from hurting politeness
Sleeping inside the fetch call blocks a worker and ignores the frontier's per-host delay. A better design puts the URL back in the frontier with a later ready time and a retry count. Other hosts keep being served while the failed one waits. Give up after a fixed number of attempts and record the URL as failed, so the crawl always makes progress.
Redirects and loops
urllib follows redirects automatically and stops after a small number of hops. Treat the final URL as the page's real address. Normalize it and add it to the seen set so you don't fetch it again under another name.
Exercise
A crawler gets HTTP 503 with Retry-After: 120 from a host. It also gets HTTP 404 from another URL. What should it do with each?
Show answer
Treat the 503 as transient. Requeue the URL with a ready time at least 120 seconds ahead, and count the attempt against the retry limit. Treat the 404 as permanent. Drop the URL and do not retry.
Exercise
Why is urlopen(url, timeout=10) alone not enough to bound the time a worker spends on one page?
Show answer
The timeout applies to each blocking socket operation, such as connecting or waiting for the next bytes. A server that keeps sending data slowly never triggers it, so you also need a cap on bytes read or a total deadline.