Single-Fetch Web Crawler with Bounded Parallelism

Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

You are given a thread-safe helper fetch_and_parse(url: str) -> List[str] that downloads a web page and returns the list of outgoing canonical URL strings found on that page. Starting from seed_url, implement both a single-threaded baseline crawler and a production-grade bounded-concurrency crawler that visit every reachable page without returning a result collection (None).

Implement the following exception and functions defined in starter.py:

  • CrawlIncompleteError(failed: Dict[str, str], not_attempted: List[str]): an Exception subclass raised whenever crawl cannot guarantee that every reachable page was fetched cleanly:
    • self.failed: maps each URL whose attempts all failed to its final error description (str). Pages reachable solely behind a failed page are never discovered.
    • self.not_attempted: lists reserved URLs that were queued in the frontier when cancellation stopped the crawl before they could be fetched.
  • crawl_sequential(seed_url: str, fetch_and_parse: Callable[[str], List[str]]) -> None: single-threaded traversal over a finite static graph where every fetch succeeds. Invoke fetch_and_parse(url) once for every distinct URL reachable from seed_url (including seed_url itself), invoke it zero times for unreachable URLs, and properly deduplicate self-links, cycles, and multi-parent diamond paths.
  • crawl(seed_url: str, fetch_and_parse: Callable[[str], List[str]], max_workers: int = 8, max_attempts: int = 1, cancel: Optional[threading.Event] = None) -> None: concurrent traversal obeying all of the following rules:
    1. Configuration validation: Raise ValueError immediately if max_workers < 1 or max_attempts < 1.
    2. Bounded parallelism: Run at most max_workers concurrent calls to fetch_and_parse at any moment, executing network calls outside shared locks so independent pages download in parallel.
    3. Atomic reservation and exact termination: Reserve unseen URLs atomically upon discovery, keep workers waiting whenever the queue is momentarily empty while in-flight fetches may still emit child links, avoid producer-consumer queue deadlocks, and return only once zero URLs remain queued and zero fetches remain active.
    4. Retries and failure reporting: When fetches succeed, call fetch_and_parse once per distinct reachable URL and return None. When a call raises an Exception, retry that URL up to max_attempts total calls; if every attempt raises, record {url: error_message} in failed, finish crawling all other reachable branches, and raise CrawlIncompleteError(failed, not_attempted).
    5. Worker crash resilience: Even if a non-Exception BaseException (such as SystemExit) escapes fetch_and_parse, record that URL in failed and update work accounting so surviving workers never block forever.
    6. Cooperative cancellation: Once cancel is set (before start or mid-run), start no new fetches and no new retry attempts (a page whose retry is skipped due to cancellation is recorded in failed), wait for already-running fetches to finish, and raise CrawlIncompleteError(failed, not_attempted).

Examples

Example 1

Input:

web = {
    "https://docs.io/home": ["https://docs.io/home", "https://docs.io/guide", "https://docs.io/api"],
    "https://docs.io/guide": ["https://docs.io/faq", "https://docs.io/home"],
    "https://docs.io/api": ["https://docs.io/faq", "https://docs.io/changelog"],
    "https://docs.io/faq": ["https://docs.io/guide"],
    "https://docs.io/changelog": [],
    "https://docs.io/orphan": ["https://docs.io/home"],
}
crawl("https://docs.io/home", fetch_and_parse, max_workers=3, max_attempts=1)

Output: Returns None, with fetch_and_parse call counts:

{
    "https://docs.io/home": 1,
    "https://docs.io/guide": 1,
    "https://docs.io/api": 1,
    "https://docs.io/faq": 1,
    "https://docs.io/changelog": 1,
}

Explanation: Starting from "https://docs.io/home", the self-link back to "home" is skipped because "home" was reserved initially. Both "guide" and "api" link to "faq", which is reserved on first discovery and skipped on the second link. Cycles "guide" -> "home" and "faq" -> "guide" are ignored, "changelog" is a leaf page, and "https://docs.io/orphan" is never visited because no path from "home" reaches it (crawl_sequential produces the identical call counts).

Example 2

Input:

web = {
    "https://shop.io/index": ["https://shop.io/catalog", "https://shop.io/broken"],
    "https://shop.io/catalog": ["https://shop.io/item-7"],
    "https://shop.io/broken": ["https://shop.io/secret"],
}
# Suppose "https://shop.io/catalog" fails once with ConnectionError then succeeds,
# while "https://shop.io/broken" raises ConnectionError on every attempt.
crawl("https://shop.io/index", fetch_and_parse, max_workers=2, max_attempts=2)

Output: Raises CrawlIncompleteError with list(err.failed) == ["https://shop.io/broken"], err.not_attempted == [], and fetch_and_parse call counts:

{
    "https://shop.io/index": 1,
    "https://shop.io/catalog": 2,
    "https://shop.io/item-7": 1,
    "https://shop.io/broken": 2,
}

