Concurrent Site Crawler with Fault-Tolerant Fetching
Trees & GraphsModel answerLast updated
Build a crawler that explores every page reachable from a seed URL using a slow, flaky link API, evolving from a sequential traversal to a thread pool with bounded, backoff-driven retries.
You are given a seed URL and a function that reports which pages a given page links to:
fetch_links(url: str) -> list[str] # network call: slow, and may raise an exception on failure
Design and implement a crawler that discovers every page reachable from the seed by following links. Build it in three stages.
Before coding, state your assumptions. Good topics to settle: whether to stay on the seed's host or follow any link, whether there is a depth or page-count cap, how URLs are normalized (fragments, trailing slashes, case), what the crawler returns (page set, visit order, or link graph), and whether the API signals if an error is retryable and whether it enforces rate or concurrency limits.
Stage 1: Sequential crawl
Write crawl(seed) using BFS or DFS that returns the pages reached. Justify your traversal choice and discuss time and memory in terms of pages and links.
Stage 2: Concurrent crawl
Because network latency dominates, fetch several pages at the same time. The result must equal the sequential crawl's set of pages. Explain how you keep the shared visited set safe, how you detect that crawling is finished, how you cap the number of simultaneous fetches, and what happens if a worker thread raises.
Stage 3: Handling failures
fetch_links sometimes fails. Add retries so that no page is fetched more often than necessary and the crawler cannot loop forever. Explain which errors you retry, how many times, with what delay, how you avoid idling threads during a wait, how you protect a struggling host, and how the final result reports pages that never succeeded.
Hints
Hint 1
Mark a URL as seen at the moment you enqueue it, not when you fetch it, and make the check and insert one atomic step (a lock, or a single-threaded coordinator). Otherwise two workers can both schedule the same page.
Hint 2
For termination, track the number of pending units of work (queued plus in-flight) instead of just checking whether the queue is empty. The crawl is done when that counter reaches zero, since an in-flight fetch may still produce new links.
Hint 3
Treat retries as scheduled work: re-enqueue a failed URL with an attempt count and a not-before time rather than sleeping inside a worker. Use exponential backoff with jitter, cap the attempts, and record permanently failed URLs in a separate result set.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Scope: only URLs on the seed's host (same scheme and host), with no depth cap but an optional page limit.
- Normalization: drop fragments, lowercase scheme and host, strip a trailing slash on the path. Resolve relative links against the current page.
- Result: an object with
crawled(set of pages fetched successfully) andfailed(map of URL to last error). - Errors: transient errors (timeouts, 5xx, connection reset) are retryable; permanent ones (404, 410, malformed URL) are not. If the API does not distinguish them, retry a small bounded number of times regardless.
Stage 1: Sequential crawl
BFS with a queue and a visited set:
from collections import deque
def crawl(seed):
start = normalize(seed)
seen = {start}
queue = deque([start])
while queue:
url = queue.popleft()
for link in fetch_links(url):
link = normalize(link)
if in_scope(link) and link not in seen:
seen.add(link)
queue.append(link)
return seen
Each page is fetched once, and the total work is O(P + L) for P pages and L links, plus O(P) memory for the visited set and frontier. BFS is a good default because it reaches nearby pages first, which suits a depth or page cap. DFS gives the same set of pages; if you use it, use an explicit stack rather than recursion, since long link chains will blow the recursion limit. Mark pages as seen when enqueued, not when popped, so the queue never holds duplicates.
Stage 2: Concurrent crawl
Use a pool of N worker threads (for example 8 to 32, tuned to latency and what the host tolerates). The pool size is also the cap on concurrent fetches.
Key points:
- Atomic check-and-insert.
if link not in seen: seen.add(link)is a race across threads. Guard it with a lock, or have only one coordinator thread own the visited set while workers just fetch and return links. - Termination. An empty queue does not mean we are done, since an in-flight fetch may add more URLs. Keep a
pendingcounter incremented when a URL is enqueued and decremented when its processing (including enqueuing its children) finishes. Done whenpending == 0. Withqueue.Queue,task_done()andjoin()implement exactly this. Increment for children before decrementing for the parent. - Exceptions in workers. Wrap each fetch in try/except. An uncaught exception would kill the worker and leave
pendingnever reaching zero, causing a hang. Always decrement in afinally. - Shutdown. After
join(), push one sentinel per worker so they exit.
import threading, queue
def crawl_concurrent(seed, workers=16):
start = normalize(seed)
seen, lock = {start}, threading.Lock()
q = queue.Queue()
q.put(start)
def worker():
while True:
url = q.get()
if url is None:
return
try:
links = fetch_links(url)
for link in map(normalize, links):
if in_scope(link):
with lock:
if link in seen:
continue
seen.add(link)
q.put(link)
except Exception:
pass # handled properly in Stage 3
finally:
q.task_done()
threads = [threading.Thread(target=worker) for _ in range(workers)]
for t in threads: t.start()
q.join()
for _ in threads: q.put(None)
for t in threads: t.join()
return seen
Threads are appropriate because the work is I/O-bound, so the GIL is not a bottleneck. An asyncio version with a semaphore is an equally good alternative.
Stage 3: Retries
Treat a retry as new scheduled work rather than a loop inside the fetch.
- What to retry: only transient errors, up to a max attempts (say 4 total).
- Delay: exponential backoff with jitter:
delay = random.uniform(0, min(cap, base * 2**attempt)), for example base 0.5 s and cap 30 s. Jitter prevents all failed requests from retrying in lockstep. - Do not block workers. Do not
sleepinside a worker, which wastes a slot. Put the task in a delay heap or usethreading.Timerto re-enqueue it after the delay, keepingpendingincremented until the task finally succeeds or is abandoned. - No extra fetches. The URL stays in
seenfrom the first enqueue, so retries do not create duplicates. Only a failed attempt is repeated; a success is never re-fetched. - Protect the host. Add a per-host circuit breaker: after K consecutive failures, pause fetches to that host for a cooldown, and optionally honor
Retry-Afterand a rate limiter. This stops the crawler from hammering a failing service. - Termination: a task leaves
pendingonly when it succeeds or exhausts its attempts or hits a permanent error. This guarantees the crawl ends. - Reporting: on exhaustion, record
failed[url] = last_error. Note that the subtree behind a failed page is not discovered, so the result should say the crawl is incomplete and list the failed URLs so the caller can rerun them.
def process(url, attempt):
try:
links = fetch_links(url)
except RetryableError as e:
if attempt + 1 < MAX_ATTEMPTS:
schedule(url, attempt + 1, backoff(attempt)) # keeps pending held
return
failed[url] = e
return
except Exception as e:
failed[url] = e
return
crawled.add(url)
enqueue_new(links)
Trade-offs and common mistakes
- Marking visited on fetch rather than on enqueue, causing duplicate fetches.
- Declaring completion when the queue is empty while fetches are still in flight.
- Letting an exception kill a worker and hang
join(). - Sleeping inside workers during backoff, which throttles throughput.
- Retrying without a cap, without jitter, or retrying permanent errors.
- Returning a silently partial result with no failure report.
- Unbounded concurrency, which can overwhelm the target or exhaust sockets.
- Forgetting URL normalization, which makes the visited set miss duplicates and can create near-infinite crawls on sites with calendar or session links.
For very large crawls, the visited set can be a Bloom filter or sharded store, and the frontier can be a persistent queue partitioned by host to enforce politeness.