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.
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
0 ms600 ms
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?
Put numbers on it. Say each fetch waits wait_ms on the network and spends work_ms in your own code. In the editor, write waiting_share(wait_ms, work_ms), the share of each fetch spent waiting, and pages_per_second(wait_ms, work_ms), the pages one fetch at a time gets through in a second.
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?
A waiting thread lets go of the GIL
The usual objection to threads in Python is the GIL. CPython, the standard Python, has one lock called the GIL, the global interpreter lock. Only the thread that holds it can run Python code.
It doesn't get in the way here, because a waiting thread isn't running Python code. Python's glossary says a thread always lets go of the GIL while it does I/O, meaning input and output, like a network read. While one thread waits, the others take turns doing their small part.
time.sleep lets go of the GIL too, just like a socket read. That's why the tests' fake network behaves like a real one.
Threads help with waiting, not with computing
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?
Each fetch is
One at a time
8 threads
50 ms of waiting (time.sleep)
2.36 s
0.35 s
50 ms of pure-Python arithmetic
2.02 s
2.03 s
When the work is waiting, 8 threads are 6.7 times faster. When the work is Python computing, they gain nothing, because only one of them can compute at a time:
The same fetches as Python arithmeticInteractive
w1
w2
w3
w4
0 ms600 ms
runs Python, holds the GIL waits on the network, GIL let go
Total
600 ms
Speedup
1.0×
Peak in flight
1
4 workers, but only the thread that holds the GIL can compute, so they take turns: 600 ms, no faster than one at a time.
That's the whole GIL story: threads for waiting, processes for computing. A process is a separate running program, with its own memory and its own GIL. Python 3.13 added an optional free-threaded build without the GIL, but it isn't the default, so plan for the GIL.
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:
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.
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
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.
fetch(url) returns the links on a page. /broken raises, like a server that refuses you. A page that isn't in SITE has no links. calls records every fetch, so you can count them.
Breadth first means the start, then every page one click away, then every page two clicks away. Keep a queue: take the oldest page from the front, and add each page you haven't seen to the back. In the editor, links is a smaller site as a plain dict from each page to its links. Write depths(start, links): each reachable page and its fewest clicks from start, which is its parent's count plus one.
Breadth first needs two pieces of state. Here is the whole crawl, one page at a time.
from collections import dequefrom collections.abc import Callablefrom urllib.parse import urldefrag, urljoin, urlparsedef 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 seencalls.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.
The crawl keeps two pieces of state:
The frontier: URLs you've found but haven't fetched yet.
The visited set, seen: every URL that has ever gone into the frontier.
Here they are after each fetch:
Step
Fetch
Frontier after
seen after
1
/
/a/b
//a/b
2
/a
/b/c
//a/b/c
3
/b
/c/broken
//a/b/c/broken
4
/c
/broken
no change
5
/broken
empty
no change: the fetch fails
/broken went into seen before its fetch failed. So it counts as reached even though it adds no links, which is the problem's rule for broken pages.
Get it right one page at a time first. The faster versions are this same loop with the fetches overlapped.
popleft takes the oldest URL, so the nearest pages come first
The frontier is a deque, open at both ends
frontier
oldestnextnewest/b/c/broken
popleft() takes the oldest, /b, so the nearest pages come first: breadth first. pop() would take the newest, /broken: depth first. append() adds new links at the right.
popleft() takes the oldest URL, so pages come out in order of distance from the start. That's breadth-first search. pop() would go depth-first.
Order starts to matter once there's a budget, like a page limit or a maximum depth. Then breadth-first gets you the pages nearest the start first.
Pick an answer above to see the rest
Predict
pop() instead of popleft(). What comes back?
A deque is a list that is fast at both ends. The name isn't the point: a plain list with pop(0) gives the same order, only slower on a big frontier.
In the editor, write visit_order(start, links, from_left): the order pages leave the frontier. Take them with popleft() when from_left is true and with pop() when it's false, and mark each page when you find it.
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?
Here is each fetch, both ways:
Fetch
Mark when fetched
Mark when found
home
queue p0 to p39
queue p0 to p39
p0
p1 isn't marked yet, so queue p1 again
p1 is marked: skip
p1
queue p2 again
p2 is marked: skip
in all
80 fetches for 41 pages
41 fetches for 41 pages
The line that matters most is where seen.add sits. Mark a URL when you find it, before it goes into the frontier, and nothing gets queued twice. Mark it when you fetch it instead, and every link to a page that's still waiting queues that page again.
With eight workers, marking at fetch time cost 62 to 68 fetches, varying from run to run. The tests catch it, because each page must be fetched exactly once.
In the editor, finish nearest(start, fetch, max_pages): the crawl loop under a budget. It fetches at most max_pages pages, nearest the start first, and marks each link when it finds it.
CheckpointBreadth first, under a budget
Finish nearest(start, fetch, max_pages): fetch at most max_pages pages, nearest the start first, and return them in the order you fetched them. Mark each link when you find it, so no page is fetched twice. The links here are already clean, so skip normalizing.
Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 11 min
Clean links
Clean every link before you compare it
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 urljoinpage = "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.
On a real page, a link's href is often relative: written from where the page sits, like a path between folders. urljoin(page_url, href) turns it into a full URL, using the page it came from.
The practice problem's links are already full URLs, and urljoin passes those through unchanged. So it costs nothing there.
Look at the //other.com/x row. A link that starts with // keeps the page's http: and takes a new host. A join can land on any host, so the host check comes after the join.
Resolve against the URL the page actually came from. After a redirect, that's where you landed, not what you asked for.
In the editor, write absolute(page, hrefs): each link in hrefs resolved against page with urljoin, in order.
The second step: the part after # names a place on a page, not a different page.
from urllib.parse import urldefragprint(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.
The part after # is the fragment. It names a spot inside a page, and it never reaches the server: urllib's request for http://example.com/b#top asks for /b.
So /b, /b#top and /b#part are one page. urldefrag(url) splits the fragment off and returns a pair. .url is the part you keep. The worked solution writes urldefrag(url)[0], the same thing by position, and either spelling is fine.
In the editor, found holds four links as pages wrote them. Set pages to the set of pages they point at, with every fragment dropped by urldefrag.
from urllib.parse import urlparsefor 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.
urlparse(link).hostname is the host in lower case, without the port or a user name. It is None for a link with no host, like mailto: or javascript:. Compare it with == to the start URL's host.
The link's hostname
== "example.com"
.endswith("example.com")
example.com
keep
keep
news.example.com
skip
keep: wrong, a subdomain
badexample.com
skip
keep: wrong, another site
None, a mailto:
skip
crash
A subdomain is a different host: news.example.com isn't example.com. Don't compare netloc either. It keeps the port and the user name, as the last line of the output shows, so http://example.com:80/ would look like another site.
In the editor, write keep(base, href, host): all three steps on one link. Resolve href against base, the page it came from, drop the fragment, and return the result only if its hostname is exactly host. Return None for every other link.
CheckpointNormalize, then check the host
Write keep(base, href, host): resolve href against base, the page it came from, drop any fragment, and return the result if its hostname is exactly host. Return None for every other link.
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 ThreadPoolExecutorurls = [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.
pool.submit(fetch, url) hands the call to the pool and returns at once with a future: an object that will hold the call's result once the call finishes. future.result() waits for the call, then returns what it returned.
submit, then resultInteractive
→
→
pool.submit(fetch, url) = a future, at once. The main thread gets the future right away and goes on to submit the next URL.
Submit them all before you wait on any. Call result() right after each submit(), and each fetch waits for the one before it. Leaving the with block waits for every job to finish, then stops the threads.
The pool, submit and result are all the API you need here. Other languages have the same object under other names, like a promise in JavaScript.
In the editor, fake_fetch sleeps 50 ms like a fetch, and running and peak count fetches in flight. They are one-item lists so the function can change them. Finish fake_fetch so it counts itself in under lock and records the peak, then run the 12 URLs on a pool of 3 and see that the peak never passes 3.
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=λW. Here L is the number in flight, λ (lambda) is the rate in pages a second, and W 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?
To fetch 100 pages a second at 200 ms each, you need 100×0.2=20 in flight. With fewer, you can't reach the rate. With more, the extra workers sit idle, or worse, push the server harder than you meant to. In practice a politeness limit sets the rate, and the rate sets the pool.
In the editor, write fetch_all(urls, fetch, max_workers): every URL fetched on a pool of max_workers threads, returned as {url: links}. Submit them all before you call result() on any.
CheckpointA pool with a bound
Write fetch_all(urls, fetch, max_workers): fetch every URL on a ThreadPoolExecutor with max_workers threads and return {url: links}. Submit them all before you wait on any result, so the fetches overlap.
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 loggingimport sysfrom collections.abc import Callablefrom concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, waitfrom urllib.parse import urldefrag, urljoin, urlparselogging.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)).urldef 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 seencalls.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.
The basicConfig line only sends the log to the screen, so you see it here. Walk through the loop:
pending maps each future to its URL, so you know which page a result or an error belongs to.
wait(pending, return_when=FIRST_COMPLETED) blocks until at least one fetch finishes. It returns two sets: the finished futures, and the rest.
For each finished page, the coordinator cleans its links, filters them, marks the new ones and submits them. So the pool never sits idle while there's work.
The loop ends when pending is empty.
wait and FIRST_COMPLETED are only the spelling. The idea is: wait until any one fetch finishes. The worked solution keeps pending as a plain set and takes the second set that wait returns as the new pending. That works the same way.
In the editor, fake_fetch sleeps 0.3 s, 0.05 s or 0.15 s, by URL, and futures maps each future to its URL. Set done, pending with wait(futures, return_when=FIRST_COMPLETED), then set fastest to the URL of the future in done.
pending on the small site, with equal fetch times:
Moment
pending
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?
as_completed only sees the futures you gave it at the start
from concurrent.futures import as_completedwith ThreadPoolExecutor(max_workers=2) as pool: futures = {pool.submit(fetch, f"{E}{p}"): p for p in ["/", "/a", "/b"]} came_out = 0 for future in as_completed(futures): came_out += 1 if len(futures) == 3: # add a fourth futures[pool.submit(fetch, f"{E}/c")] = "/c"print(len(futures), "futures,", came_out, "came out of the loop")
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.
as_completed(futures) hands back futures as they finish. It's the other tool people reach for, with one catch: it only looks at the futures you passed in when you called it.
So with as_completed, you crawl one level at a time:
level = [start]while level: futures = {pool.submit(fetch, url): url for url in level} level = [] for future in as_completed(futures): # the same handling, but new links go into level ...
That passes the tests too. But each level waits for its slowest page while the other workers sit idle.
In the editor, fetch returns a page's children from tree, and pending starts with the root page's future. Write the loop: while pending has futures, wait for the first to finish, pop each one, add its URL to got, and submit its children.
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 pages
Level by level
wait(FIRST_COMPLETED)
1, on level 1
0.68 s
0.68 s
2, on levels 1 and 2
1.13 s
0.69 s
3, one on each level
1.58 s
0.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?
Worker
Fetched
Then waits for
1
page 0
page 1's result
2
page 1
page 2's result
3
page 2
page 3's result
4
page 3
page 4's result
the queue
page 4
a free worker, and none ever comes
That's a deadlock: threads that wait on each other, so none can move. Python's docs warn about exactly this case, a call in the pool that waits on another future. The coordinator does all the waiting, outside the pool.
The editor holds the coordinator on a folder tree instead of a site. list_dir(path) returns a folder's children, the way fetch returns a page's links, and found(path) marks a new path and submits its listing. In walk, write the loop that waits for finished listings, hands each child to found, and stops when nothing is pending.
CheckpointWork that makes more work
The coordinator's shape on a folder tree: list_dir(path) returns a folder's children, and walk(root, list_dir, max_workers) returns every path reachable from root. found(path) already marks and submits a new path, so write the loop that keeps going until nothing is pending.
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.
A fetch can raise: a timeout, a refused connection, a server error.
In the coordinator design, the thread that asks is the main loop. So an unguarded result() turns one bad page into a dead crawl.
Catch it, log the URL and carry on
try: links = future.result()except Exception as exc: log.warning("fetch failed for %s: %r", url, exc) continue
That's the try in the coordinator: catch Exception, log the URL and the error, and continue to the next finished page. The page is already in seen, so it still counts as reached, which is what the problem asks for.
On the 41-page site, with one of home's links failing, 8 workers and no try:
Round
Fetches
What happens
1
home
it submits all 40 links
2
p0 to p7
p0 fails, and result() raises
3 to 6
p8 to p39
leaving the with block waits for every queued fetch
after round 6
only now does the caller see the error
In the editor, fetch raises for /broken. Call result() on each future inside a try, put the good URLs in ok and the failed ones in failed, and carry on.
You catch BaseException around result() instead of Exception. What breaks?
Exception
Catch it?
KeyboardInterrupt, from Ctrl-C
no: it sits outside Exception, so it gets through
ConnectionError, a refused or dropped connection
yes: an OSError, under Exception
TimeoutError, a fetch that took too long
yes: an OSError, under Exception
And log the failure rather than pass over it. A crawl that quietly lost half its pages looks exactly like a small site.
A page that hangs needs a timeout
Pick an answer above to see the rest
Predict
8 workers, and 8 pages that never answer. What happens to the crawl?
Give every real fetch a timeout, like urllib.request.urlopen(url, timeout=10), so a hang turns into an exception you already handle.
Your walk from the coordinator step is in the editor, and now some listings raise. Change it so a folder whose listing raises is logged with log.warning, still counts as reached, and the walk carries on.
CheckpointOne bad folder is a log line
Some listings raise. Change walk so a folder whose listing raises still counts as reached, the walk carries on, and each failure goes to log.warning with its path. Ctrl-C still has to stop the walk.
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
Thread
Touches
the coordinator
seen and pending: the only thread that reads or writes them
each worker
fetch(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 queueimport threadingdef 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.
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?
Step
Worker A
Worker B
1
is /x in seen? no
2
is /x in seen? no
3
add /x, queue it
4
add /x, queue it
/x gets fetched twice.
A lock lets only one thread at a time run a block of code. Here it covers the check and the add, and nothing more. With both under one lock, worker B can't check /x until worker A has added it.
Hold the lock across a fetch, though, and your eight workers take turns, one fetch at a time.
join() waits for a counter to reach zero
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?
On the small site
Unfinished count
put(/)
1
a worker gets / and fetches it
1
it puts /a and /b
3: the page's links go in first
it calls task_done() for /
2: then the page counts as done
the other pages, the same way
task_done() for the last page
0: join() returns
todo.join() waits on a counter, not on an empty queue. Every put() adds one, and every task_done() takes one away. When the count reaches zero, join() returns.
A worker puts a page's links before it calls task_done() for the page. So the count can't reach zero while any page still has work coming.
task_done() sits in finally, so a page that raises still counts down. Leave it out, and join() waits forever.
One None per worker stops the threads
When join() returns, one None per worker tells them to stop, and t.join() waits until they have.
The worker's first line reads inside out. todo.get() waits until the queue holds an item and takes it. := assigns it to url inside the condition. The loop ends when that item is None. The := is only shorthand: while True:, then url = todo.get(), then if url is None: break, does the same.
In the editor, four workers take URLs from jobs until they get None. After the ten jobs, put one None on jobs for each worker, then join every worker, so none is still running at the end.
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?
On that site, 300 runs with if link in seen right before seen.add(link) fetched nothing twice. That held even with sys.setswitchinterval(1e-6), which asks Python to switch threads every microsecond.
Then put a slow step between the check and the add, say a 1 ms robots.txt lookup. All 50 of 50 runs fetched pages more than once: a median of 160 fetches for 61 pages, with one page fetched 7 times. Claim the URL under the lock first and do the slow check after, and there were zero duplicates.
A race your tests can't trigger is still a race. And on a free-threaded build, the threads really do run that window at the same time.
asyncio needs no lock between awaits
asyncio runs many tasks in one thread, and switches between them. Its three pieces fit in a few lines:
async def makes a coroutine: calling nap("a") doesn't run it yet, it makes a task to run. await runs one and waits for its result, and the current task pauses right there so others can run. asyncio.gather runs several at once and returns their results in order, and asyncio.run(main()) starts the loop that runs them all. Use asyncio.sleep inside a coroutine: time.sleep would stop every task at once, since they share one thread.
Pick an answer above to see the rest
Predict
In asyncio, where can a task be paused?
An asyncio crawler bounds its fetches with asyncio.Semaphore(n): a counter that lets at most n tasks into an async with block at once. asyncio.gather runs many tasks together and returns their results in order.
In the editor, fetch sleeps 20 ms and counts how many run at once in running and peak, but nothing limits it yet. Hold limit around its work with async with, and make main return all 10 fetches, run with asyncio.gather.
The video writes this section's worker design with asyncio. Its filter compares netloc against the allowed domains, which keeps any port. Compare hostname, as above.
Watch · 7 min
This section's worker design written with asyncio. A URL queue, a fixed set of worker tasks, a seen set updated as links are found, task_done in a finally and join to finish, then the workers cancelled. Links go through urljoin and urldefrag before a domain check.
Intro to async Python | Writing a Web Crawler · mCoding · Feb 2023YouTube
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 finished
Its links
After normalize and filter
Submitted
/
/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
/c
none
/broken
raises ConnectionError
logged
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?
Every run found all 41 pages with 41 fetches. Medians of 5 runs, 3 for the loop:
Crawler
Rounds
Measured
Peak in flight
one page at a time
41
2.36 s
1
pool, max_workers=1
41
2.33 s
1
pool, 2
21
1.21 s
2
pool, 4
11
0.64 s
4
pool, 8
6
0.35 s
8
pool, 16
4
0.23 s
16
pool, 40
2
0.13 s
40
pool, 64
2
0.13 s
40
In general the crawl takes 1+⌈40/w⌉ rounds of about 58 ms. Here w is max_workers, and ⌈x⌉ is x rounded up to a whole number.
Past 40 workers nothing improves, because only 40 pages are ever waiting at once. With 64 workers, the peak in flight was still 40.
In the editor, write best_time(pages, workers, seconds): the shortest crawl of a site shaped like this one, where the home page links to every other page. The home page takes a round alone. Then the other pages go workers at a time, and the last round may be part full.
The problem's README lists the design follow-ups. Have an answer ready for each.
Politeness: cap the rate for each host
import threadingimport timeclass 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?
So cap the rate for each host. A shared limiter that hands out time slots takes a few lines, and it's a clean example of a lock held only for arithmetic.
At 10 requests a second
Reserved slot
worker 1
0.0 s
worker 2
0.1 s
worker 3
0.2 s
worker 4
0.3 s
Each worker sleeps until its slot, outside the lock.
Call limit.wait() before each fetch(url).
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?
The limit sets the speed now, and 10×0.058≈0.6 fetches in flight says a single worker nearly keeps up.
For many hosts, keep one limiter per host. Better still, have the coordinator hold back URLs whose host isn't due yet and submit them when it is, so no worker spends its slot asleep.
In the editor, write slots(n, per_second, start): the time each of n requests may start, 1 / per_second apart, from start. These are the slots RateLimit hands out, one per caller.
robots.txt says Disallow: /private/ and Crawl-delay: 2. What do the three lines print?
Pick one to see what it prints.
Sites publish rules for crawlers at /robots.txt. Python reads them with urllib.robotparser.RobotFileParser. For a real site, call set_url() and read() once per host. Then call can_fetch(user_agent, url) before you submit a URL.
crawl_delay(user_agent) and request_rate(user_agent) return the site's own pace when it states one, and that feeds the limiter. Cache the parsed file for each host, and read it again on long crawls. The format is standardized as RFC 9309.
Retries with backoff
Try
Result
Then wait
1
fails
about 1 s
2
fails
about 2 s
3
fails
about 4 s
4
works
Pick an answer above to see the rest
Predict
Which failure should you not retry?
Wait longer each time: double a base delay, add some randomness so retries don't arrive in lockstep, and give up after a few attempts. If the server sends a Retry-After header, it's telling you how long to wait.
In the coordinator design, a retry is just the coordinator submitting the URL again later. So no worker sits in sleep() holding a slot.
In the editor, write delays(tries, base, cap): the wait before each retry. Start at base, double it each time, and never go above cap.
The last follow-up asks why threads, and not something else.
Threads
asyncio
Processes
Best at
waiting, with ordinary blocking libraries
waiting, on thousands of connections
Python computing, like parsing
Each one costs
an OS thread
a task object in one thread
a whole process
Shared state
needs a lock once workers share it
can only switch at an await
not shared, data is pickled across
Watch for
the OS thread limit
one blocking call stalls every task
startup 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?
One machine can hold that many connections. What breaks first is the state.
Host
A hash of the hostname picks
example.com
machine 2
other.com
machine 0
news.example.com
machine 1
Each machine holds, for its own hosts only, the frontier, the seen set, robots.txt and the rate limit.
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?
The frontier becomes a durable queue, split by host, so a crash resumes the crawl instead of restarting it.
Shard by host. A hash of the hostname picks the machine that owns each host. Only that machine fetches the host, so its robots.txt and rate limit live in one place. Links to other hosts get forwarded to their owners.
Dedup at scale. Each shard keeps the seen set for its own hosts, in a key-value store or a Bloom filter. A Bloom filter is a compact bit array that answers whether it has seen a key. It can wrongly answer seen and skip a page, but it never answers new for a URL it holds, so nothing gets fetched twice.
Duplicate content. Different URLs often serve the same page, from mirrors or session ids in the URL. A hash of the page body catches what URL normalization can't.
In the editor, write machines_needed(pages, days, per_machine_per_second): the fewest machines that crawl pages pages in days days, when one machine fetches per_machine_per_second pages a second.
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.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.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.A page links to http://example.com/b#top. What should go into seen and get fetched?
4.The crawl starts at http://example.com/. Which check keeps it on that host?
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.
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).
“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.”
“If url contains a fragment identifier, return a modified version of url with no fragment identifier, and the fragment identifier as a separate string.”