Sub topic 10
Fetching many pages concurrently
This chapter assumes you have read the earlier chapters on the URL frontier and per-host politeness. It also assumes you know Python's threading basics and why the global interpreter lock (GIL) matters.
Why a crawler needs concurrency
A fetch spends nearly all its time waiting on the network. A single-threaded crawler with a one-second politeness delay and 300 ms responses uses a small fraction of the machine. Fetching is I/O-bound, so threads help even with the GIL. The interpreter releases the GIL while a thread waits on a socket.
The demo below simulates the wait with sleep so you can see the effect.
import time
from concurrent.futures import ThreadPoolExecutor
def slow_fetch(url):
time.sleep(0.5) # stands in for network wait
return url
urls = [f'https://example.com/{i}' for i in range(20)]
start = time.monotonic()
for u in urls:
slow_fetch(u)
print('sequential', round(time.monotonic() - start, 1))
start = time.monotonic()
with ThreadPoolExecutor(max_workers=10) as pool:
list(pool.map(slow_fetch, urls))
print('threaded', round(time.monotonic() - start, 1))This prints about 10.0 seconds for the sequential run and about 1.0 for the threaded run.
Keep the frontier in one thread
The frontier and the seen set are plain Python objects with no locking. Sharing them among workers would need locks, and politeness bookkeeping is easy to get wrong under contention. A simpler design is to let one coordinator thread own all crawl state. Workers only download pages and return the results.
The loop below reuses Frontier, normalize, LinkExtractor, and fetch from the earlier chapters.
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
def crawl_concurrent(seeds, max_pages=50, workers=8):
frontier = Frontier(delay=1.0)
for seed in seeds:
url = normalize(seed, seed)
if url:
frontier.add(url)
in_flight = {} # future -> URL
submitted = 0
with ThreadPoolExecutor(max_workers=workers) as pool:
while True:
while submitted < max_pages and len(in_flight) < workers:
url = frontier.next()
if url is None:
break
in_flight[pool.submit(fetch, url)] = url
submitted += 1
if not in_flight:
break
done, _ = wait(in_flight, return_when=FIRST_COMPLETED)
for future in done:
url = in_flight.pop(future)
try:
html = future.result()
except (OSError, ValueError):
continue
if html is None:
continue
extractor = LinkExtractor()
extractor.feed(html)
for href in extractor.links:
link = normalize(url, href)
if link:
frontier.add(link)
print('fetched', url)The loop has two phases. It fills the pool up to workers jobs, then waits for at least one to finish and processes the results. Bounding in_flight is backpressure. Without it, the coordinator would queue thousands of jobs and memory would grow.
Threads or asyncio
| Approach | Strength | Cost |
|---|---|---|
| Thread pool | Works with blocking libraries such as `urllib` | Each thread uses memory, so it suits tens to low hundreds of connections |
| `asyncio` | Thousands of connections in one thread | Needs async HTTP and DNS libraries, and blocking calls stall everything |
Common errors
- Sharing the frontier or seen set across threads without a lock.
- Sizing the pool by CPU count. Size it by how many connections the network and target hosts can tolerate.
- Letting
frontier.next()sleep while finished results wait. In this version a long politeness delay stalls result processing. A production crawler would poll with a timeout instead. - Counting
max_pagesby submissions. Here failed fetches use up budget too.
Exercise
Your crawl has 50 workers, but all seed URLs are on one host with a 1-second delay. Roughly how many pages per second will you fetch, and why do the extra workers not help?
Show answer
About one page per second. The frontier hands out only one URL for that host per delay interval, so most workers sit idle. More workers help only when the frontier holds URLs from many different hosts.