A multithreaded web crawler

95 min6 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Why threads make a crawler faster even with the GIL, and the kind of work where they don't, both measured
  • Breadth-first search with a frontier and a visited set, where a URL is marked when you find it, not when you fetch it
  • Cleaning links the way the tests check, with urljoin for relative links, no fragments and an exact host match
  • A thread pool with a fixed size, fed by one coordinating thread, and how that thread knows the crawl is over
  • Where a lock is needed, where one owner makes it unnecessary, and why one bad page must be a log line
  • The follow-ups: rate limits, robots.txt, retries, asyncio versus threads, and many machines
Part 1 of 6about 10 min
Why threads

Web crawler

Anthropic candidates report a web crawler question in coding rounds, written with threads or processes, sometimes with a design discussion on top (3 sources). One staff candidate describes the order it came in: crawl a site first, then make it multithreaded (1 report). It starts like this:

You get a start URL and a function fetch(url) that returns the links on that page. fetch is slow, because it waits on the network, and it can raise.

Write crawl(start_url, fetch). Return the set of every URL on the same hostname as start_url that you can reach from it, start_url included. Drop #fragments before you compare URLs. Never fetch a page on another host, subdomains included. Fetch each URL once. A page whose fetch raises still counts as reached, with no links.

For example, on a site of three pages:

  • fetch("http://example.com/") returns ["http://example.com/a", "http://example.com/b#top", "http://other.com/x"]
  • fetch("http://example.com/a") returns ["http://example.com/", "http://news.example.com/n"]
  • fetch("http://example.com/b") returns []

So crawl("http://example.com/", fetch) returns {"http://example.com/", "http://example.com/a", "http://example.com/b"}. The #top is dropped, and other.com and news.example.com are never fetched.

Once that works, the interviewer adds to it: fetch several pages at the same time, with a limit on how many are in flight, then retry a page that times out. The fetching isn't what they grade. They watch who keeps the set of pages already seen, how you know you're done when every page can add more work, and how you bound the work in flight.

You don't write it yet. The lesson first teaches what it needs, starting with why threads help a crawler at all. At the end you solve the whole problem, level by level, in an interview simulation with a 55-minute timer.

This lesson builds on the grid search: a crawl is a breadth-first search over links, with a seen-set from the hash maps lesson. The new idea here is threads, so that many slow fetches can wait at the same time.

A crawler spends its time waiting

Start with where a crawler's time goes.

One page at a time, almost all the time is waiting

Twelve fetches of 50 ms, nearly all of it waitingInteractive
runs Python, holds the GIL waits on the network, GIL let go
Total
600 ms
Speedup
1.0×
Peak in flight
1
One page at a time: 12 pages × 50 ms = 600 ms, and almost all of it is waiting.

A crawler fetches a page, reads the links on it, and then fetches those pages. Each fetch(url) sends a request and then sits idle until the server answers. Your own code does very little for each page.

The practice tests fake the network with time.sleep. Their bigger site has 41 pages, and every fetch sleeps 50 ms. That came to 58 ms on average on the machine these numbers come from.

Predict

41 bare sleeps of 50 ms took 2.36 s. How long did the whole crawl take, one page at a time?

Pick an answer above to see the rest

Threads let the waits overlap

A thread is a separate line of work inside one program, sharing the program's memory. Give each thread its own page, and the waits overlap.

Predict

12 fetches of 50 ms each take 600 ms on 1 worker. About how long on 4 workers?

Pick an answer above to see the rest
Predict

Make each fetch 50 ms of pure-Python arithmetic instead. 41 of them take 2.02 s alone. How long on 8 threads?

Pick an answer above to see the rest

Start every thread before you join any

A thread runs one function. Give threading.Thread the function as target and its arguments as args, start it, and wait for it to end with join:

import threading
import time


def nap(name, out):
    time.sleep(0.1)
    out.append(name)


out = []
t = threading.Thread(target=nap, args=("a", out))
t.start()
t.join()
print(out)
['a']

