Sub topic 16
Scaling Out: Partitioning the Crawl Across Machines
This chapter assumes you have read the earlier chapters on the URL frontier, the seen set, and per-host politeness. It also assumes you can read short Python programs and know what a hash function is. The single-machine crawler you built has one frontier, one seen set, and one process that tracks delays. This chapter explains what breaks when you add machines, and how to split the work so it keeps working.
Why one machine stops being enough
A single crawler runs out of room in several places, and which one comes first decides your design.
- Bandwidth and CPU. Downloading, decompressing, and parsing HTML saturates a network link or a core.
- Memory. A seen set of hundreds of millions of URLs does not fit in one machine's RAM.
- Frontier size. The queues of discovered but unfetched URLs grow faster than the crawler drains them.
- Time. At one page per second per host, a large site takes weeks. Parallelism across hosts is the only way to finish sooner.
Threads or async I/O (see the concurrency chapter) help with the first item. They do not help with memory or with the limits of one network connection. For those you need several crawler nodes that each own part of the work.
The core question: who owns which URL?
Once there are several nodes, each URL must have exactly one owner. If two nodes both think they own a URL, you get duplicate fetches. If no node owns it, it is never fetched. Ownership also decides where the seen set entry and the frontier entry for that URL live.
You can partition by URL or by host. Partitioning by URL, for example hash(url) % N, spreads load evenly. It also breaks politeness, because pages from one host land on every node. Each node then applies its own delay, and the host receives N times the intended request rate.
Partitioning by host fixes this. Every URL from example.com goes to the same node, so that node alone enforces the delay, caches the robots.txt file, and tracks the host's error state. The cost is skew: one huge host can overload its node.
| Strategy | Politeness | Load balance | Seen set locality |
|---|---|---|---|
| Hash of full URL | Hard, needs coordination | Even | Scattered |
| Hash of host name | Natural, one node per host | Skewed by big hosts | All of a host's URLs together |
Most crawlers partition by host. The rest of this chapter assumes that.
Consistent hashing for host assignment
The simple rule hash(host) % N has a problem. When N changes, because a node is added or crashes, almost every host gets a new owner. Every node would then need to hand off most of its frontier and seen set.
Consistent hashing limits this. Each node is placed at many points on a circular hash space. A host is hashed onto the same circle and belongs to the first node point clockwise from it. When a node is added or removed, only the hosts in the arcs next to its points move.
import hashlib
from bisect import bisect_right
from urllib.parse import urlsplit
class HashRing:
def __init__(self, nodes, replicas=100):
self.ring = []
for node in nodes:
for i in range(replicas):
self.ring.append((self._hash(f'{node}#{i}'), node))
self.ring.sort()
self.keys = [point for point, _ in self.ring]
@staticmethod
def _hash(text):
digest = hashlib.sha1(text.encode('utf-8')).digest()
return int.from_bytes(digest[:8], 'big')
def node_for(self, host):
index = bisect_right(self.keys, self._hash(host)) % len(self.keys)
return self.ring[index][1]
def owner(ring, url):
return ring.node_for((urlsplit(url).hostname or '').lower())
hosts = [f'site{i}.example' for i in range(1000)]
before = HashRing(['node-a', 'node-b', 'node-c'])
after = HashRing(['node-a', 'node-b', 'node-c', 'node-d'])
moved = sum(1 for h in hosts if before.node_for(h) != after.node_for(h))
print(f'{moved} of {len(hosts)} hosts changed owner')
print(owner(after, 'https://site7.example/page'))Adding a fourth node moves roughly a quarter of the hosts, and all of them move to the new node. With hash(host) % N, about three quarters would move. The exact count varies a little, but it stays close to 1/N.
The many points per node (replicas) smooth out the load. With one point per node, arcs are uneven and one node may own most of the circle. Use SHA-1 or another stable hash. Python's built-in hash() for strings is randomized per process, so two nodes would disagree on ownership.
Routing discovered links between nodes
A node that parses a page finds links to hosts it may not own. It must forward those links to the owner instead of adding them to its own frontier.
def route(ring, my_node, url, local_frontier, send):
target = owner(ring, url)
if target == my_node:
local_frontier.add(url)
else:
send(target, url)Here send is a placeholder for your transport, such as a message queue topic per node or a batched network call. Two practical details matter:
- Batch the messages. Most links point to other hosts, so a crawl generates far more forwarded URLs than fetched pages. Sending them one by one makes network overhead the bottleneck. Buffer URLs per target and flush when the buffer is full or after a short interval.
- Deduplicate before sending. Many links on a page point to well-known hosts such as a social site. A small local cache of recently forwarded URLs removes much of that traffic.
The receiving node checks its own seen set. Because it owns the host, its seen set is the authoritative record for that host's URLs, and no global seen set is needed.
What each node keeps locally
With host-based partitioning, a node holds its own state and shares almost nothing:
- A frontier covering only its hosts, using the per-host queue and heap design from the frontier chapter.
- A seen set for URLs on its hosts.
- A robots.txt cache for its hosts.
- Its own checkpoint of the frontier and seen set (see the storage chapter).
Because the nodes share no mutable state, a node can be restarted from its own checkpoint without coordinating with the others. This is the main reason host partitioning is popular.
Failures and rebalancing
Nodes will fail, and the ring needs a way to change.
- Detect the failure. Nodes send heartbeats to a coordinator such as ZooKeeper or etcd, or to a simple membership service.
- Update the ring. All nodes must switch to the new ring around the same time. Brief disagreement causes two nodes to fetch one host at once, which breaks politeness for a few seconds. Use a version number on the ring and have nodes reject forwarded URLs for hosts they no longer own, re-forwarding them.
- Recover the state. The failed node's frontier is lost unless it was checkpointed to shared storage. Lost frontier entries can be rediscovered by recrawling from seeds, which costs time but not correctness. A lost seen set causes duplicate fetches, which wastes bandwidth.
- Hand off on planned changes. When adding a node, the previous owners send the moved hosts' frontier and seen entries to the new node before the ring switches.
Many crawlers accept some duplicate work after a failure. A crawl is usually approximate, and exact once-only delivery is expensive.
Skew and hot hosts
Some hosts are far larger than others. A node that owns a large forum or news site may fall behind while other nodes idle. Mitigations include:
- Adding more ring points for nodes with more capacity.
- Splitting very large hosts by a prefix of the path, which is safe only if the whole group still shares one rate limit.
- Capping the pages per host, which also protects against crawl traps.
Politeness limits how much a node can speed up on one host anyway. If a host allows one request per second, giving it more machines does not make it finish sooner.
Keeping the crawl fresh at scale
Recrawl scheduling also benefits from host ownership. The node that owns a host stores when each page was last fetched and whether it changed, so it can schedule revisits locally. The node does not need to ask any other machine whether a page is due.
Exercise
A crawler uses hash(url) % 4 to assign URLs to four nodes. The crawl delay for a site is one second, but the site's operator reports about four requests per second from your crawler. Why does this happen, and what change fixes it?
Show answer
URLs from the same host are spread across all four nodes, and each node applies its own one-second delay independently, so the host receives about four requests per second. Partition by host (hash the host name instead of the full URL) so that one node owns each host and alone enforces its delay.
Exercise
Why does consistent hashing help when you add a fifth node to a crawl of four nodes, compared with hash(host) % N?
Show answer
With % N, changing N from 4 to 5 changes the owner of most hosts, so most frontier and seen set state must move. With consistent hashing, only the hosts in the arcs taken by the new node's points move, roughly one fifth of the hosts, and they all move to the new node.