Sub topic 10
Fetching Many Pages Concurrently
This chapter assumes you have read the earlier chapters on fetching, the URL frontier, and per-host politeness. You should also know basic Python threads or concurrent.futures. It reuses Frontier, normalize, LinkExtractor, and fetch from those chapters.
Why a single-threaded crawler is slow
A crawler spends most of its time waiting. It waits for DNS, for the TCP and TLS handshake, and for the server to send bytes. The CPU is idle during those waits. If a typical fetch takes 500 ms and parsing takes 5 ms, a sequential loop manages about two pages per second, and almost all of that time is spent doing nothing.
Work that waits on the network is called I/O-bound. Overlapping many waits is the cheapest way to raise throughput. Concurrency does not make any single fetch faster. It lets many fetches be in flight at once.
Choosing a concurrency model
| Model | How it overlaps waits | Strengths | Weaknesses |
|---|---|---|---|
| Threads | One OS thread per in-flight fetch | Works with blocking libraries such as `urllib` | Memory per thread, shared-state bugs |
| asyncio | One thread, tasks yield at `await` | Thousands of connections cheaply | Needs async libraries, one blocking call stalls everything |
| Processes | Separate interpreters | Uses several CPU cores | Heavy, state must be passed explicitly |
For a crawler on one machine, threads or asyncio are the usual choices. Python's global interpreter lock (GIL) does not hurt much here, because a thread blocked on a socket releases it. Processes only pay off when parsing or content hashing becomes the bottleneck.
The demo below uses threads. It replaces the network with a half-second sleep so you can see the effect without hitting any server.
import time
from concurrent.futures import ThreadPoolExecutor
def fake_fetch(url):
time.sleep(0.5) # stands in for network latency
return url
urls = [f'https://site{i}.example/' for i in range(20)]
start = time.monotonic()
for u in urls:
fake_fetch(u)
print(f'sequential: {time.monotonic() - start:.1f}s') # about 10s
start = time.monotonic()
with ThreadPoolExecutor(max_workers=10) as pool:
list(pool.map(fake_fetch, urls))
print(f'10 threads: {time.monotonic() - start:.1f}s') # about 1sOne owner for crawl state
The tempting design is to let every worker thread call frontier.add() and frontier.next() directly. That breaks in several ways:
Frontier.addchecksurl in self.seenand then callsself.seen.add(url). Two threads can both pass the check and queue the same URL twice.- The heap and the per-host deques are modified in several steps. Without a lock, another thread can see them half-updated.
Frontier.nextsleeps to honor the delay. If you hold a lock while sleeping, every other thread stalls.
A simpler pattern is to give the frontier a single owner. The main thread schedules work and updates all state. Worker threads only fetch. They take a URL in and return (url, html), and they touch no shared structures.
This is a dispatch loop that keeps at most workers fetches in flight:
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
def fetch_page(url):
try:
return url, fetch(url)
except (OSError, ValueError):
return url, None
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)
pending = set()
submitted = 0
with ThreadPoolExecutor(max_workers=workers) as pool:
while True:
while len(pending) < workers and submitted < max_pages:
url = frontier.next()
if url is None:
break
pending.add(pool.submit(fetch_page, url))
submitted += 1
if not pending:
break
done, pending = wait(pending, return_when=FIRST_COMPLETED)
for future in done:
url, html = future.result()
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)Three details matter:
- The inner
whilefills free worker slots. Thewaitcall then blocks until at least one fetch finishes. - When the frontier is empty but fetches are still running, the loop waits instead of stopping. Those fetches may produce new links.
- The loop exits only when nothing is in flight and nothing can be submitted.
The budget counts submitted fetches, so failed fetches use up budget. That is deliberate. It guarantees the crawl stops even if every page fails.
Politeness under concurrency
Concurrency and politeness pull in opposite directions. Eight workers could send eight requests to one host at once. The frontier enforces a delay between the start times of requests to a host. It does not stop two requests to the same host from overlapping when a fetch takes longer than the delay. With delay=1.0 and a page that takes three seconds, up to three requests to one host can be in flight.
There are two ways to fix this:
- Track in-flight hosts. Do not hand out a URL for a host that already has a fetch running, and set the next-allowed time when the fetch finishes instead of when it starts.
- Cap total concurrency per host, for example at 1 or 2, and keep a global cap as well.
Concurrency helps most when the crawl spans many hosts. A crawl of one large site is limited by that site's delay, not by your worker count. Adding threads will not make it faster, and the right response is not to raise the request rate.
Common errors
- Unbounded in-flight work. Submitting every queued URL to the pool at once uses memory and hides back-pressure. Keep the in-flight count at or below the worker count, as the loop above does.
- Timeouts that do not bound total time. The
timeoutpassed tourlopenapplies to each socket operation, not to the whole download. A server that sends one byte every few seconds can hold a worker for a very long time. Enforce a total deadline, or stop reading after a time limit as well as a byte limit. - One slow host filling the pool. If every worker is waiting on the same sluggish host, fast hosts starve. A per-host in-flight cap prevents this.
- Too many workers. Each connection uses a file descriptor and a DNS lookup. Large worker counts can hit the operating system's open-file limit or overload your resolver. Start with 8 to 32 and raise the count only while throughput keeps rising.
- Sleeping on the scheduler thread.
Frontier.next()sleeps when the earliest host is not ready. This is acceptable at small scale. At larger scale, return the wait time to the scheduler so it can process finished fetches while it waits.
Picking the worker count
Use a rough estimate to size the pool. Throughput is about workers / average fetch time. With 500 ms fetches, 16 workers give about 32 pages per second. The real ceiling is usually one of these:
- your network bandwidth
- the per-host delays across the hosts you actually have queued
- the speed of parsing and storage
Measure the pages-per-second figure at several worker counts. When doubling the workers stops raising it, you have found the limit.
Exercise
A crawl has 16 workers and a 1-second per-host delay. Every page on the one seed host takes 4 seconds to download. How many requests to that host can be in flight at once with the frontier shown in this chapter, and what change would limit it to one?
Show answer
Up to four. The frontier only spaces the start times by 1 second, so requests that each last 4 seconds overlap. To limit it to one, track in-flight hosts in the scheduler, skip a host that already has a fetch running, and set its next-allowed time when the fetch completes.
Exercise
Why does the dispatch loop in this chapter keep all frontier and seen-set updates on the main thread instead of letting workers call frontier.add?
Show answer
Frontier.add checks and updates seen in separate steps, so two threads can queue the same URL twice, and the heap and deques can be seen half-updated. Keeping one owner removes the need for locks. A lock held around next() would also be held during its sleep and stall every thread.