Explanation: "catalog" recovers on its second attempt so "item-7" is discovered and fetched once. "broken" fails both allowed attempts, preventing discovery of "secret", and after all reachable non-failing work finishes, crawl raises CrawlIncompleteError.

Example 3

Input:

web = {
    "https://news.io/front": ["https://news.io/world", "https://news.io/tech", "https://news.io/sports"],
}
# Suppose cancel.set() runs while fetch_and_parse("https://news.io/front") is executing.
crawl("https://news.io/front", fetch_and_parse, max_workers=2, max_attempts=1, cancel=cancel)

Output: Raises CrawlIncompleteError with err.failed == {}, sorted(err.not_attempted) == ["https://news.io/sports", "https://news.io/tech", "https://news.io/world"], and fetch_and_parse call counts {"https://news.io/front": 1}.

Explanation: The in-flight seed fetch finishes and reserves its three outgoing links, but because cancel is set, workers start zero new fetches and report the queued links in not_attempted.

Constraints

  • Do not parse raw HTML or change the fetch_and_parse(url: str) -> List[str] interface; pages with no outgoing links return [].
  • Do not introduce hidden host filters, depth cutoffs, or page-count caps that silently skip reachable URLs.
  • Under the baseline assumption (finite static reachable graph, canonical URL strings, error-free fetches), crawl_sequential and crawl must call fetch_and_parse once per distinct reachable URL.
  • max_workers and max_attempts are integers; raise ValueError whenever either is < 1.
  • Peak concurrent calls to fetch_and_parse must never exceed max_workers, and zero fetches may remain running after crawl returns or raises.

