Thread-Pooled Link Crawler with Depth Limit and Dedup
Trees & GraphsModel answerLast updated
Implement a thread-safe crawler that explores links from a seed page to a given depth, never fetches a URL twice, and caps the number of simultaneous fetches.
Parallel Link Crawler
You are building a crawler that starts at one seed URL, downloads the page, extracts the links on it, and keeps following those links, but only up to a configurable number of hops from the seed. Many downloads should run at once, yet the number running simultaneously must stay under a fixed cap.
Implement this class:
class WebCrawler:
def __init__(self, max_depth, max_threads):
"""Configure the crawler."""
def crawl(self, start_url):
"""Crawl from start_url and return the set of URLs found."""
def _fetch_page(self, url):
"""Simulated download. Returns a list of URLs linked from `url`."""
Requirements
- No URL may be fetched more than once, even when pages link to each other in cycles or several threads discover the same link at the same moment.
- Slow or failing downloads must not stall or crash the whole crawl.
- At most
max_threadsdownloads may be in flight at any time. - All shared state must be safe under concurrent access.
Constraints
max_depthis a positive integer; the seed is at depth 0.1 <= max_threads <= 20.- You may use a thread pool, a semaphore, or any equivalent mechanism to limit concurrency.
Examples
Example 1. start_url = "http://a.com", max_depth = 1. The result contains the seed and every URL linked directly from it.
Example 2. start_url = "http://a.com", max_threads = 2. Several pages are fetched in parallel, and no page is fetched twice.
State clearly in your answer how you define depth and which pages you actually download.
Hints
Hint 1
Treat the web as a graph and the crawl as a breadth-first traversal. The only unusual part is that discovering a node's neighbours is slow I/O.
Hint 2
A check followed by an insert on a shared set is a race. Make 'has anyone seen this URL? if not, mark it' a single atomic step, and mark URLs when they are discovered rather than after they are fetched.
Hint 3
Keep the frontier in one coordinating thread and let workers only download. Wait on the in-flight futures with FIRST_COMPLETED, and track each future's depth so you know when to stop expanding.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A crawl is a breadth-first traversal over a graph whose edges are expensive to discover. Each _fetch_page call is dominated by network wait time, so threads give a real speedup even in Python: the GIL is released while a thread blocks on I/O.
The design has three pieces.
- Bounded worker pool. A
ThreadPoolExecutor(max_workers=max_threads)guarantees no more thanmax_threadsfetches run at once. Extra submissions wait in the executor's internal queue, so no separate semaphore is needed. - Claim on discovery. A URL goes into the visited set the moment it is found, and the "is it present? if not, add it" step happens under a single lock. Only the caller whose claim succeeds may schedule a fetch. This removes the check-then-act race where two threads both see "unvisited" and both download the page.
- Depth stored per task. A dict maps each pending future to the depth of its URL. Links on a depth-
dpage have depthd + 1.
One coordinator thread (the caller of crawl) loops on wait(pending, FIRST_COMPLETED). As soon as any download finishes, it processes that page's links and schedules new work. A slow page therefore never blocks a whole level. Workers only do I/O; the coordinator owns the frontier.
Depth semantics
Say these out loud before coding:
- The seed has depth 0.
- Every URL at depth
<= max_depthbelongs in the result. - A page is downloaded only if its depth is
< max_depth, because links found on a page at depthmax_depthwould be too deep anyway. - With
max_depth = 1the result is the seed plus all links on the seed page. Those linked pages are recorded but not downloaded.
Code
import threading
import time
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from urllib.parse import urldefrag
class WebCrawler:
def __init__(self, max_depth, max_threads, graph=None, latency=0.0):
# graph (url -> list of urls) and latency are simulation hooks
self.max_depth = max_depth
self.max_threads = max_threads
self._graph = graph or {}
self._latency = latency
self._visited = set()
self._lock = threading.Lock()
@staticmethod
def _normalize(url):
return urldefrag(url)[0] # drop #fragment
def _claim(self, url):
with self._lock: # atomic check-and-insert
if url in self._visited:
return False
self._visited.add(url)
return True
def _fetch_page(self, url):
if self._latency:
time.sleep(self._latency) # stands in for network wait
return list(self._graph.get(url, []))
def _safe_fetch(self, url):
try:
return self._fetch_page(url)
except Exception:
return [] # failed page = leaf
def crawl(self, start_url):
with self._lock:
self._visited = set()
seed = self._normalize(start_url)
self._claim(seed)
if self.max_depth <= 0:
return {seed}
with ThreadPoolExecutor(max_workers=self.max_threads) as pool:
pending = {pool.submit(self._safe_fetch, seed): 0}
while pending:
done, _ = wait(pending, return_when=FIRST_COMPLETED)
for fut in done:
depth = pending.pop(fut)
for raw in fut.result():
link = self._normalize(raw)
if self._claim(link) and depth + 1 < self.max_depth:
pending[pool.submit(self._safe_fetch, link)] = depth + 1
with self._lock:
return set(self._visited)
With graph = {a: [b, c], b: [d]}, max_depth = 1 returns {a, b, c} and max_depth = 2 returns {a, b, c, d}.
Why it is correct
- No duplicate fetches. A URL is scheduled only if its claim succeeded, and a claim can succeed once per URL.
- Depth bound. Scheduling requires
depth + 1 < max_depth, so nothing deeper than the limit is downloaded. - Termination. Each URL is claimed once, so total submissions are bounded by the number of distinct URLs. Futures are removed from
pendingwhen processed, and the loop ends when it is empty. - Concurrency cap. The executor enforces it structurally.
- Failure tolerance.
_safe_fetchconverts any exception into "no links". A real fetcher should also set a request timeout so a hung socket cannot occupy a worker forever.
Only the coordinator calls _claim here, so the lock is uncontended. It stays because the common alternative, where workers claim and enqueue their own children, depends on it. Keeping it makes the class safe under refactoring.
Complexity
Let V be the distinct URLs within range, E the links seen, L the per-fetch latency, and T the thread count.
- CPU work: O(V + E), one average O(1) set operation per link.
- Wall-clock time: about max(depth * L, V * L / T). You cannot beat the chain of dependent hops, and you cannot exceed T parallel fetches.
- Space: O(V) for the visited set plus O(T + frontier) for pending futures.
Edge cases
- Cycles and self-links are absorbed by the visited set.
- Duplicate links on one page are claimed once.
- URLs differing only by fragment are normalized to one. In production also lowercase the host, resolve relative links, and canonicalize trailing slashes.
- Timeouts and parse errors are treated as leaf pages.
max_depth = 0returns only the seed, defensively.- Calling
crawlagain resets state, so an instance is reusable.
Trade-offs and common mistakes
- Check-then-act race: testing
in visitedand adding later, without one lock around both. - Marking visited after the fetch, which lets two workers fetch the same page while the first is still in flight.
- Bad termination: calling
queue.join()while workers can still add items, or returning while futures are still running. - Off-by-one depth: fetching pages at depth
max_depth, or failing to include the boundary URLs in the result. - Unbounded thread creation (one thread per link) instead of a pool.
- Threads vs. asyncio: an event loop with a semaphore scales to thousands of connections more cheaply, but threads are simpler when the fetch library is blocking.
Follow-ups
- Politeness: per-domain rate limits and robots.txt, using a per-host token bucket or one queue per host.
- Distributed crawl: a durable queue partitioned by domain hash, so each domain is owned by one shard, with a shared store (or Bloom filter plus persistent set) for visited URLs. A Bloom filter risks occasionally skipping a new URL but never double-fetches.
- Retries: exponential backoff with a per-URL attempt cap, and a dead-letter list.
- Memory: for very large crawls, spill the frontier to disk and store hashed URLs instead of full strings.