KatInterview

Crawl One Site: Sequential Traversal, Then a Parallel Version

Trees & GraphsModel answer
MediumModel answerTrees & Graphsweb-crawlerbfsconcurrency

Last 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#top and http://news.example.org/a are 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.