A join waits for its thread to finish, so joining each one right after starting it runs them one at a time again. Start them all first.

In the editor, fake_fetch(url, out) stands in for a fetch: it sleeps 0.1 s, like a wait on the network, and records the page in out. Set threads to one threading.Thread per URL, then start them all before you join any, so the eight waits overlap.

Part 1 done
Part 2 of 6about 13 min
Breadth first

Search the site breadth first

Set the threads aside for a moment. First, which pages does a crawl visit, and in what order?

A site is a graph, and a crawl walks it

The tests' small site, crawled breadth firstInteractive
//a/b#topother.com/x/cnews.example.com/n/broken/never
in the frontier fetched fetch failed another host
frontier, popleft takes the left end:/seen: 1
The start URL goes into the frontier and into seen, before anything is fetched.

A site is a graph: pages are the points, and links are the arrows between them. A crawl starts at one page and follows the arrows. Nothing ever finds /never, because the fetch of /broken fails. Here is the small site as code:

E = "http://example.com"
SITE: dict[str, list[str]] = {
    f"{E}/": [f"{E}/a", f"{E}/b#top", "http://other.com/x"],
    f"{E}/a": [f"{E}/", f"{E}/c", "http://news.example.com/n"],
    f"{E}/b": [f"{E}/a#part", f"{E}/broken"],
    f"{E}/c": [],
    f"{E}/broken": [f"{E}/never"],
}
calls: list[str] = []


def fetch(url: str) -> list[str]:
    """The page's links, as written. /broken raises, like a refused connection."""
    calls.append(url)
    if url == f"{E}/broken":
        raise ConnectionError("refused")
    return SITE.get(url, [])


print(fetch(f"{E}/b"))
Predict

What does fetch(f"{E}/b") return?

Pick one to see what it prints.
Pick an answer above to see the rest

Keep two things: a frontier and a visited set

Breadth first needs two pieces of state. Here is the whole crawl, one page at a time.

from collections import deque
from collections.abc import Callable
from urllib.parse import urldefrag, urljoin, urlparse


def crawl_one_at_a_time(
    start_url: str, fetch: Callable[[str], list[str]]
) -> set[str]:
    """Every reachable page on the start's host, one fetch at a time."""
    start = urldefrag(start_url).url
    host = urlparse(start).hostname
    seen, frontier = {start}, deque([start])
    while frontier:
        url = frontier.popleft()
        try:
            links = fetch(url)
        except Exception:
            continue
        for link in links:
            link = urldefrag(urljoin(url, link)).url
            if urlparse(link).hostname == host and link not in seen:
                seen.add(link)
                frontier.append(link)
    return seen


calls.clear()
found = crawl_one_at_a_time(f"{E}/", fetch)
print(*calls, sep="\n")
print(len(found), "pages found")
Predict

Which pages get fetched, and in what order?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

pop() instead of popleft(). What comes back?

Pick an answer above to see the rest

Mark a URL when you find it, not when you fetch it

One line in that loop decides how often a page gets fetched: the moment you mark it as seen. Take the 41-page site: the home page links p0 to p39, and each p links to the next one.

Predict

Mark each URL when you fetch it instead of when you find it. On the 41-page site, with one worker, how many fetches?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 11 min
Clean links

The visited set compares strings, and pages write the same link in many ways.

One link, cleaned in three stepsInteractive
the link = ../c#top. Found on the page http://example.com/docs/a.html.

The same page shows up under many spellings, and seen compares strings. So every link goes through the same three steps before you compare it to anything.

Resolve a relative link against its page

from urllib.parse import urljoin

page = "http://example.com/docs/a.html"
for href in ["b.html", "/b", "../c", "?page=2", "//other.com/x",
             "mailto:me@example.com"]:
    print(f"{href:23} {urljoin(page, href)}")
Predict

The page is http://example.com/docs/a.html. What does urljoin(page, "../c") give?

Pick one to see what it prints.
Pick an answer above to see the rest