Step-by-step walkthrough

  1. Restate the problem and pin down the contract

    We are given a thread-safe helper fetchAndParse(url) (in Python, fetch_and_parse(url)) that downloads one page and returns the list of outgoing link strings on it. Our job is to implement crawl(seed_url, ...) with no return value (None), visiting every reachable page starting from seed_url.

    Because the function returns nothing, its contract is defined entirely by which calls to fetch_and_parse happen and whether the function returns normally or raises an error:

    • Baseline success contract: on a finite static web graph where every fetch succeeds, fetch_and_parse is called exactly once for seed_url and for every distinct reachable URL, and zero times for any unreachable URL.
    • URL identity: under the baseline, each canonical URL string identifies a distinct page. (In a real crawler, stripping #fragment anchors or normalizing trailing slashes happens right before checking visited, without changing the traversal logic.)
    • No silent truncation: we never silently drop pages behind an arbitrary depth or page cap. If a crawl stops early due to cancellation or exhausted retries, returning normally would lie to the caller, so crawl raises CrawlIncompleteError listing failed and unattempted URLs.
    • Retries vs attempts: once network failures are possible, no crawler can promise at most one attempt while also retrying failures; "exactly once" becomes at most one successful fetch per URL (up to max_attempts total calls when attempts fail).
  2. Part 1: Single-threaded BFS that reserves on discovery

    Start with one thread. We maintain two structures: - frontier: a first-in, first-out (FIFO) queue of URLs waiting to be fetched—this gives breadth-first search (BFS), visiting pages level by level outward from seed_url. - visited: a hash set of every URL that has already been reserved, whether it has been fetched or is still sitting in frontier.

    The single most important rule in Part 1 is when a URL enters visited: reserve it at discovery time (right before appending to frontier), NOT after fetching it. See why on Example 1's diamond subgraph (home -> [home, guide, api], guide -> [faq, home], api -> [faq, changelog]):

    Reserve AFTER fetch (broken):                   Reserve ON discovery (exact):
    1. fetch home -> queue guide, api               1. start: visited={home}, frontier=[home]
    2. fetch guide -> faq not fetched -> [api,faq]  2. fetch home -> skip home; reserve guide, api
    3. fetch api -> faq STILL not fetched!          3. fetch guide -> reserve faq; skip home
                    queues a 2nd faq -> [faq,faq]   4. fetch api -> faq already in visited; reserve changelog
    4. faq is fetched TWICE!                        5. fetch faq, changelog -> frontier=[], return
    
    from typing import Callable, List
    from collections import deque
    
    
    def crawl_sequential(
        seed_url: str,
        fetch_and_parse: Callable[[str], List[str]],
    ) -> None:
        """Single-threaded BFS: call fetch_and_parse once per reachable URL."""
        # visited: every URL ever reserved (already fetched OR waiting in frontier),
        # e.g. {"https://docs.io/home", "https://docs.io/guide"}
        visited = {seed_url}
        # frontier: FIFO queue of reserved URLs waiting to be fetched, e.g. deque(["https://docs.io/home"])
        frontier = deque([seed_url])
    
        while frontier:
            current_url = frontier.popleft()
            discovered_links = fetch_and_parse(current_url)
            for link in discovered_links:
                # Reserve each unseen URL at discovery time—before queuing—so self-links,
                # cycles, and diamond paths never put duplicate copies in frontier.
                if link not in visited:
                    visited.add(link)
                    frontier.append(link)
    

    Why every tricky graph topology works and terminates: - Self-links (home -> home) and cycles (guide -> home, guide <-> faq): home and guide are already in visited before any link back to them is inspected, so neither is ever queued again. - Multiple parents (guide -> faq and api -> faq): the first parent to inspect faq adds it to visited and frontier; the second parent sees faq in visited and skips it. - Termination and complexity: in a single thread, nothing is running in the background, so frontier becoming empty guarantees all V reachable pages have been fetched. Graph bookkeeping performs O(V + E) hash-set and deque operations across V reachable pages and E total outgoing links using O(V) memory—completely separate from network download and HTML parsing cost.

  3. Identify the bottleneck and bound concurrency

    In crawl_sequential, the CPU sits idle almost the entire time waiting on network round-trips. Suppose a crawl visits V = 10,000 pages where each fetch_and_parse spends 200 ms waiting on HTTP and 2 ms parsing HTML:

    Sequential wall time: 10,000 * 0.202 s = 2,020 s (~34 minutes), CPU busy < 1% of the time
    

    Because independent URLs already in frontier do not depend on one another, W worker threads can overlap those network waits. Regardless of scheduler design, wall-clock time obeys two fundamental lower bounds (for fetch latency L and deepest shortest-path hop count D from seed_url):

    Wall time >= (V * L) / W     (throughput bound: W workers finish at most W / L pages per second)
    Wall time >= (D + 1) * L     (chain bound: a page D hops deep cannot be discovered until D ancestor fetches finish)
    

    With W = 50 workers and depth D = 6, network time drops from 34 minutes toward max(10,000 * 0.2 / 50, 7 * 0.2) = 40 seconds whenever the frontier stays wide enough to feed all 50 workers. (Note for Python: CPython's Global Interpreter Lock (GIL)—an internal lock allowing only one thread to run Python bytecode at once—is released during socket I/O so network waits overlap freely, though 10,000 * 2 ms = 20 s of pure-Python parsing remains a single-core floor unless parsing uses C extensions or multiple processes.)

    Concurrency must be bounded (max_workers = W): spawning an unbounded thread per discovered link would exhaust OS file descriptors, blow up memory, and overwhelm target servers.

  4. Part 2: Atomic reservation and tracking in-flight work

    Adding W worker threads breaks naive BFS in two places:

    1. Duplicate discovery (race condition): a race condition occurs when two threads read and modify shared state concurrently. If Worker 1 (finishing guide) and Worker 2 (finishing api) both check if "faq" not in visited: at the same instant before either inserts "faq", both pass the check and fetch "faq" twice. Checking visited, adding "faq", and appending to frontier must happen atomically inside a mutex (lock)—while the slow fetch_and_parse(url) call MUST happen outside the lock so workers actually run in parallel.
    2. Premature termination when the frontier is temporarily empty: right after Worker 1 pops seed_url, frontier is empty ([]), yet Worker 1 is still downloading seed_url and is about to discover dozens of links! If Worker 2 sees an empty frontier and exits, parallelism collapses to 1 thread; if crawl returns on an empty frontier, it returns before the crawl is done.

    The state that stays nonzero during an in-flight fetch is pending: queued pages plus currently active fetches:

    pending = len(frontier) + active_fetches
    
    Start:           frontier=[home], active=0  -> pending = 1
    Worker pops url: frontier=[],     active=1  -> pending = 1  (unchanged! Workers wait, do NOT exit)
    Finish url (+2 unseen links guide, api):
      Step A (+children first): frontier=[guide,api], active=1 -> pending = 1 + 2 = 3
      Step B (-parent second):  frontier=[guide,api], active=0 -> pending = 3 - 1 = 2
    All work done:   frontier=[],     active=0  -> pending = 0  (safe to wake everyone and exit!)
    

    Notice the ordering in finish: we increment pending for newly discovered child links before decrementing pending for the finished parent page, so pending never transiently hits 0. A condition variable (threading.Condition) pairs the lock with wait() and notify_all() so idle workers sleep without burning CPU. Waiting always sits inside a while True loop to guard against lost races and spurious wakeups (rare OS wakeups when the condition is not yet satisfied).

    import threading
    from typing import Dict, Optional
    
    
    class _CrawlState:
        """Thread-safe coordinator for one concurrent crawl guarded by `self.cond`."""
    
        def __init__(self, seed_url: str, cancel: Optional[threading.Event]) -> None:
            self.cond = threading.Condition()
            # visited: set of all reserved URL strings discovered so far
            self.visited = {seed_url}
            # frontier: unbounded FIFO deque of reserved URLs waiting for a worker;
            # len(frontier) <= len(visited) because each URL is queued at most once.
            self.frontier = deque([seed_url])
            # pending: invariant pending == len(frontier) + active_fetches.
            # Only when pending == 0 are both the queue and all workers completely idle.
            self.pending = 1
            # failed: {url: "ErrorType: details"} for URLs whose attempts all failed
            self.failed: Dict[str, str] = {}
            self.cancel = cancel
    
        def take(self) -> Optional[str]:
            """Pop the next URL to fetch, waiting if needed, or return None to exit."""
            with self.cond:
                # Loop around cond.wait() to re-check state after wakeups or lost races.
                while True:
                    if self.cancel is not None and self.cancel.is_set():
                        return None
                    if self.frontier:
                        # Popping moves 1 URL from frontier to active_fetches,
                        # so pending (queued + active) stays unchanged.
                        return self.frontier.popleft()
                    if self.pending == 0:
                        return None
                    # Frontier is empty right now, but pending > 0 means another worker
                    # is still fetching a page that may discover new child URLs.
                    self.cond.wait()
    
        def finish(self, url: str, links: List[str], error: Optional[str]) -> None:
            """Record any failure, atomically reserve unseen links, and retire `url`."""
            with self.cond:
                if error is not None:
                    self.failed[url] = error
    
                # Phase 1: count and enqueue newly discovered children BEFORE decrementing
                # pending for `url`, so pending never momentarily dips to 0 mid-handoff.
                for link in links:
                    if link not in self.visited:
                        self.visited.add(link)
                        self.frontier.append(link)
                        self.pending += 1
    
                # Phase 2: retire the finished parent fetch and wake waiting workers.
                self.pending -= 1
                self.cond.notify_all()
    
  5. Avoid producer-consumer deadlock on the frontier

    Backpressure is the policy for handling work produced faster than consumers drain it. A classic trap in concurrent crawlers is replacing deque with a bounded queue.Queue(maxsize=C) and calling blocking put() inside workers. Because every worker is both a consumer (get) and a producer (put), a bounded blocking queue causes a deadlock—a permanent freeze where every worker waits on space that only another worker could free:

    Capacity C = 2, Workers W = 2, Queue already full: [u3, u4]
      Worker 1 finishes u1 (found u5) -> calls queue.put(u5) -> BLOCKS waiting for free slot
      Worker 2 finishes u2 (found u6) -> calls queue.put(u6) -> BLOCKS waiting for free slot
      Who is left to call queue.get() and free a slot? NOBODY -> permanent deadlock!
    

    Our design avoids this cleanly by separating the two limits: - In-flight concurrency is bounded by the fixed pool of max_workers threads (<= W concurrent network calls). - Publishing discovered links is non-blocking into self.frontier. Even without an artificial cap on self.frontier, memory is already bounded by O(V) because each distinct reachable URL is added to self.frontier at most once when reserved in self.visited (len(frontier) <= len(visited) <= V). At web scale where V exceeds RAM, keep link publishing non-blocking by spilling frontier segments and visited keys to disk or a database rather than blocking active workers.

  6. Worker loop, single-owner retries, and safe exception handling

    Now wire up error reporting, retries, worker survival, and crawl:

    • Single-owner retries (_fetch_with_retries): the worker that pops url owns all 1..max_attempts tries in a plain local loop. Never re-push a failing URL back onto frontier from multiple places (like a worker and a separate timeout monitor), or two workers can retry the same URL concurrently. Because a retry is a new fetch call, check cancel.is_set() before starting any retry.
    • Unbreakable pending accounting (_worker): if an unexpected exception escapes fetch_and_parse and kills a worker without calling state.finish(...), pending stays stuck above 0 forever and hangs every surviving worker. Catching Exception handles ordinary errors per attempt, while wrapping the fetch in except BaseException + finally: state.finish(...) guarantees that even a fatal SystemExit records url in failed, decrements pending, and wakes the other workers.
    from typing import Tuple
    
    
    class CrawlIncompleteError(Exception):
        """Raised by crawl when it cannot claim that every reachable page was fetched.
    
        failed:        {url: last error message} for pages whose every attempt raised.
                       Pages reachable only through a failed page were never discovered.
        not_attempted: reserved URLs that were never fetched because the crawl was cancelled.
        """
    
        def __init__(self, failed: Dict[str, str], not_attempted: List[str]) -> None:
            self.failed = failed
            self.not_attempted = not_attempted
            message = (
                f"{len(failed)} page(s) failed, "
                f"{len(not_attempted)} page(s) never attempted"
            )
            super().__init__(message)
    
    
    def _fetch_with_retries(
        url: str,
        fetch_and_parse: Callable[[str], List[str]],
        max_attempts: int,
        cancel: Optional[threading.Event],
    ) -> Tuple[List[str], Optional[str]]:
        """Fetch `url` up to `max_attempts` times outside all locks."""
        last_error = ""
        for _ in range(max_attempts):
            try:
                links = list(fetch_and_parse(url))
                return links, None
            except Exception as exc:
                # Catch normal runtime/network errors per attempt so the worker survives.
                last_error = f"{type(exc).__name__}: {exc}"
    
            # Each retry is a fresh fetch call; stop immediately if cancellation arrived.
            if cancel is not None and cancel.is_set():
                break
    
        return [], last_error
    
    
    def _worker(
        state: _CrawlState,
        fetch_and_parse: Callable[[str], List[str]],
        max_attempts: int,
    ) -> None:
        """Worker loop: take a reserved URL, fetch outside the lock, publish results."""
        while True:
            url = state.take()
            if url is None:
                return
    
            links: List[str] = []
            error: Optional[str] = "worker terminated unexpectedly during fetch"
            try:
                # Perform network I/O and parsing with NO shared lock held.
                links, error = _fetch_with_retries(
                    url, fetch_and_parse, max_attempts, state.cancel
                )
            except BaseException as exc:
                # Capture non-Exception crashes (e.g. SystemExit) so `url` is still
                # recorded in `failed` before `finally` decrements `pending`.
                error = f"{type(exc).__name__}: {exc}"
                raise
            finally:
                state.finish(url, links, error)
    
    
    def crawl(
        seed_url: str,
        fetch_and_parse: Callable[[str], List[str]],
        max_workers: int = 8,
        max_attempts: int = 1,
        cancel: Optional[threading.Event] = None,
    ) -> None:
        """Crawl every page reachable from `seed_url` with bounded concurrency."""
        if max_workers < 1 or max_attempts < 1:
            raise ValueError("max_workers and max_attempts must be at least 1")
    
        state = _CrawlState(seed_url, cancel)
    
        # Start a fixed pool of `max_workers` threads to cap concurrent fetches.
        workers: List[threading.Thread] = []
        for index in range(max_workers):
            worker = threading.Thread(
                target=_worker,
                args=(state, fetch_and_parse, max_attempts),
                name=f"crawler-{index}",
            )
            worker.start()
            workers.append(worker)
    
        # Wait until every worker exits so zero fetches remain in flight upon return.
        for worker in workers:
            worker.join()
    
        # Honest void contract: return normally only on complete, error-free traversal.
        if state.failed or state.frontier:
            raise CrawlIncompleteError(dict(state.failed), list(state.frontier))
    
  7. Trace two workers and define the production failure contract

    Trace W = 2 workers on Example 1 (home -> [home, guide, api], guide -> [faq, home], api -> [faq, changelog], faq -> [guide], changelog -> [], plus unreachable orphan -> [home]):

    Event                                          frontier         active   pending   visited
    -----------------------------------------------------------------------------------------------------------------
    Initial state                                  [home]           0        1         {home}
    W1 pops home; W2 sees frontier=[], pending=1   []               1        1         {home}
      -> W2 sleeps in cond.wait()
    W1 finishes home: skips home; reserves         [guide, api]     0        1+2-1=2   {home,guide,api}
      guide, api
    W1 pops guide; W2 wakes and pops api           []               2        2         {home,guide,api}
    W2 finishes api: reserves faq, changelog       [faq, changelog] 1        2+2-1=3   {home,guide,api,faq,changelog}
    W2 pops faq (guide and faq both fetching)      [changelog]      2        3         {home,guide,api,faq,changelog}
    W1 finishes guide: faq, home already visited   [changelog]      1        3+0-1=2   {home,guide,api,faq,changelog}
    W1 pops changelog                              []               2        2         {home,guide,api,faq,changelog}
    W2 finishes faq: guide already visited         []               1        2+0-1=1   {home,guide,api,faq,changelog}
    W2 sees frontier=[], pending=1 -> sleeps       []               1        1         {home,guide,api,faq,changelog}
    W1 finishes changelog: []                      []               0        1+0-1=0   {home,guide,api,faq,changelog}
      -> notify_all() wakes W2; both see pending == 0 and exit; crawl returns None
    

    Every reachable URL (home, guide, api, faq, changelog) is fetched once, orphan is never touched, and pending >= 1 keeps W1 and W2 alive whenever the queue is momentarily empty.

    Part 3 — Production failure and crash-recovery contract: - Explicit URL lifecycle: each URL moves strictly forward from reserved (queued) -> in_flight (attempt k of N owned by one worker) -> terminal (succeeded, failed, or not_attempted). - Backoff and per-attempt timeouts: in production, retry only transient faults (network timeouts, HTTP 429/5xx) using exponential backoff with jitter—doubling wait times (1s, 2s, 4s...) plus random noise so workers do not hammer a recovering host simultaneously—and pass a socket timeout into the HTTP client because Python cannot forcibly kill a blocked thread. - Process crash mid-request: if our process crashes after sending an HTTP request for url and before saving completion to disk, no restarted process can prove whether the remote server received that call. Therefore, across crashes, at-least-once attempts are unavoidable (persist in_flight to a database before sending, and re-queue in_flight rows on restart), paired with effectively-once processing: save parsed page data, child URL reservations, and state = "succeeded" in a single atomic database transaction keyed by url (an upsert, which overwrites by primary key instead of duplicating). If crawling triggers external side effects (like billing or webhooks), attach an idempotency key (hash(crawl_id, url)) so the downstream service deduplicates repeated deliveries.

  8. Put the full crawler together

    Here is the complete solution.py combining sequential BFS, bounded concurrent traversal, single-owner retries, cancellation, and CrawlIncompleteError:

    from typing import Callable, Dict, List, Optional, Tuple
    import threading
    from collections import deque
    
    
    class CrawlIncompleteError(Exception):
        """Raised by crawl when it cannot claim that every reachable page was fetched.
    
        failed:        {url: last error message} for pages whose every attempt raised.
                       Pages reachable only through a failed page were never discovered.
        not_attempted: reserved URLs that were never fetched because the crawl was cancelled.
        """
    
        def __init__(self, failed: Dict[str, str], not_attempted: List[str]) -> None:
            self.failed = failed
            self.not_attempted = not_attempted
            message = (
                f"{len(failed)} page(s) failed, "
                f"{len(not_attempted)} page(s) never attempted"
            )
            super().__init__(message)
    
    
    def crawl_sequential(
        seed_url: str,
        fetch_and_parse: Callable[[str], List[str]],
    ) -> None:
        """Single-threaded BFS: call fetch_and_parse once per reachable URL."""
        # visited: every URL ever reserved (already fetched OR waiting in frontier),
        # e.g. {"https://docs.io/home", "https://docs.io/guide"}
        visited = {seed_url}
        # frontier: FIFO queue of reserved URLs waiting to be fetched, e.g. deque(["https://docs.io/home"])
        frontier = deque([seed_url])
    
        while frontier:
            current_url = frontier.popleft()
            discovered_links = fetch_and_parse(current_url)
            for link in discovered_links:
                # Reserve each unseen URL at discovery time—before queuing—so self-links,
                # cycles, and diamond paths never put duplicate copies in frontier.
                if link not in visited:
                    visited.add(link)
                    frontier.append(link)
    
    
    class _CrawlState:
        """Thread-safe coordinator for one concurrent crawl guarded by `self.cond`."""
    
        def __init__(self, seed_url: str, cancel: Optional[threading.Event]) -> None:
            self.cond = threading.Condition()
            # visited: set of all reserved URL strings discovered so far
            self.visited = {seed_url}
            # frontier: unbounded FIFO deque of reserved URLs waiting for a worker;
            # len(frontier) <= len(visited) because each URL is queued at most once.
            self.frontier = deque([seed_url])
            # pending: invariant pending == len(frontier) + active_fetches.
            # Only when pending == 0 are both the queue and all workers completely idle.
            self.pending = 1
            # failed: {url: "ErrorType: details"} for URLs whose attempts all failed
            self.failed: Dict[str, str] = {}
            self.cancel = cancel
    
        def take(self) -> Optional[str]:
            """Pop the next URL to fetch, waiting if needed, or return None to exit."""
            with self.cond:
                # Loop around cond.wait() to re-check state after wakeups or lost races.
                while True:
                    if self.cancel is not None and self.cancel.is_set():
                        return None
                    if self.frontier:
                        # Popping moves 1 URL from frontier to active_fetches,
                        # so pending (queued + active) stays unchanged.
                        return self.frontier.popleft()
                    if self.pending == 0:
                        return None
                    # Frontier is empty right now, but pending > 0 means another worker
                    # is still fetching a page that may discover new child URLs.
                    self.cond.wait()
    
        def finish(self, url: str, links: List[str], error: Optional[str]) -> None:
            """Record any failure, atomically reserve unseen links, and retire `url`."""
            with self.cond:
                if error is not None:
                    self.failed[url] = error
    
                # Phase 1: count and enqueue newly discovered children BEFORE decrementing
                # pending for `url`, so pending never momentarily dips to 0 mid-handoff.
                for link in links:
                    if link not in self.visited:
                        self.visited.add(link)
                        self.frontier.append(link)
                        self.pending += 1
    
                # Phase 2: retire the finished parent fetch and wake waiting workers.
                self.pending -= 1
                self.cond.notify_all()
    
    
    def _fetch_with_retries(
        url: str,
        fetch_and_parse: Callable[[str], List[str]],
        max_attempts: int,
        cancel: Optional[threading.Event],
    ) -> Tuple[List[str], Optional[str]]:
        """Fetch `url` up to `max_attempts` times outside all locks."""
        last_error = ""
        for _ in range(max_attempts):
            try:
                links = list(fetch_and_parse(url))
                return links, None
            except Exception as exc:
                # Catch normal runtime/network errors per attempt so the worker survives.
                last_error = f"{type(exc).__name__}: {exc}"
    
            # Each retry is a fresh fetch call; stop immediately if cancellation arrived.
            if cancel is not None and cancel.is_set():
                break
    
        return [], last_error
    
    
    def _worker(
        state: _CrawlState,
        fetch_and_parse: Callable[[str], List[str]],
        max_attempts: int,
    ) -> None:
        """Worker loop: take a reserved URL, fetch outside the lock, publish results."""
        while True:
            url = state.take()
            if url is None:
                return
    
            links: List[str] = []
            error: Optional[str] = "worker terminated unexpectedly during fetch"
            try:
                # Perform network I/O and parsing with NO shared lock held.
                links, error = _fetch_with_retries(
                    url, fetch_and_parse, max_attempts, state.cancel
                )
            except BaseException as exc:
                # Capture non-Exception crashes (e.g. SystemExit) so `url` is still
                # recorded in `failed` before `finally` decrements `pending`.
                error = f"{type(exc).__name__}: {exc}"
                raise
            finally:
                state.finish(url, links, error)
    
    
    def crawl(
        seed_url: str,
        fetch_and_parse: Callable[[str], List[str]],
        max_workers: int = 8,
        max_attempts: int = 1,
        cancel: Optional[threading.Event] = None,
    ) -> None:
        """Crawl every page reachable from `seed_url` with bounded concurrency."""
        if max_workers < 1 or max_attempts < 1:
            raise ValueError("max_workers and max_attempts must be at least 1")
    
        state = _CrawlState(seed_url, cancel)
    
        # Start a fixed pool of `max_workers` threads to cap concurrent fetches.
        workers: List[threading.Thread] = []
        for index in range(max_workers):
            worker = threading.Thread(
                target=_worker,
                args=(state, fetch_and_parse, max_attempts),
                name=f"crawler-{index}",
            )
            worker.start()
            workers.append(worker)
    
        # Wait until every worker exits so zero fetches remain in flight upon return.
        for worker in workers:
            worker.join()
    
        # Honest void contract: return normally only on complete, error-free traversal.
        if state.failed or state.frontier:
            raise CrawlIncompleteError(dict(state.failed), list(state.frontier))
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a team of research assistants mapping every room in a museum starting from the lobby (seed_url). They keep one shared master checklist (visited) and a clipboard of rooms waiting to be inspected (frontier, the queue of reserved URLs not yet fetched). Whenever an assistant steps out of a room with newly spotted doorways, they briefly grab the master clipboard under a mutex (a lock ensuring only one assistant edits the list at a time), cross off any new room immediately before adding it to the waiting list, and keep a running tally (pending) of rooms on the waiting list plus assistants still inside rooms. Only when pending hits 0—meaning the clipboard is empty and nobody is still inside a room about to find another door—does everyone pack up and go home.

Naive crawlers break in three classic ways. First, if you mark a URL visited after downloading it instead of when you first discover it, two workers visiting guide and api will both enqueue shared child faq and download faq twice. Second, if workers exit as soon as frontier looks empty, every extra worker quits during the very first millisecond while Worker 1 is still downloading seed_url, collapsing a 50-thread crawler onto 1 thread (or returning before child links are even discovered). Third, using a bounded blocking queue where workers both consume URLs and push child URLs can cause a deadlock—a permanent freeze where every worker blocks trying to push new links into a full queue with nobody left to pop.

Walk through the diamond core of Example 1 (home -> [guide, api], guide -> [faq], api -> [faq]) with 2 workers: 1. Start with visited = {home}, frontier = [home], pending = 1. Worker 1 pops home (frontier = [], pending = 1). Worker 2 sees an empty frontier but pending == 1, so it sleeps on a condition variable (a lock-plus-wakeup primitive) instead of exiting. 2. Worker 1 finishes home, acquires the lock, reserves guide and api (pending becomes 1 + 2 - 1 = 2), and wakes Worker 2. 3. Worker 1 fetches guide while Worker 2 fetches api in parallel outside the lock. Whoever finishes first reserves faq (pending stays 2); whoever finishes second sees faq already in visited (pending drops to 1), and once faq finishes with no new unseen links, pending drops to 0 and both workers exit cleanly.

Complexity

  • Network fetch calls — V calls on success (<= V * max_attempts with retries): each of the V distinct reachable URLs is inserted into visited and appended to frontier once, and one owning worker runs at most max_attempts tries for it.
  • Graph bookkeeping time — O(V + E): for V reachable pages and E total outgoing links across those pages, each page is popped from the deque once in O(1) time and each outgoing link performs one O(1) hash-set lookup in visited under the lock, while slow network I/O runs lock-free.
  • Memory — O(V + W): visited stores at most V URL strings, frontier never holds duplicates so len(frontier) <= V, and the thread pool allocates W = max_workers worker threads.
  • Wall-clock latency — at least max(V * L / W, (D + 1) * L): with per-page latency L, W workers, and maximum shortest-path hop depth D, W workers complete at most W fetches per L seconds, and discovering depth-D pages requires D + 1 sequential hops regardless of how large W is.

Edge cases

  • Single-page web (seed_url returns []): seed_url is fetched once, finish adds zero links and decrements pending from 1 to 0, waking all idle workers to exit immediately.
  • Self-links (home -> home), cycles (guide -> home, faq -> guide), and diamond paths (guide -> faq, api -> faq): reserving on discovery ensures visited already contains home and faq before a second path can queue them.
  • Empty frontier while a slow page is in flight: pending remains above 0, keeping idle workers asleep inside cond.wait() so full W-way parallelism resumes as soon as the slow page publishes its child links.
  • Permanent failure on one branch: the owning worker tries url max_attempts times, records url in failed, and lets the rest of the reachable graph finish before crawl raises CrawlIncompleteError (honestly noting that subtrees behind failed could not be discovered).
  • Cancellation before start or mid-crawl: if cancel is already set, zero fetches start and [seed_url] is reported in not_attempted; if set mid-crawl, running calls finish, pending retries are skipped (recording that page in failed), and queued URLs come back in not_attempted.
  • BaseException inside fetch_and_parse (such as SystemExit): except BaseException records the crash reason on url and finally: state.finish(...) still decrements pending and calls notify_all(), so surviving workers finish the crawl instead of hanging forever.
  • Invalid configuration (max_workers < 1 or max_attempts < 1): rejected immediately with ValueError rather than starting zero threads and silently doing nothing.

Common mistakes

  • Adding to visited after fetch_and_parse instead of at discovery: allows duplicate URLs into frontier and causes concurrent workers to fetch shared child pages multiple times.
  • Checking visited and inserting without a lock: two workers can pass link not in visited simultaneously, violating the single-fetch guarantee.
  • Holding self.cond across fetch_and_parse(url): turns a multithreaded crawler back into a single-file sequential crawler because nobody else can enter take() or finish() during a network call.
  • Terminating when not frontier: exits prematurely whenever all currently discovered work is in flight inside workers.
  • Decrementing pending before adding newly discovered children: lets pending hit 0 for an instant during finish(), waking another worker to exit early.
  • Using a bounded blocking queue.Queue(maxsize=C) shared by worker-producers: risks a full-queue deadlock when all W workers block inside put().
  • Swallowing or leaking worker death without finally: if a worker crashes before decrementing pending, pending never reaches 0 and worker.join() hangs forever.
  • Returning None after failures or cancellation: misleads a caller of a void method into believing every reachable page was visited.

Alternative approaches

  • queue.Queue with task_done() and join(): Python's standard Queue maintains an internal unfinished_tasks counter identical to pending (put() increments it, task_done() decrements it). Enqueue unseen children before calling task_done() for the parent, and push W None sentinel values once queue.join() unblocks.
  • concurrent.futures.ThreadPoolExecutor: submit one future per newly reserved URL and loop over wait(active_futures, return_when=FIRST_COMPLETED) on the coordinator thread, harvesting returned link lists and submitting unseen URLs without manual Condition code.
  • asyncio with asyncio.Semaphore(W): when an async HTTP client is available, coroutines scale to thousands of concurrent sockets on one OS thread; because cooperative multitasking only yields at await, checking and updating visited synchronously has no race condition.
  • Sharded distributed crawler: at multi-machine scale, partition URLs by hash(hostname) across worker nodes so each node owns the authoritative visited store and politeness rate limiter for its assigned hosts.

Follow-up questions

  • Why does marking pages as seen only upon download completion fail in single-threaded and multi-threaded crawlers? Every parent page that links to faq while faq is still queued or downloading will push another copy of faq onto frontier, bloating queue memory from O(V) to O(E). In a single thread you could patch over duplicate fetches by checking visited a second time right after popleft(), though you still pay the O(E) queue memory penalty. With multiple threads, even a pop-time check fails: while Worker 1 is still downloading faq (faq is not yet in visited), Worker 2 pops the second copy of faq, sees faq still absent from visited, and downloads faq a second time.
  • Why can a fixed-capacity blocking frontier freeze the entire worker pool when worker threads both pop pages and push discovered links? Suppose queue capacity is C = 4 and all W = 2 workers pop a page when 4 other URLs remain in the queue (4/4 full). Both workers finish their downloads, discover child links, and call blocking queue.put(child)—both threads now sleep waiting for a free queue slot, yet those same two threads are the only consumers that could ever call queue.get() to free a slot. Avoid this by bounding active network calls via max_workers (or a semaphore) while keeping frontier link insertion non-blocking (an in-memory deque bounded naturally by len(visited) <= V, or spilling overflow chunks to disk).
  • How would you design crash recovery so an interrupted crawl resumes safely when an in-progress network request has an unknown outcome? Store each URL in a durable table keyed by url with status (queued, in_flight, succeeded, failed) and attempt_count, incrementing attempt_count and committing status = "in_flight" before sending the network request. When a fetch finishes, write the page output, newly discovered queued child rows (INSERT ... ON CONFLICT DO NOTHING), and status = "succeeded" in a single atomic transaction. After a crash, any row still marked in_flight might or might not have reached the remote server, so reset in_flight rows with attempt_count < max_attempts back to queued (at-least-once network attempts) and store page outputs via upsert (overwrite-by-URL) so the final saved dataset achieves effectively-once results.

Follow-up questions

Similar questions

More MongoDB interview questions

All 16 MongoDB questions →