Sub topic 7
The crawl frontier: deciding what to fetch next
This chapter assumes you know how a crawler fetches a page and extracts links, and that you have read the earlier chapters on URL normalization and robots.txt. You should be comfortable reading short Python snippets that use queues and heaps.
What the frontier is
The crawl frontier is the data structure that holds every URL a crawler knows about but has not fetched yet. It sits between URL discovery and the fetcher. Discovery adds URLs to it, and the fetcher takes URLs out. Everything the crawler does about ordering happens here.
The frontier answers two questions:
- Which URL is the most worth fetching right now?
- Is any URL on that list allowed to be fetched right now?
The first question is about priority. The second is about politeness, which the next chapter covers in detail. This chapter shows where both fit into one design.
The simplest frontier
The crawler in the earlier chapter used a deque and popleft(). That gives first-in, first-out order, which is breadth-first search. It is easy to reason about, and it tends to reach pages close to the seed first. It treats every URL as equally important, though. A link in the site footer and a link to a new article wait in the same line.
A frontier that supports priorities needs a different structure. A binary heap works well. The heap keeps the entry with the smallest key at the front, so a lower number means "fetch sooner".
import heapq
import itertools
class Frontier:
def __init__(self):
self._heap = []
self._seen = set()
self._counter = itertools.count()
def add(self, url, priority):
if url in self._seen:
return False
self._seen.add(url)
heapq.heappush(self._heap, (priority, next(self._counter), url))
return True
def pop(self):
_, _, url = heapq.heappop(self._heap)
return url
def __len__(self):
return len(self._heap)
frontier = Frontier()
frontier.add("https://example.com/archive/2019/post", 5)
frontier.add("https://example.com/guide", 1)
frontier.add("https://example.com/", 0)
frontier.add("https://example.com/guide", 0) # duplicate, ignored
while len(frontier):
print(frontier.pop())This prints https://example.com/, then /guide, then the archive post.
The counter in each heap entry breaks ties. Without it, two entries with the same priority would make Python compare the URL strings, and the order would depend on the text of the URLs instead of arrival order. The counter makes equal priorities come out in first-in, first-out order.
The _seen set has a side effect. The duplicate /guide at priority 0 is rejected, so the URL stays at priority 1. A URL's priority is fixed by whichever sighting came first. Real systems handle this by updating the priority when a better signal arrives, for example when a sitemap lists a URL that was first found in a footer link.
Deciding priority
A priority function turns signals about a URL into a number. Common signals are:
| Signal | Effect on priority | Why |
|---|---|---|
| Link depth from the seed | Deeper means lower | Shallow pages are usually more important |
| Number of known inbound links | More links mean higher | Widely linked pages tend to matter more |
| Listed in a sitemap with a recent `lastmod` | Higher | The site owner says it changed |
| Past change frequency of the page | More frequent means higher | Fresh content is worth a revisit |
| URL has never been fetched | Higher than a known stale URL | New content widens coverage |
| URL looks like a parameter or session variant | Lower | Likely a duplicate |
The weights are a policy decision. A news crawler might heavily favor change frequency. A crawler that builds a broad web snapshot might favor discovery of new hosts. No single formula is correct, and production crawlers tune these weights against measured outcomes such as how many fetched pages turn out to be new or useful.
You can fold the signals into one score with a weighted sum. Keep the function pure and cheap, because it runs for every discovered link, and a crawler may discover millions of links per hour.
Two levels: priority and politeness
A single priority heap cannot protect a website. Suppose the ten highest-priority URLs all belong to one host. The heap hands them to the fetcher back to back, and the host receives ten requests at once.
The standard fix splits the frontier into two layers:
- Front queues order URLs by priority across the whole crawl.
- Back queues hold one queue per host. A scheduler tracks when each host may next be contacted.
The fetcher asks the back-queue layer for the next host that is ready, then takes one URL from that host's queue. The sketch below shows only the back-queue layer.
import heapq
import time
from collections import deque
from urllib.parse import urlparse
class HostScheduler:
def __init__(self, delay=1.0):
self.delay = delay
self.queues = {}
self.next_ok = {}
self.scheduled = set()
self.ready = []
def add(self, url):
host = urlparse(url).netloc
self.queues.setdefault(host, deque()).append(url)
if host not in self.scheduled:
self.scheduled.add(host)
heapq.heappush(self.ready, (self.next_ok.get(host, 0.0), host))
def next_url(self):
if not self.ready:
return None
ready_time, host = heapq.heappop(self.ready)
wait = ready_time - time.monotonic()
if wait > 0:
time.sleep(wait)
url = self.queues[host].popleft()
self.next_ok[host] = time.monotonic() + self.delay
if self.queues[host]:
heapq.heappush(self.ready, (self.next_ok[host], host))
else:
self.scheduled.discard(host)
return url
scheduler = HostScheduler(delay=0.2)
for u in [
"https://a.example/1",
"https://a.example/2",
"https://b.example/1",
]:
scheduler.add(u)
while (url := scheduler.next_url()) is not None:
print(url)The output interleaves the hosts: a.example/1, b.example/1, then a.example/2 after the delay. The scheduler remembers next_ok even after a host's queue empties. That matters because a URL for the same host may arrive a moment later, and the delay must still apply.
The sketch ignores priority inside each host's queue. In a full design, a front-queue stage decides which URLs enter which host queue, and each host queue may itself be a small heap.
Filtering before enqueueing
Every URL passes some checks before it earns a slot in the frontier:
- Normalization. The URL is put into canonical form first, so
HTTP://Example.com/a#topandhttp://example.com/acount as one entry in the seen set. - Seen check. At web scale the seen set does not fit in a Python
set. Crawlers use Bloom filters or sharded key-value stores. A Bloom filter has false positives, so a small fraction of new URLs is wrongly treated as already seen. Crawlers accept that loss for the memory savings. - Scope rules. The crawler may be limited to certain hosts, URL patterns, or maximum depth.
- Robots rules. The crawler checks robots.txt, usually just before the fetch, because the rules can change while a URL waits in the queue.
Checking robots.txt at fetch time costs a lookup in a cached copy of the file. Checking only at enqueue time is cheaper, but it can send requests to paths that were disallowed after the URL was queued.
Failure modes
Crawler traps. Some sites generate unlimited URLs, such as a calendar with a "next month" link that never ends, or a search page that links to every combination of filters. A breadth-first crawler can fill the frontier with these URLs. Defenses include a depth limit, a cap on URLs per host, a cap on query-string length, and detection of repeating path segments like /a/b/a/b/a/b.
Starvation. If priority always favors a certain kind of URL, low-priority URLs may never be fetched while new high-priority URLs keep arriving. A common fix is to raise a URL's priority as it ages in the queue.
Hot hosts. A large site can account for most of the frontier. Without a per-host cap, one site crowds out the rest of the crawl.
Memory growth. The frontier grows faster than it shrinks, because each fetched page yields many links. Real crawlers keep the hot part of the frontier in memory and spill the rest to disk.
Lost state. If the crawler restarts and the frontier lived only in memory, all discovered URLs vanish. Persisting the frontier lets a crawl resume without rediscovering everything.
Trade-offs
Breadth-first order is simple and tends to find important pages early, but it ignores signals about change and importance. Pure priority ordering uses those signals, but it needs a score function and can cause starvation. The two-level design adds code and state, and it is the only one of the three that keeps the load on each host under control. Most real crawlers end up with it.
Exercise
A frontier holds 1,000 URLs. The top 200 by priority all belong to one small site. What goes wrong if the fetcher simply takes URLs in priority order, and how does a back-queue layer fix it?
Show answer
The fetcher would send 200 requests to one host in a row, which can overload it and get the crawler blocked. A back-queue layer keeps one queue per host and a "next allowed time" for each. The fetcher takes the next URL from a host that is ready, so requests to the small site are spread out while other hosts are fetched in between.
Exercise
In the Frontier class above, a URL is first added with priority 1 and then added again with priority 0. Which priority does it keep, and what would you change so the better priority wins?
Show answer
It keeps priority 1, because add returns early when the URL is already in _seen. To let the better priority win, store the best known priority per URL in a dictionary, push a new heap entry when a lower priority arrives, and skip stale heap entries when popping them (lazy deletion).