Drop the fragment: /b#top is the page /b

The second step: the part after # names a place on a page, not a different page.

from urllib.parse import urldefrag

print(urldefrag("http://example.com/b#top"))
for link in ["http://example.com/b#top", "http://example.com/b#part"]:
    print(urldefrag(link).url)
Predict

What does urldefrag("http://example.com/b#top").url give?

Pick one to see what it prints.
Pick an answer above to see the rest

Keep only the exact host

The third step keeps the crawl on one site.

from urllib.parse import urlparse

for link in ["http://example.com/x", "http://Example.com:80/x",
             "http://news.example.com/n", "http://badexample.com/",
             "mailto:me@example.com"]:
    print(f"{link:27} {urlparse(link).hostname}")
print(urlparse("http://example.com:80/x").netloc)
Predict

What is urlparse("http://Example.com:80/x").hostname?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 24 min
A pool and a coordinator

Run the fetches on a pool with a fixed number of threads

Now bring the threads back, with a fixed number of them.

A thread pool is a fixed set of threads that take jobs from a queue

A pool with max_workers=4
in flight, one on each worker
u1u2u3u4
waiting in the pool's queue
u5u6u7

Never more than 4 fetches in flight. The rest wait their turn, and the next one starts the moment a worker is free.

A thread pool is a fixed set of threads that take jobs from a queue. Python's is ThreadPoolExecutor(max_workers=n), from the concurrent.futures module.

When all n threads are busy, new jobs wait in the pool's queue until a thread is free. That queue now holds your frontier, and max_workers is your bound on fetches in flight. That bound is exactly what the tests measure.

submit gives you a future, and result() waits for it

from concurrent.futures import ThreadPoolExecutor

urls = [f"{E}/", f"{E}/a", f"{E}/c"]
with ThreadPoolExecutor(max_workers=2) as pool:
    futures = [pool.submit(fetch, url) for url in urls]
    for url, future in zip(urls, futures):
        print(url, "has", len(future.result()), "links")
Predict

Three URLs on a pool of 2 threads, all submitted first. What do the three lines report?

Pick one to see what it prints.
Pick an answer above to see the rest

Why not start one thread per link and skip the pool?

The home page returns 40 links
a thread per link
40 in flight
a pool of 4
4 in flight, 36 queued

A thread per URL looks like the same thing without the bookkeeping, and on the test site it's even faster. But the number of threads has no bound, and the number of URLs isn't up to you.

Size the pool from the rate you want

Fetches in flight equal the rate you want times how long each fetch takes. That's Little's law, L=λWL = \lambda W. Here LL is the number in flight, λ\lambda (lambda) is the rate in pages a second, and WW is the seconds each fetch takes.

Predict

Each fetch takes 0.2 s, and you want 20 pages a second. How many fetches must be in flight?

Pick an answer above to see the rest

One coordinator thread makes every decision

A pool fetches a fixed list of URLs. A crawl doesn't have a fixed list.

Each finished page can bring more work

The coordinator's loopInteractive
wait = wait(pending, return_when=FIRST_COMPLETED). Block until any one fetch finishes.

The hard part isn't fetching in parallel. It's that work makes more work: every finished page can bring new URLs. So you can't submit everything up front and wait. You need a loop that keeps feeding the pool, and a rule for when to stop.

The cleanest version keeps every decision in one thread, the coordinator. Workers only fetch.

The coordinator loop

import logging
import sys
from collections.abc import Callable
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from urllib.parse import urldefrag, urljoin, urlparse

logging.basicConfig(stream=sys.stdout, format="%(message)s")
log = logging.getLogger("crawler")


def normalize(base: str, href: str) -> str:
    """href resolved against its page, base, with no fragment."""
    return urldefrag(urljoin(base, href)).url


