Crawl One Site: Sequential Traversal, Then a Parallel Version
Trees & GraphsModel answerLast updated
Collect every page reachable from a seed URL on the same host, ignoring URL fragments and fetching each page once, first with one thread and then with safe concurrency.
You are building a small site crawler. You receive a seed URL and a fetcher object. Calling fetcher.links(url) downloads the page at url and returns a list of absolute URLs found on it. The call blocks, may be slow, and is the only way to discover links. (The method name is a stand-in for whatever interface you are given.)
Return all URLs reachable from the seed by following links, under these rules:
- Same host only. Only pages whose hostname equals the seed's hostname are fetched or returned. Links to other hosts are ignored.
- Fragments do not count. Remove everything from
#onward from every URL before comparing, storing or fetching it.http://news.example.org/a#topandhttp://news.example.org/aare the same page. - Fetch once. Each distinct page is fetched at most once, even if pages link to each other in cycles.
The order of the result does not matter. Expect test inputs with cross-host links, URLs that differ only by fragment, self-links and cycles.
Part 1. Implement the crawler with a single thread.
Part 2. Since links is slow, redesign the crawler to fetch many pages at the same time. Explain how the visited set stays correct when several threads find the same link simultaneously, and how the crawler decides it is done.
State any assumptions you make (for example: are scheme, port, case and query string part of a page's identity, and what happens when a fetch fails?). Give time and space complexity.
Hints
Hint 1
Treat pages as graph nodes and links as edges. A visited set keyed by the normalized URL (fragment removed) is what makes cycles terminate.
Hint 2
Use a real URL parser to drop the fragment and read the hostname instead of splitting strings by hand. Normalize before the visited check, not after.
Hint 3
For concurrency, the check 'have I seen this URL?' and the mark 'now I have' must be a single atomic step under a lock. For termination, track how many tasks are pending (submitted but not finished), not whether a queue looks empty.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I would state these up front and confirm them:
- Hostname comparison is case-insensitive. Scheme and port follow the parsed hostname; I compare
hostnameonly, sohttpandhttpsversions of the same host count as the same site. If the interviewer wants them separate, compare(scheme, netloc)instead. - Subdomains are different hostnames.
- Query strings are part of a page's identity. Only the fragment is removed.
- The seed is included in the result, after its fragment is stripped.
- A failed fetch is logged and the page is still reported as visited, but it contributes no links.
Part 1: Single-threaded
This is graph traversal with a normalization step. BFS or DFS both work. The key points:
- Normalize each URL (strip the fragment) before the visited check.
- Compare hostnames with a URL parser, not string splitting. Splitting on
/breaks on ports, userinfo and odd inputs. - Mark a URL visited when it is enqueued, not when it is popped, so it is never queued twice.
from urllib.parse import urldefrag, urlparse
from collections import deque
def normalize(url):
return urldefrag(url)[0]
def host(url):
return (urlparse(url).hostname or "").lower()
def crawl(seed, fetcher):
seed = normalize(seed)
target = host(seed)
visited = {seed}
queue = deque([seed])
while queue:
url = queue.popleft()
for link in fetcher.links(url):
link = normalize(link)
if host(link) == target and link not in visited:
visited.add(link)
queue.append(link)
return list(visited)
Complexity. With P distinct same-host pages and E total links, time is O(P + E) plus P fetches (the dominant real cost), and space is O(P) for the visited set and queue. Each page is fetched exactly once.
Part 2: Concurrent
Fetches are I/O-bound, so the single-threaded version spends nearly all its time waiting. Running many fetches in parallel gives close to a linear speedup until we hit the worker limit or the host's capacity.
The race
If two threads both discover link L at the same moment, this interleaving is possible:
T1: if L not in visited -> True
T2: if L not in visited -> True
T1: visited.add(L); fetch(L)
T2: visited.add(L); fetch(L) # duplicate fetch
Check-then-act is not atomic. The fix is to make test-and-insert one critical section:
with lock:
if link in visited:
is_new = False
else:
visited.add(link)
is_new = True
Only the thread that gets is_new == True schedules the fetch. Keep the lock held only for this tiny block, never across the network call, otherwise you serialize everything. (In CPython a single set.add is atomic, but the check plus add together is not, so an explicit lock is still needed.)
Termination
Do not use "the queue is empty" as the stop condition: a worker may have just taken the last item and be about to enqueue more, so other workers would exit early. Do not use a blocking get() with no exit either, or the crawler hangs.
The robust approach is to count outstanding work: increment a counter when a URL is scheduled, decrement when its fetch and link processing finish. The crawl is done exactly when the counter reaches zero. With queue.Queue this is task_done() and join().
import threading
from queue import Queue
from urllib.parse import urldefrag, urlparse
def crawl_concurrent(seed, fetcher, workers=16):
seed = urldefrag(seed)[0]
target = (urlparse(seed).hostname or "").lower()
visited = {seed}
lock = threading.Lock()
q = Queue()
q.put(seed)
def worker():
while True:
url = q.get()
if url is None:
q.task_done()
return
try:
links = fetcher.links(url)
except Exception:
links = [] # log and continue
for link in links:
link = urldefrag(link)[0]
if (urlparse(link).hostname or "").lower() != target:
continue
with lock:
if link in visited:
continue
visited.add(link)
q.put(link) # put BEFORE task_done of the parent
q.task_done()
threads = [threading.Thread(target=worker, daemon=True) for _ in range(workers)]
for t in threads: t.start()
q.join() # returns when pending count hits 0
for _ in threads: q.put(None)
for t in threads: t.join()
return list(visited)
The ordering matters: children are put before the parent calls task_done(), so the pending count never drops to zero while work is still being created.
An equivalent design uses ThreadPoolExecutor with a set of in-flight futures, looping until none remain.
Bounded concurrency and politeness
- A fixed worker pool (for example 8 to 32) bounds in-flight requests. Unbounded thread-per-URL can exhaust memory and hammer the host.
- Real crawlers also respect
robots.txt, add per-host rate limiting and use timeouts and retries with backoff. - Exceptions in a worker must not kill the thread, otherwise
join()hangs becausetask_done()is never called. Thetry/exceptplus unconditionaltask_done()handles this.
Why threads
The workload is I/O-bound, so the GIL is released during blocking network calls and threads work well and share the visited set cheaply. Processes would need inter-process sharing of the visited set and add overhead without helping. asyncio is a strong alternative that scales to thousands of concurrent fetches with less memory, if the fetcher is async.
Common mistakes
- Checking visited after popping rather than before enqueuing, causing duplicate fetches.
- Normalizing after the visited check, so
/aand/a#xare both fetched. - Holding the lock during the fetch, which removes all parallelism.
- Using an empty queue as the termination test.
- Letting one failed fetch crash a worker and hang the crawl.
- Comparing hosts by substring (for example
example.orgmatchingevil-example.org).
Complexity (concurrent). Total work is unchanged at O(P + E). Wall-clock time drops to roughly (P / workers) times the average fetch latency, bounded below by the longest dependency chain in the link graph.