12A web crawler, then make it concurrent
12 A web crawler, then make it concurrent
Anthropic candidates report a crawler with threads or processes, sometimes with a design discussion on top (3 sources). A staff candidate reports the order this problem follows: crawl a site first, then make it multithreaded (1 report). This is practice in that shape, not a leaked question.
Set a 55-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/12_web_crawler -k level1. Earlier levels must keep passing.
fetch(url) returns the list of links on that page, each a full URL like http://example.com/a. It's
slow, because it waits on the network, and it can raise.
Level 1. crawl(start_url, fetch) returns the set of every URL on the same hostname as
start_url that is reachable from it, start_url included. Drop #fragments before you compare
URLs, so /b#top is the page /b, and return them without it. That goes for start_url too. Never fetch a URL on another host, subdomains included. Fetch
each URL exactly once. A page whose fetch raises still counts as reached: it just has no links, and
one bad page must not stop the crawl.
Level 2. crawl(start_url, fetch, max_workers=8) runs fetches at the same time, with at most
max_workers in flight. Every level 1 rule still holds. Decide who owns the visited set (one
coordinating thread, or a lock), and how you know you're done when work spawns more work.
Level 3. fetch raises TimeoutError when a page might load on a second try. Any other
exception means the page is broken, like a 404, so never fetch it again. Add two parameters:
crawl(start_url, fetch, max_workers=8, retries=2, backoff=0.1). A page that times out gets up to
retries more tries. Wait backoff seconds before the first retry, and twice as long before each
retry after it: with backoff=0.1, waits of 0.1, 0.2, 0.4. Don't wait before the first try or after the
last one. A page that still fails counts as reached, with no links.
Design follow-ups: what a sleeping retry costs the pool, politeness and rate limits per host, robots.txt, threads versus asyncio versus processes, and spreading the crawl over many machines (the URL frontier, sharding by host, dedup at scale).