Sub topic 6
Designing the URL frontier
This chapter assumes you can read short Python programs, know queues, hash sets, and heaps, and have seen the URL normalization from the previous chapters. Here you build the frontier, the component that decides which URL the crawler fetches next.
What the frontier does
The frontier holds every URL that has been discovered but not yet fetched. It has three jobs:
- Accept new URLs and reject ones already seen.
- Hand out one URL at a time when the fetcher asks.
- Choose the order so that no single host is hit too fast.
A plain FIFO queue does the first two jobs. It fails the third. A page with 200 links to the same site puts 200 consecutive requests to that host at the front of the queue.
One queue per host
The fix is to keep a separate queue for each host. A heap then orders the hosts by the earliest time each may be contacted again. The fetcher always takes the host at the top of the heap, so the other hosts are served while one host waits out its delay.
The implementation
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
if __name__ == '__main__':
f = Frontier(delay=0.5)
for u in ['http://a.example/1', 'http://a.example/2', 'http://b.example/1']:
f.add(u)
while (url := f.next()) is not None:
print(round(time.monotonic() % 100, 1), url)The demo prints a.example/1, then b.example/1, then a.example/2 about half a second later. The second a.example URL waits, and b.example goes in between.
Design points and common errors
- A host is in the heap only while its queue is non-empty.
addpushes the host only when its queue was empty, andnextre-pushes it only if URLs remain. Pushing a host twice would let it be fetched twice in a row, ignoring the delay. - Use
time.monotonic(), nottime.time(). The system clock can jump, which would break the delays. - Normalize before
add. The seen set compares strings, so unnormalized duplicates get through. - The seen set records discovery, not fetching. A URL is marked seen when queued. Otherwise the same link found on ten pages would be queued ten times.
Extending the design
This frontier is FIFO within a host, so crawling is breadth-first. To prefer important pages, replace each deque with a priority queue. To honor a site's Crawl-delay, store a per-host delay instead of the single self.delay.
Exercise
Why does the frontier keep a heap of hosts instead of a single heap of URLs ordered by allowed fetch time?
Show answer
Each URL's allowed time depends only on its host. With a heap of URLs, every URL for a busy host would need its time updated after each fetch. With one queue per host, only one heap entry per host exists, and its time changes once per fetch. The heap stays small, and URLs within a host keep their arrival order.