Same-Host Link Crawler: Sequential and Concurrent Versions
Trees & GraphsModel answerLast updated
Crawl every page reachable from a seed URL on the same host, ignoring URL fragments, first with one thread and then with a thread-safe parallel design.
Crawl a Site from a Seed Page
You are given a seed address startUrl (for example "http://news.example.com/a/index.html") and an object HtmlParser exposing one method, getUrls(url). That method fetches the page at url and returns every absolute URL linked from it. Treat it as a black box that may be slow, like a network call.
Starting from startUrl, follow links and collect every distinct page you can reach, obeying these rules.
Rules
- Stay on one host. Only visit pages whose hostname equals the hostname of
startUrl. The hostname is the text after the scheme (http://orhttps://) up to the next/. - Drop fragments. A URL may end with a fragment such as
#section2. Remove the#and everything after it before you check whether a page was seen, and before you put it in the result. Sohttp://a.com/x#p1andhttp://a.com/x#p2are the same page,http://a.com/x. - Nothing else is normalized. Do not touch trailing slashes, default ports, letter case, query-parameter order, and so on. Only the fragment is removed.
Part A: Single thread
Write a crawler that runs on one thread and returns all visited URLs (fragments removed) that satisfy the host rule.
Part B: Multiple threads
Now speed it up with several threads.
- Many threads may call
getUrlsat the same time. - The solution must be thread-safe and must never fetch the same cleaned URL twice.
Output
All distinct cleaned URLs reachable from startUrl on the same host (order does not matter).
Notes
- The link graph can contain cycles and self-links.
- Every URL returned by
getUrlsis absolute.
Explain your approach, state the complexity, and give code for both parts. Be ready to discuss how you would terminate the concurrent version and what could go wrong.
Hints
Hint 1
Model pages as graph nodes and links as directed edges. Cycles mean you need a visited set, and a queue (BFS) or stack (DFS) for the frontier.
Hint 2
Clean the URL first: cut at the first '#'. Only then extract the hostname (otherwise a URL like 'http://a.com#top' gives a wrong host), check membership in visited, and store it.
Hint 3
Add a URL to visited at the moment you schedule it, not when you later pop it. That is what guarantees one fetch per cleaned URL.
Hint 4
For threads, getUrls is the slow part. Let workers only fetch and return links, while a single coordinator thread owns visited and decides what to submit next. That removes the need for locks and makes termination simply 'no pending fetches'.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is graph traversal. Pages are nodes, links are directed edges, and cycles are possible, so a visited set is mandatory. Three details decide correctness:
- Clean first. Cut the URL at the first
#before doing anything else: host check, dedup, fetch, output. Otherwisex#aandx#bcount as two pages, and a URL likehttp://a.com#topyields the hostnamea.com#top. - Literal hostname rule. Take the text between
://and the next/. Do not lowercase it, drop ports, or use a library that normalizes. Under the stated rulesa.com:8080anda.comare different hosts, andblog.a.comdiffers froma.com. A different scheme with the same hostname is still crawlable, buthttp://a.com/xandhttps://a.com/xremain distinct URLs. - Mark visited on enqueue. Insert into
visitedwhen you schedule the URL, not when you dequeue it. This prevents the same URL being queued (or fetched) twice.
Part A: single thread (BFS)
Start with the cleaned seed in both visited and the queue. Pop a URL, call getUrls, and for each link: clean it, skip it if it is already visited or has a different host, otherwise mark it visited and enqueue it. DFS works equally well.
Part B: multi-threaded
Since getUrls is IO-bound, run it in a thread pool. The simplest safe design is a coordinator pattern:
- Workers only call
getUrls(url)and return the list of links. They touch no shared state. - One coordinator thread waits for any future to finish, cleans and filters the links, updates
visited, and submits new fetches. - Because only the coordinator reads or writes
visitedand the pending set, there are no data races and no locks. - Termination is simply "the pending set is empty".
Alternative: shared-state workers
Workers pull from a queue.Queue and update visited under a threading.Lock. The check and the insert must be in the same critical section. Doing if u not in visited and then visited.add(u) separately is the classic race that causes duplicate fetches. Termination is the harder part: use queue.join() with task_done(), or an in-flight counter, so workers can tell "queue empty for now" from "crawl finished". The coordinator version is shorter and easier to reason about.
Code (Python)
from collections import deque
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from typing import List
def strip_fragment(url: str) -> str:
return url.split('#', 1)[0]
def get_hostname(url: str) -> str:
rest = url.split('://', 1)[1] if '://' in url else url
return rest.split('/', 1)[0]
def crawl(startUrl: str, htmlParser) -> List[str]:
start = strip_fragment(startUrl)
host = get_hostname(start)
visited = {start}
queue = deque([start])
while queue:
url = queue.popleft()
try:
links = htmlParser.getUrls(url)
except Exception:
links = []
for link in links:
clean = strip_fragment(link)
if clean not in visited and get_hostname(clean) == host:
visited.add(clean)
queue.append(clean)
return list(visited)
def crawl_concurrent(startUrl: str, htmlParser, max_workers: int = 16) -> List[str]:
start = strip_fragment(startUrl)
host = get_hostname(start)
visited = {start} # only the coordinator touches this
with ThreadPoolExecutor(max_workers=max_workers) as pool:
pending = {pool.submit(htmlParser.getUrls, start)}
while pending:
done, pending = wait(pending, return_when=FIRST_COMPLETED)
for fut in done:
try:
links = fut.result()
except Exception:
continue
for link in links:
clean = strip_fragment(link)
if clean not in visited and get_hostname(clean) == host:
visited.add(clean) # claim before scheduling
pending.add(pool.submit(htmlParser.getUrls, clean))
return list(visited)
Why it is correct
- Completeness: Every reachable same-host page is connected to the seed by a chain of same-host pages (we never expand off-host pages). By induction on path length, BFS reaches each one.
- No duplicates: A cleaned URL enters
visitedexactly when it is scheduled, so any later sighting, even with a different fragment, is skipped. - Termination: At most one fetch per distinct cleaned URL, and there are finitely many. The loop ends when the queue or pending set is empty.
Complexity
Let N be the number of distinct same-host pages, E the total links returned, and L the maximum URL length.
- CPU time: O((N + E) · L) for stripping, hostname extraction and hashing, plus N calls to
getUrls. - Space: O(N · L) for
visitedand the frontier. - Wall-clock (Part B): with W workers and fetch latency T, roughly max(depth · T, N · T / W) instead of N · T. The GIL is not a problem because threads release it while blocked on IO.
Edge cases
- The seed itself has a fragment: clean it before computing the host and before adding it to the result.
- No path, e.g.
http://a.com#top: strip the fragment before extracting the host. - Self-loops, cycles, empty link lists: handled by
visited. getUrlsraises: treat the page as visited with no links so one failure does not abort the crawl.
Common mistakes
- Deduplicating on the raw URL and stripping the fragment only at output time.
- Marking visited on dequeue, which lets duplicates pile up in the queue (or be fetched twice in the threaded version).
- Using a URL library that lowercases the host or removes ports, contradicting the "no other normalization" rule.
- Unsynchronized check-then-add on a shared set.
- Workers exiting as soon as the queue is momentarily empty while other workers are still producing links.
Production considerations (brief)
Per-host rate limiting and politeness, bounded frontier and pool size, timeouts and retries on getUrls, and a distributed visited store (or hash-partitioning of URLs across crawler nodes) when scaling out.