KatInterview

Thread-Pooled Link Crawler with Depth Limit and Dedup

Trees & GraphsModel answer
MediumModel answerTrees & Graphsconcurrencybfsthread-pool

Last 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

  1. 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.
  2. Slow or failing downloads must not stall or crash the whole crawl.
  3. At most max_threads downloads may be in flight at any time.
  4. All shared state must be safe under concurrent access.

Constraints

  • max_depth is 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.