def crawl(
    start_url: str, fetch: Callable[[str], list[str]], max_workers: int = 8
) -> set[str]:
    """Every reachable page on the start's host, max_workers fetches at a time."""
    start = urldefrag(start_url).url
    host = urlparse(start).hostname
    # every URL ever submitted
    seen = {start}
    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        # future -> its URL
        pending = {pool.submit(fetch, start): start}
        while pending:
            done, _ = wait(pending, return_when=FIRST_COMPLETED)
            for future in done:
                url = pending.pop(future)
                try:
                    links = future.result()
                except Exception as exc:
                    log.warning("fetch failed for %s: %r", url, exc)
                    continue
                for link in links:
                    link = normalize(url, link)
                    if urlparse(link).hostname == host and link not in seen:
                        seen.add(link)
                        pending[pool.submit(fetch, link)] = link
    return seen


calls.clear()
for url in sorted(crawl(f"{E}/", fetch, max_workers=4)):
    print(url)
print(len(calls), "fetches")
Predict

The coordinator crawls the small site on 4 workers. How many fetches, and what happens at /broken?

Pick one to see what it prints.
Pick an answer above to see the rest

Stop when nothing is pending

pending on the small site, with equal fetch times:

Momentpending
at the start{ / }
/ finishes{ /a, /b }
/a and /b finish{ /c, /broken }
/c and /broken finish{ }: empty, the crawl is over
Predict

pending is empty. Can a fetch still be running somewhere?

Pick an answer above to see the rest
Predict

as_completed gets 3 futures, and the loop adds a fourth while it runs. How many come out of the loop?

Pick one to see what it prints.
Pick an answer above to see the rest

Level by level, every level waits for its slowest page

Here is what that waiting costs, on a site with a few slow pages.

25 pages, 3 of them slow, 8 workers
level by level
1.58 s
wait(FIRST_COMPLETED)
0.69 s

Level by level, a level starts only when the one before is done. With FIRST_COMPLETED, each chain moves on by itself.

The site is a home page linking 8 pages, and each of those starts a chain of two more. A few pages sleep 0.5 s instead of 50 ms, each on its own chain. With 8 workers:

Slow pagesLevel by levelwait(FIRST_COMPLETED)
1, on level 10.68 s0.68 s
2, on levels 1 and 21.13 s0.69 s
3, one on each level1.58 s0.69 s

Each level pays for its own slowest page. The growing set of pending futures pays once.

Workers never wait on other futures

Predict

Each worker fetches a page, submits its links and calls .result() on them. 4 workers, a chain of 11 pages. What happens?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 24 min
Errors and shared state

One bad page is a log line

Real pages fail: a server refuses, or a connection drops. One failure must not stop the crawl.

result() raises the fetch's error in the thread that asks for it

with ThreadPoolExecutor(max_workers=2) as pool:
    future = pool.submit(fetch, f"{E}/broken")
    try:
        future.result()
    except ConnectionError as exc:
        print("result() raised", repr(exc))
Predict

The fetch of /broken raises ConnectionError on a worker thread. What happens when the main thread calls future.result()?

Pick one to see what it prints.
Pick an answer above to see the rest

Catch Exception, not BaseException

Which errors should the crawl catch?

Predict

You catch BaseException around result() instead of Exception. What breaks?

Pick an answer above to see the rest
Predict

8 workers, and 8 pages that never answer. What happens to the crawl?

Pick an answer above to see the rest

Who owns the visited set

Shared state is where threaded code breaks. In this design, who touches what?

With one coordinator, nothing is shared

ThreadTouches
the coordinatorseen and pending: the only thread that reads or writes them
each workerfetch(url) only: it takes a URL and hands back the links through the future

Shared state needs an owner. In the coordinator design, the owner is the main thread: only it reads or writes seen and pending. Workers run fetch(url) and hand back a list through the future. Nothing they touch is shared, so nothing needs a lock.

With workers that decide, the check and the add are one step

import queue
import threading


