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 Python queues, dictionaries, and heaps. It covers why a crawler must pace its requests, how to enforce that pacing with per-host queues, and which edge cases break the simple version.
Why politeness exists
A crawler that fetches as fast as it can acts like a small denial-of-service attack on the sites it visits. A typical small site runs on one modest server. Fifty requests per second from your crawler can slow it down for real visitors or knock it over. Site operators answer by blocking your IP address, and then your crawl is finished.
Politeness is the set of rules that prevents this:
- Never have more than one request in flight to the same host.
- Leave a minimum gap between consecutive requests to that host.
- Obey any
Crawl-delaythe site declares in robots.txt. - Slow down when the server shows signs of strain.
The key point is that politeness is per host, not global. A crawler can fetch quickly overall if it spreads requests across many hosts. The frontier's job is to make that interleaving happen.
The queue-per-host design
A single FIFO queue fails here. If the first 500 URLs all belong to one site, the crawler must either sleep between them (wasting time while other sites wait) or break the delay rule.
The standard fix has two parts:
- One queue per host, holding the URLs waiting for that host.
- A heap ordered by the earliest time each host may be contacted next.
The crawler pops the host that becomes ready soonest, fetches one URL from that host's queue, and pushes the host back with a new ready time of "now plus delay".
The basic frontier
This is the frontier from the earlier chapter. Read it with politeness in mind.
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 urlThree invariants keep this correct:
- A host is in the heap exactly when its queue is non-empty.
addpushes it when the queue goes from empty to non-empty.nextre-pushes it only if URLs remain. - The heap key is a monotonic clock value.
time.monotonic()never jumps backward when the system clock is adjusted, so use it for delays rather thantime.time(). - The delay is measured from the start of the previous fetch's scheduling, not from when the response finished. Section "Measuring the gap" below discusses that choice.
Choosing the host key
The code keys queues on netloc, which includes the port. That raises a design question: what counts as "the same server"?
| Key | Effect | Risk |
|---|---|---|
| `netloc` (host and port) | Simple, matches robots.txt scope | `a.example.com` and `b.example.com` may share one server and be hit in parallel |
| Hostname only | Merges ports | Rarely matters, and robots.txt is per origin |
| Registered domain | Protects shared servers | One huge site (a blogging platform) becomes a bottleneck |
| Resolved IP address | Protects the real machine | Needs DNS lookups, and CDNs put thousands of sites behind one IP |
Per-netloc is the usual default. Move to a coarser key only if you see evidence of subdomains overloading one server.
Honoring Crawl-delay and backing off
A fixed delay ignores two signals: the site's declared preference and the server's current health. The extension below handles both. It keeps a per-host delay, and it lets the caller push a host's next fetch time forward.
import heapq
import time
class PoliteFrontier(Frontier):
def __init__(self, delay=1.0, max_delay=60.0):
super().__init__(delay)
self.max_delay = max_delay
self.host_delay = {} # host -> delay in seconds
def set_delay(self, host, seconds):
self.host_delay[host] = min(max(seconds, self.delay), self.max_delay)
def back_off(self, host, seconds):
seconds = min(seconds, self.max_delay)
self.next_time[host] = max(self.next_time.get(host, 0.0),
time.monotonic() + seconds)
def next(self):
while self.ready:
when, host = heapq.heappop(self.ready)
due = self.next_time.get(host, 0.0)
if due > when: # host was pushed back after queuing
heapq.heappush(self.ready, (due, host))
continue
wait = when - time.monotonic()
if wait > 0:
time.sleep(wait)
url = self.queues[host].popleft()
gap = self.host_delay.get(host, self.delay)
self.next_time[host] = time.monotonic() + gap
if self.queues[host]:
heapq.heappush(self.ready, (self.next_time[host], host))
return url
return NoneThe if due > when check matters. back_off changes next_time, but the host's heap entry still carries the old time. Without the check, the host would be fetched too early. Re-pushing with the corrected time fixes this lazily, and a heap cannot update entries in place.
After you load a host's robots.txt, wire in its delay like this:
delay = rp.crawl_delay('MyCrawler')
if delay is not None:
frontier.set_delay(host, float(delay))When a response is 429 (Too Many Requests) or 503, read the Retry-After header. If it is a number of seconds, call frontier.back_off(host, seconds). If it is an HTTP date, convert it to a number of seconds. If the header is absent, double the host's delay up to max_delay.
Measuring the gap
There are two ways to define the delay:
- Start-to-start: the next fetch may begin
delayseconds after the previous one began. This is what the code above approximates. A slow response eats into the gap. - End-to-start: the next fetch may begin
delayseconds after the previous response finished. This is gentler on slow servers, because a server that takes 5 seconds to answer gets a rest afterward.
A common refinement is to set the gap to a multiple of the observed response time, for example max(delay, 10 * last_response_seconds). Slow servers are often the ones under load, so this slows you down exactly where it helps. To use end-to-start timing, call a method that sets next_time after the response arrives, instead of inside next.
Edge cases
- Single-threaded sleeping blocks everything.
nextsleeps until the earliest host is ready. That is fine when only one fetch runs at a time. With concurrent workers, the frontier must return "nothing ready yet" or the wait time instead of sleeping, so other workers can proceed. The next chapter on concurrency builds on this. - One request in flight per host. Concurrent workers can take two URLs from the same host if the second pop happens before the first fetch finishes. The delay usually prevents this, but a slow response longer than the delay exposes it. Mark a host as busy when handed out and clear the mark on completion.
- Hosts with huge queues. One site with a million URLs sits in the heap and is served once per delay. That is correct behavior, but it means that site's pages take a million seconds at a 1-second delay. Page budgets per host (covered under crawl traps) bound this.
- Memory. Queues for every discovered host live in memory. At large scale, keep only the heap and the head of each queue in memory and spill the rest to disk.
- Redirects. A redirect to another host must go back through the frontier. Following it immediately would skip the new host's delay.
- robots.txt fetches count. Requests for
/robots.txthit the same server and should respect the same delay.
Exercise
Your crawler uses a single FIFO queue for all URLs and sleeps 1 second between fetches. The first 1000 URLs in the queue belong to one site, and 50 other sites have URLs further back. What two problems does this cause, and how does the per-host queue plus heap design fix them?
Show answer
First, the crawler spends all its time on the one site at one page per second, so the other 50 sites wait roughly 1000 seconds. Second, the sleep applies to every fetch, so even when consecutive URLs come from different hosts, the crawler waits for no reason. With per-host queues and a heap keyed on next allowed time, the crawler fetches from another ready host while the busy host waits out its delay. Each host sees at most one request per delay interval, and the crawler stays busy.
Exercise
A server returns 503 with Retry-After: 30 for a host that has 200 URLs queued. Using the PoliteFrontier above, what do you call, and why does next need the due > when check afterward?
Show answer
Call frontier.back_off(host, 30). This sets next_time[host] about 30 seconds ahead, but the host's existing heap entry still holds the earlier time. The due > when check notices that the stored next_time is later than the entry's time, and re-pushes the host with the corrected time instead of fetching it early.