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]): anExceptionsubclass raised whenevercrawlcannot 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. Invokefetch_and_parse(url)once for every distinct URL reachable fromseed_url(includingseed_urlitself), 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:- Configuration validation: Raise
ValueErrorimmediately ifmax_workers < 1ormax_attempts < 1. - Bounded parallelism: Run at most
max_workersconcurrent calls tofetch_and_parseat any moment, executing network calls outside shared locks so independent pages download in parallel. - 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.
- Retries and failure reporting: When fetches succeed, call
fetch_and_parseonce per distinct reachable URL and returnNone. When a call raises anException, retry that URL up tomax_attemptstotal calls; if every attempt raises, record{url: error_message}infailed, finish crawling all other reachable branches, and raiseCrawlIncompleteError(failed, not_attempted). - Worker crash resilience: Even if a non-
ExceptionBaseException(such asSystemExit) escapesfetch_and_parse, record that URL infailedand update work accounting so surviving workers never block forever. - Cooperative cancellation: Once
cancelis 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 infailed), wait for already-running fetches to finish, and raiseCrawlIncompleteError(failed, not_attempted).
- Configuration validation: Raise
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_sequentialandcrawlmust callfetch_and_parseonce per distinct reachable URL. max_workersandmax_attemptsare integers; raiseValueErrorwhenever either is< 1.- Peak concurrent calls to
fetch_and_parsemust never exceedmax_workers, and zero fetches may remain running aftercrawlreturns or raises.
Step-by-step walkthrough
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 implementcrawl(seed_url, ...)with no return value (None), visiting every reachable page starting fromseed_url.Because the function returns nothing, its contract is defined entirely by which calls to
fetch_and_parsehappen 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_parseis called exactly once forseed_urland 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
#fragmentanchors or normalizing trailing slashes happens right before checkingvisited, 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
crawlraisesCrawlIncompleteErrorlisting 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_attemptstotal calls when attempts fail).
- Baseline success contract: on a finite static web graph where every fetch succeeds,
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 fromseed_url. -visited: a hash set of every URL that has already been reserved, whether it has been fetched or is still sitting infrontier.The single most important rule in Part 1 is when a URL enters
visited: reserve it at discovery time (right before appending tofrontier), 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=[], returnfrom 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):homeandguideare already invisitedbefore any link back to them is inspected, so neither is ever queued again. - Multiple parents (guide -> faqandapi -> faq): the first parent to inspectfaqadds it tovisitedandfrontier; the second parent seesfaq in visitedand skips it. - Termination and complexity: in a single thread, nothing is running in the background, sofrontierbecoming empty guarantees allVreachable pages have been fetched. Graph bookkeeping performsO(V + E)hash-set and deque operations acrossVreachable pages andEtotal outgoing links usingO(V)memory—completely separate from network download and HTML parsing cost.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 visitsV = 10,000pages where eachfetch_and_parsespends200 mswaiting on HTTP and2 msparsing HTML:Sequential wall time: 10,000 * 0.202 s = 2,020 s (~34 minutes), CPU busy < 1% of the timeBecause independent URLs already in
frontierdo not depend on one another,Wworker threads can overlap those network waits. Regardless of scheduler design, wall-clock time obeys two fundamental lower bounds (for fetch latencyLand deepest shortest-path hop countDfromseed_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 = 50workers and depthD = 6, network time drops from34 minutestowardmax(10,000 * 0.2 / 50, 7 * 0.2) = 40 secondswhenever the frontier stays wide enough to feed all50workers. (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, though10,000 * 2 ms = 20 sof 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.Part 2: Atomic reservation and tracking in-flight work
Adding
Wworker threads breaks naive BFS in two places:- 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 (finishingapi) both checkif "faq" not in visited:at the same instant before either inserts"faq", both pass the check and fetch"faq"twice. Checkingvisited, adding"faq", and appending tofrontiermust happen atomically inside a mutex (lock)—while the slowfetch_and_parse(url)call MUST happen outside the lock so workers actually run in parallel. - Premature termination when the frontier is temporarily empty: right after Worker 1 pops
seed_url,frontieris empty ([]), yet Worker 1 is still downloadingseed_urland is about to discover dozens of links! If Worker 2 sees an emptyfrontierand exits, parallelism collapses to 1 thread; ifcrawlreturns on an emptyfrontier, 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 incrementpendingfor newly discovered child links before decrementingpendingfor the finished parent page, sopendingnever transiently hits0. A condition variable (threading.Condition) pairs the lock withwait()andnotify_all()so idle workers sleep without burning CPU. Waiting always sits inside awhile Trueloop 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()- Duplicate discovery (race condition): a race condition occurs when two threads read and modify shared state concurrently. If Worker 1 (finishing
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
dequewith a boundedqueue.Queue(maxsize=C)and calling blockingput()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_workersthreads (<= Wconcurrent network calls). - Publishing discovered links is non-blocking intoself.frontier. Even without an artificial cap onself.frontier, memory is already bounded byO(V)because each distinct reachable URL is added toself.frontierat most once when reserved inself.visited(len(frontier) <= len(visited) <= V). At web scale whereVexceeds RAM, keep link publishing non-blocking by spilling frontier segments andvisitedkeys to disk or a database rather than blocking active workers.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 popsurlowns all1..max_attemptstries in a plain local loop. Never re-push a failing URL back ontofrontierfrom 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, checkcancel.is_set()before starting any retry. - Unbreakable
pendingaccounting (_worker): if an unexpected exception escapesfetch_and_parseand kills a worker without callingstate.finish(...),pendingstays stuck above0forever and hangs every surviving worker. CatchingExceptionhandles ordinary errors per attempt, while wrapping the fetch inexcept BaseException+finally: state.finish(...)guarantees that even a fatalSystemExitrecordsurlinfailed, decrementspending, 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))- Single-owner retries (
Trace two workers and define the production failure contract
Trace
W = 2workers on Example 1 (home -> [home, guide, api],guide -> [faq, home],api -> [faq, changelog],faq -> [guide],changelog -> [], plus unreachableorphan -> [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 NoneEvery reachable URL (
home, guide, api, faq, changelog) is fetched once,orphanis never touched, andpending >= 1keeps 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, ornot_attempted). - Backoff and per-attempt timeouts: in production, retry only transient faults (network timeouts, HTTP429/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 forurland 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 (persistin_flightto a database before sending, and re-queuein_flightrows on restart), paired with effectively-once processing: save parsed page data, child URL reservations, andstate = "succeeded"in a single atomic database transaction keyed byurl(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.Put the full crawler together
Here is the complete
solution.pycombining sequential BFS, bounded concurrent traversal, single-owner retries, cancellation, andCrawlIncompleteError: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 —
Vcalls on success (<= V * max_attemptswith retries): each of theVdistinct reachable URLs is inserted intovisitedand appended tofrontieronce, and one owning worker runs at mostmax_attemptstries for it. - Graph bookkeeping time —
O(V + E): forVreachable pages andEtotal outgoing links across those pages, each page is popped from thedequeonce inO(1)time and each outgoing link performs oneO(1)hash-set lookup invisitedunder the lock, while slow network I/O runs lock-free. - Memory —
O(V + W):visitedstores at mostVURL strings,frontiernever holds duplicates solen(frontier) <= V, and the thread pool allocatesW = max_workersworker threads. - Wall-clock latency — at least
max(V * L / W, (D + 1) * L): with per-page latencyL,Wworkers, and maximum shortest-path hop depthD,Wworkers complete at mostWfetches perLseconds, and discovering depth-Dpages requiresD + 1sequential hops regardless of how largeWis.
Edge cases
- Single-page web (
seed_urlreturns[]):seed_urlis fetched once,finishadds zero links and decrementspendingfrom1to0, 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 ensuresvisitedalready containshomeandfaqbefore a second path can queue them. - Empty frontier while a slow page is in flight:
pendingremains above0, keeping idle workers asleep insidecond.wait()so fullW-way parallelism resumes as soon as the slow page publishes its child links. - Permanent failure on one branch: the owning worker tries
urlmax_attemptstimes, recordsurlinfailed, and lets the rest of the reachable graph finish beforecrawlraisesCrawlIncompleteError(honestly noting that subtrees behindfailedcould not be discovered). - Cancellation before start or mid-crawl: if
cancelis already set, zero fetches start and[seed_url]is reported innot_attempted; if set mid-crawl, running calls finish, pending retries are skipped (recording that page infailed), and queued URLs come back innot_attempted. BaseExceptioninsidefetch_and_parse(such asSystemExit):except BaseExceptionrecords the crash reason onurlandfinally: state.finish(...)still decrementspendingand callsnotify_all(), so surviving workers finish the crawl instead of hanging forever.- Invalid configuration (
max_workers < 1ormax_attempts < 1): rejected immediately withValueErrorrather than starting zero threads and silently doing nothing.
Common mistakes
- Adding to
visitedafterfetch_and_parseinstead of at discovery: allows duplicate URLs intofrontierand causes concurrent workers to fetch shared child pages multiple times. - Checking
visitedand inserting without a lock: two workers can passlink not in visitedsimultaneously, violating the single-fetch guarantee. - Holding
self.condacrossfetch_and_parse(url): turns a multithreaded crawler back into a single-file sequential crawler because nobody else can entertake()orfinish()during a network call. - Terminating when
not frontier: exits prematurely whenever all currently discovered work is in flight inside workers. - Decrementing
pendingbefore adding newly discovered children: letspendinghit0for an instant duringfinish(), waking another worker to exit early. - Using a bounded blocking
queue.Queue(maxsize=C)shared by worker-producers: risks a full-queue deadlock when allWworkers block insideput(). - Swallowing or leaking worker death without
finally: if a worker crashes before decrementingpending,pendingnever reaches0andworker.join()hangs forever. - Returning
Noneafter failures or cancellation: misleads a caller of avoidmethod into believing every reachable page was visited.
Alternative approaches
queue.Queuewithtask_done()andjoin(): Python's standardQueuemaintains an internalunfinished_taskscounter identical topending(put()increments it,task_done()decrements it). Enqueue unseen children before callingtask_done()for the parent, and pushWNonesentinel values oncequeue.join()unblocks.concurrent.futures.ThreadPoolExecutor: submit one future per newly reserved URL and loop overwait(active_futures, return_when=FIRST_COMPLETED)on the coordinator thread, harvesting returned link lists and submitting unseen URLs without manualConditioncode.asynciowithasyncio.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 atawait, checking and updatingvisitedsynchronously has no race condition.- Sharded distributed crawler: at multi-machine scale, partition URLs by
hash(hostname)across worker nodes so each node owns the authoritativevisitedstore 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
faqwhilefaqis still queued or downloading will push another copy offaqontofrontier, bloating queue memory fromO(V)toO(E). In a single thread you could patch over duplicate fetches by checkingvisiteda second time right afterpopleft(), though you still pay theO(E)queue memory penalty. With multiple threads, even a pop-time check fails: while Worker 1 is still downloadingfaq(faqis not yet invisited), Worker 2 pops the second copy offaq, seesfaqstill absent fromvisited, and downloadsfaqa 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 = 4and allW = 2workers pop a page when4other URLs remain in the queue (4/4full). Both workers finish their downloads, discover child links, and call blockingqueue.put(child)—both threads now sleep waiting for a free queue slot, yet those same two threads are the only consumers that could ever callqueue.get()to free a slot. Avoid this by bounding active network calls viamax_workers(or a semaphore) while keeping frontier link insertion non-blocking (an in-memorydequebounded naturally bylen(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
urlwithstatus(queued,in_flight,succeeded,failed) andattempt_count, incrementingattempt_countand committingstatus = "in_flight"before sending the network request. When a fetch finishes, write the page output, newly discoveredqueuedchild rows (INSERT ... ON CONFLICT DO NOTHING), andstatus = "succeeded"in a single atomic transaction. After a crash, any row still markedin_flightmight or might not have reached the remote server, so resetin_flightrows withattempt_count < max_attemptsback toqueued(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
- Why does marking pages as seen only upon download completion fail in single-threaded and multi-threaded crawlers?
- Why can a fixed-capacity blocking frontier freeze the entire worker pool when worker threads both pop pages and push discovered links?
- How would you design crash recovery so an interrupted crawl resumes safely when an in-progress network request has an unknown outcome?
Similar questions
- Diagnosing Tail-Latency Spikes in a Hybrid Network Server
- Document Filter Expression Tree Evaluator
- Modern Python Syntax, Framework Trade-Offs, and String Internals
- Bounded Multi-Threaded Web Crawler with Host Politeness
- Constant-Space Union Iterator for Sorted Streams
- Thread-Safe Per-Key Rolling-Window Rate Limiter
More MongoDB interview questions
- Navigating the Senior Engineer Recruiter Screen Medium
- Senior Behavioral Loop: Ownership, Collaboration, and Project Leadership Medium
- Retail Equity Brokerage with Streaming Quotes and Order Execution Medium Pro
- Cloud Database Fleet Metrics Collection and Time-Series System Medium Pro
- Document Filter Expression Tree Evaluator Medium Pro
- Constant-Space Union Iterator for Sorted Streams Medium Pro
- Thread-Safe Per-Key Rolling-Window Rate Limiter Medium Pro
- Rate-Limit Duplicate Log Lines Over a 10-Second Cooldown Medium Pro
- Diagnosing Tail-Latency Spikes in a Hybrid Network Server Medium Pro
- Lazy Sorted Union Iterator Medium Pro