def crawl(
    start_url: str, fetch: Callable[[str], list[str]], max_workers: int = 8
) -> set[str]:
    """Each worker fetches a page, then checks and queues its links."""
    start = urldefrag(start_url).url
    host = urlparse(start).hostname
    seen, lock = {start}, threading.Lock()
    # URLs to fetch, then one None per worker
    todo: queue.Queue[str | None] = queue.Queue()
    todo.put(start)

    def worker() -> None:
        """Takes URLs from todo until it gets None."""
        while (url := todo.get()) is not None:
            try:
                for link in fetch(url):
                    link = normalize(url, link)
                    if urlparse(link).hostname != host:
                        continue
                    # check and add, one step
                    with lock:
                        if link in seen:
                            continue
                        seen.add(link)
                    # the page's links go in first
                    todo.put(link)
            except Exception as exc:
                log.warning("fetch failed for %s: %r", url, exc)
            finally:
                # then the page counts as done
                todo.task_done()

    threads = [threading.Thread(target=worker) for _ in range(max_workers)]
    for t in threads:
        t.start()
    # unfinished count reached zero
    todo.join()
    for _ in threads:
        # one stop signal per worker
        todo.put(None)
    for t in threads:
        t.join()
    return seen

This is the other classic design. It hands the decisions to the workers. Each worker takes a URL from a queue.Queue, a queue that many threads can share safely, fetches it, and puts the new links back. Now every worker touches seen.

In the editor, 20 threads each try to claim /a at the same moment. Write claim(url): under lock, return False if url is in seen, else add it and return True, so exactly one thread wins.

Two workers can both see a URL as new

When the workers share the visited set, here is the race.

Predict

No lock. Workers A and B both check /x before either adds it. What happens?

Pick an answer above to see the rest
Predict

A worker calls task_done() for a page before it puts the page's links. What can go wrong?

Pick an answer above to see the rest

A race your tests can't trigger is still a race

The race is real, but it's hard to catch in a test.

Predict

300 runs of an unlocked check-and-add, on a site where 40 pages all link to the same 20. How many fetched a page twice?

Pick an answer above to see the rest
Predict

In asyncio, where can a task be paused?

Pick an answer above to see the rest

A worked example

The small site, page by page

Run the coordinator on the practice tests' small site, starting at http://example.com/, where fetching /broken raises. Paths are on http://example.com unless another host is shown.

Page finishedIts linksAfter normalize and filterSubmitted
//a, /b#top, other.com/x/a new, /b new, other.com dropped/a, /b
/a/, /c, news.example.com/n/ seen, /c new, news.example.com dropped/c
/b/a#part, /broken/a seen, /broken new/broken
/cnone
/brokenraises ConnectionErrorlogged

With equal fetch times, /a and /b finish together, then /c and /broken. Other timings reorder the rows but change nothing else.

That's five fetches and five pages: /, /a, /b, /c and /broken. Three URLs are never fetched. other.com/x and news.example.com/n are on other hosts. /never sits behind the broken page, so nothing ever finds it.

The 41-page site, timed

The tests' other site is a home page linking 40 pages, each linking back home and on to the next page. Each fetch sleeps 50 ms, which averaged 58 ms here.

Predict

8 workers. The home page is one round, and its 40 links go out together, 8 at a time. How many rounds of about 58 ms in all?

Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 13 min
What interviewers ask next

What interviewers ask next

The problem's README lists the design follow-ups. Have an answer ready for each.

Politeness: cap the rate for each host

import threading
import time


class RateLimit:
    def __init__(self, per_second: float) -> None:
        self.gap, self.next_slot, self.lock = 1 / per_second, 0.0, threading.Lock()

    def wait(self) -> None:
        """Sleeps until this caller's reserved slot."""
        # reserve a slot: arithmetic only
        with self.lock:
            now = time.monotonic()
            slot = max(now, self.next_slot)
            self.next_slot = slot + self.gap
        # sleep outside the lock
        time.sleep(slot - now)
Predict

Pages come back in 10 ms, and you run 8 workers. How many requests a second hit the server?

Pick an answer above to see the rest
Predict

At 10 requests a second, how long does the 41-page site take with 1, 8 or 40 workers?

