Sub topic 8
Politeness: per-host delays and queues
This chapter assumes you have read the earlier chapters on the URL frontier and robots.txt. You should be comfortable with queues, heaps, and short Python programs.
Why politeness matters
A crawler can send requests far faster than a small web server can answer them. If you fetch 50 pages from one host back to back, you may slow the site for real visitors, get your crawler blocked, or both. Politeness means limiting how often you contact each host.
The limit applies per host, not to the whole crawler. A global delay of one second would waste time, because the crawler could be fetching from other hosts while one host cools down.
The working model
The frontier keeps two structures:
- One FIFO queue per host, holding the URLs waiting for that host.
- A min-heap of
(earliest allowed time, host)entries, one for each host that has queued URLs.
To pick the next URL, pop the heap. The entry on top is the host that becomes available soonest. If its time has not arrived, wait. Then take one URL from that host's queue, record the next allowed time as now plus the delay, and push the host back if it still has URLs.
The code
This frontier implements that model. The demo adds three URLs on two hosts.
import heapq
import time
from collections import deque
from urllib.parse import urlsplit
class Frontier:
def __init__(self, delay=1.0):
self.delay = delay
self.queues = {} # host -> deque of URLs waiting for that host
self.next_time = {} # host -> earliest time of the next fetch
self.ready = [] # heap of (earliest time, host) for hosts with queued URLs
self.seen = set()
def add(self, url):
if url in self.seen:
return
self.seen.add(url)
host = urlsplit(url).netloc
queue = self.queues.setdefault(host, deque())
if not queue:
heapq.heappush(self.ready, (self.next_time.get(host, 0.0), host))
queue.append(url)
def next(self):
if not self.ready:
return None
when, host = heapq.heappop(self.ready)
wait = when - time.monotonic()
if wait > 0:
time.sleep(wait)
url = self.queues[host].popleft()
self.next_time[host] = time.monotonic() + self.delay
if self.queues[host]:
heapq.heappush(self.ready, (self.next_time[host], host))
return url
f = Frontier(delay=0.5)
for u in ['https://a.com/1', 'https://a.com/2', 'https://b.com/1']:
f.add(u)
start = time.monotonic()
while (url := f.next()) is not None:
print(f'{time.monotonic() - start:.1f}s', url)The output order is a.com/1, b.com/1, a.com/2. The second a.com URL waits about half a second, but b.com is served in the gap.
Design points and common errors
- Measure the delay from the start of the last request, or from its end? The code measures from when the URL is handed out. Many crawlers measure from the end of the download, so a slow server gets more breathing room.
- Use a monotonic clock.
time.monotonic()is not affected by system clock changes.time.time()can jump and break the spacing. - Key queues by host, including the port.
netlocdoes this. Subdomains such asa.example.comandb.example.comusually run on different servers, but they can share one, so treat the choice as a policy decision. - Never sleep per URL on a shared thread. The sleep here is fine for a single-threaded loop. With concurrency, you need to track the wait without blocking workers that could serve other hosts.
Exercise
The frontier holds 1,000 URLs from slow.com and one URL from fast.com, with a delay of 1 second. How long until fast.com is fetched, and why?
Show answer
Almost immediately, after at most one second. Both hosts start with an allowed time of 0.0, so each sits on the heap with its own queue. The crawler fetches one slow.com URL, which pushes slow.com back with a time one second later. The fast.com entry has an earlier time, so it is popped next. Per-host queues prevent one large host from blocking the others.