Sub topic 6
Designing the URL Frontier
This chapter assumes you can read short Python programs and know queues, hash sets, and heaps. It also assumes you have read the earlier chapters on URL normalization and the seen set. Here you design the component that decides which URL the crawler fetches next.
What the frontier is responsible for
The URL frontier is the data structure that holds every URL the crawler has discovered but not yet fetched. A crawl loop calls it in two ways: add(url) when a link is found, and next() when a worker is ready for work.
A plain FIFO queue works for a toy crawler, but it breaks on a real site. Pages usually link to many pages on the same host. A FIFO queue then hands out dozens of URLs for one server in a row, and that violates the politeness limits you set. The frontier therefore has three jobs:
- Accept only URLs not seen before.
- Space out requests to each host.
- Keep other hosts busy while one host is waiting.
Priority is a possible fourth job, covered later.
Structure: one queue per host plus a schedule
The design in this chapter has two levels.
- A queue per host holds the URLs waiting for that host, in the order they were added.
- A min-heap of
(earliest_time, host)pairs records when each host may next be contacted. The host at the top of the heap is the one that becomes ready soonest.
Each host appears in the heap at most once, and only while its queue is non-empty. That invariant keeps the heap small, bounded by the number of active hosts instead of the number of URLs.
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 urlThree details matter here.
- The heap push in
addhappens only when the queue is empty. An empty queue means the host has no heap entry. A non-empty queue means it already has one. This is how the one-entry-per-host invariant holds. next_timeoutlives the queue. If a host's queue drains and a new URL arrives a moment later,addlooks up the oldnext_time. The new entry therefore still respects the delay from the last fetch.time.monotonic()is the right clock. It never jumps backward when the system clock is adjusted, which would otherwise break the schedule.
A short demonstration shows the interleaving:
f = Frontier(delay=0.5)
for u in ['http://a.example/1', 'http://a.example/2', 'http://b.example/1']:
f.add(u)
start = time.monotonic()
while (u := f.next()) is not None:
print(f'{time.monotonic() - start:.1f}s', u)The output is a.example/1 and b.example/1 at about 0.0s, then a.example/2 at about 0.5s. The frontier serves b.example between the two a.example URLs instead of making the crawler idle.
Where the delay comes from
The delay here is one constant for all hosts. In a real crawler the delay is per host and comes from several sources:
| Source | Example | Notes |
|---|---|---|
| Crawler default | 1 second | Safe starting point for unknown hosts. |
| `Crawl-delay` in robots.txt | `rp.crawl_delay(agent)` | Not part of the original standard. Some sites use it and some crawlers ignore it. |
| Observed response time | 10 times the last fetch duration | Slows down automatically when a server is struggling. |
| HTTP 429 or 503 with `Retry-After` | Header value in seconds | A direct request from the server to back off. |
To support this, make delay a function of the host, such as self.delay_for(host), and update it as responses arrive. The next_time assignment in next() is the single place to apply it.
Adding priority
FIFO order inside each host queue means the frontier is breadth-first for each site. Often you want some URLs ahead of others: fresh news pages, shallow pages, or pages with many inbound links. Two common ways to add priority:
- Priority queue per host. Replace each
dequewith a heap keyed by a score. The cost is more bookkeeping per URL. - Front queues by priority, back queues by host. The Mercator crawler design uses this. URLs first go into a few priority queues, and a selector moves them into per-host back queues. This keeps the politeness logic separate from the priority logic.
Start without priority. Add it once you have a measurable reason, such as a crawl budget too small to cover the whole site.
Edge cases and failure modes
- Hosts with a very large backlog. One host with a million queued URLs holds a deque of a million entries. This is fine for memory, but at a 1 second delay that host takes about 11 days. Pair the frontier with page budgets per host (see the chapter on crawl traps).
- Many tiny hosts. The heap handles any number of hosts, but
queuesandnext_timegrow without bound because entries are never deleted. If a crawl touches millions of hosts, remove empty queues and expire oldnext_timevalues. - The
seenset grows forever. It stores every URL ever added, including fetched ones. At around 100 bytes per URL in Python, 50 million URLs need several gigabytes. Later chapters cover compact alternatives such as hashing URLs to fixed-size fingerprints, or a Bloom filter that accepts a small false-positive rate. - Marking URLs as seen at add time. This design marks a URL seen when it is queued, not when it is fetched. That prevents queuing duplicates. The cost is that a URL whose fetch fails is never re-queued unless you handle retries explicitly. A retry must call a separate method that bypasses
seen. - Sleeping inside
next(). This is correct for a single thread. With concurrent workers, a sleeping call holds up everyone who shares a lock. A concurrent frontier should return the wait time, orNone, instead of sleeping, so that workers can do other work. - Blocked
robots.txtURLs still consume a delay slot. In the crawl loop from the earlier chapter, a URL thatcan_fetchrejects has already updatednext_time. That wastes a little time. It is simple, and it is safe.
Checkpointing the frontier
The frontier is the crawl's state. If the process dies, the contents of queues, next_time, and seen are lost. The ready heap can be rebuilt from queues and next_time, so you only need to persist those three. A later chapter covers this. For now, design the class so its state is plain dictionaries, deques, and sets that serialize easily.
Exercise
In the Frontier class, add pushes onto the ready heap only when the host's queue is empty. What goes wrong if you remove that condition and push on every add?
Show answer
A host with several queued URLs would have several heap entries. next() would pop the same host more than once, and the extra entries would be serviced as if the host had several independent turns. After the queue empties, self.queues[host].popleft() would raise IndexError on a stale entry. The fix is the existing condition: one heap entry per host with a non-empty queue.
Exercise
A site's robots.txt declares Crawl-delay: 10, and your default is 1 second. Which change to the Frontier code applies the right delay, and which line is it?
Show answer
Replace the constant self.delay with a per-host value, for example a dictionary self.host_delay filled from rp.crawl_delay(agent) when the host's robots.txt is read, falling back to the default. Then the line self.next_time[host] = time.monotonic() + self.delay in next() becomes ... + self.host_delay.get(host, self.delay).