Pick an answer above to see the rest

robots.txt: the site's rules for crawlers

A polite crawler also reads a site's rules before it fetches.

from urllib.robotparser import RobotFileParser

robots = RobotFileParser()
robots.parse(["User-agent: *", "Disallow: /private/", "Crawl-delay: 2"])
print(robots.can_fetch("mybot", "http://example.com/private/x"))
print(robots.can_fetch("mybot", "http://example.com/docs"))
print(robots.crawl_delay("mybot"))
Predict

robots.txt says Disallow: /private/ and Crawl-delay: 2. What do the three lines print?

Pick one to see what it prints.
Pick an answer above to see the rest
Predict

Which failure should you not retry?

Pick an answer above to see the rest

Threads, asyncio or processes

The last follow-up asks why threads, and not something else.

ThreadsasyncioProcesses
Best atwaiting, with ordinary blocking librarieswaiting, on thousands of connectionsPython computing, like parsing
Each one costsan OS threada task object in one threada whole process
Shared stateneeds a lock once workers share itcan only switch at an awaitnot shared, data is pickled across
Watch forthe OS thread limitone blocking call stalls every taskstartup and pickling cost

Three tools for the same problem. A crawler is I/O-bound: its time goes to waiting, so it's threads or asyncio.

asyncio wins when you want thousands of connections open at once, and every library you call is async, like an httpx or aiohttp client. Threads win when your fetch is ordinary blocking code, like urllib or requests, and a few dozen workers are enough.

Predict

Parsing pages in Python becomes the bottleneck. What do you add?

Many machines: start with the number

Past one machine, the first question is how many.

Predict

A billion pages in 30 days. About how many pages a second?

Pick an answer above to see the rest
Predict

Dedup at scale: a billion URLs at 100 bytes each. How big is one seen set holding all of them?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.Each fetch on the 41-page site waits about 58 ms. One page at a time took 2.36 s, and an 8-thread pool took 0.35 s. Why doesn't the GIL stop that?

  2. 2.You start a threading.Thread for every new link instead of using a pool. On the test's 41-page site with max_workers=4, how many fetches were in flight at the peak?

  3. 3.A page links to http://example.com/b#top. What should go into seen and get fetched?

  4. 4.The crawl starts at http://example.com/. Which check keeps it on that host?

  5. 5.One page's fetch raises ConnectionError, and your coordinator calls future.result() with no try. What happens?

Where this shows up

The reports behind this lesson, each with its source.

Crawler question (candidate comment, Feb 2024): implement a batch-processing version of a crawler with processes or threads.

Candidate report·Blind (candidate comment)·2024-02-16Source

SWE candidate (US, dated 2025-08-07, no offer): a web crawler question that was part coding and part system design.

Candidate report·Taro (candidate report)·2025-08-07Source

Hello Interview lists 'Web Crawler Multithreaded' (BFS crawl from a seed URL) with Anthropic Senior reports in its timeline (early December 2025, late May 2026).

Prep site·Hello Interview (prep site; candidate timeline)Source

Practice

Sources (5)
  1. threading: Thread-based parallelism · Python 3.15 documentation · Oct 25, 2026
    “Threads are particularly useful when tasks are I/O bound, such as file operations or making network requests, where much of the time is spent waiting for external resources.”
  2. Glossary: global interpreter lock · Python 3.15 documentation · Oct 25, 2026
    “Also, the GIL is always released when doing I/O.”
  3. urllib.parse: Parse URLs into components · Python 3.15 documentation · Oct 25, 2026
    “If url contains a fragment identifier, return a modified version of url with no fragment identifier, and the fragment identifier as a separate string.”
  4. concurrent.futures: Launching parallel tasks · Python 3.15 documentation · Oct 25, 2026
    “If the call raised an exception, this method will raise the same exception.”
  5. queue: A synchronized queue class · Python 3.15 documentation · Oct 25, 2026
    “When the count of unfinished tasks drops to zero, join() unblocks.”