KatInterview

Concurrent Site Crawler with Fault-Tolerant Fetching

Trees & GraphsModel answer
MediumModel answerTrees & Graphsweb-crawlerconcurrencybfs

Last 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.