Design a Web Crawler
A web crawler starts from a set of seed URLs, downloads pages, extracts their links and repeats, building a copy of (a part of) the web for a search engine, an archive or a dataset. Fetching one page is trivial; crawling billions politely, without loops, duplicates or getting banned, is a real distributed system.
1. Requirements
Functional
- Given seed URLs, crawl HTML pages, extract links and store page content for indexing.
- Re-crawl pages periodically (popular pages more often).
Non-functional
- Scale: 1 billion pages per month.
- Politeness: respect
robots.txtand never hit one host with more than ~1 request per second. - Robustness: survive malformed HTML, slow servers, crawler traps (infinite calendars, session ids in URLs).
- Don't store the same content twice.
2. Estimates
pages_per_month = 1_000_000_000
avg_page_kb = 100
seconds = 30 * 86_400
fetch_seconds = 0.5 # average time to download one page
qps = pages_per_month / seconds
concurrency = qps * fetch_seconds # Little's law: requests in flight
storage_tb = pages_per_month * avg_page_kb * 1_000 / 1e12
bandwidth_mbps = qps * avg_page_kb * 1_000 * 8 / 1e6
print(f"fetch rate: {qps:,.0f} pages/s ({2 * qps:,.0f}/s at peak)")
print(f"concurrent fetches needed: {concurrency:,.0f}")
print(f"raw storage per month: {storage_tb:,.0f} TB (compressed ~{storage_tb / 4:,.0f} TB)")
print(f"download bandwidth: {bandwidth_mbps:,.0f} Mbit/s")fetch rate: 386 pages/s (772/s at peak)
concurrent fetches needed: 193
raw storage per month: 100 TB (compressed ~25 TB)
download bandwidth: 309 Mbit/s
3. High-level design
seeds -> [ URL frontier ] -> [ fetchers ] -> [ parser ] -> [ content dedup ] -> [ storage ]
^ (per-host | DNS cache | (object store)
| queues, | robots.txt v
| priorities) | cache [ link extractor ] -> normalise -> [ URL seen? ]
+-------------------------------------------------------------- new URLs ----+| Component | Job |
|---|---|
| URL frontier | Decides what to fetch next: priority (important pages first) and politeness (per-host queues and delays) |
| Fetchers | Thousands of async HTTP workers with timeouts, a DNS cache and a robots.txt cache |
| Parser / link extractor | Parses HTML, extracts and normalises URLs (lowercase host, remove fragments, resolve relative links) |
| URL seen? | A Bloom filter / hash set of every URL already queued |
| Content dedup | A hash (or SimHash for near-duplicates) of each page's content |
4. A crawler over a fake web
The simulation below crawls an in-memory "web" (no network access), with breadth-first order, URL normalisation, a seen set, content dedup and a per-host politeness delay on a simulated clock:
from collections import deque
from urllib.parse import urljoin, urldefrag, urlsplit
import hashlib
WEB = { # url -> (content, links)
"https://a.example/": ("Home of A", ["/about", "/blog", "https://b.example/"]),
"https://a.example/about": ("About A", ["/", "/about#team"]),
"https://a.example/blog": ("Blog index", ["/blog/1", "/blog/2"]),
"https://a.example/blog/1": ("Post one", ["/blog"]),
"https://a.example/blog/2": ("Post one", ["/blog"]), # duplicate content
"https://b.example/": ("Home of B", ["/shop", "HTTPS://A.EXAMPLE/about"]),
"https://b.example/shop": ("Shop", []),
}
POLITENESS = 1.0 # seconds between requests to the same host
def normalise(base, link):
url, _ = urldefrag(urljoin(base, link))
parts = urlsplit(url)
return f"{parts.scheme.lower()}://{parts.netloc.lower()}{parts.path or '/'}"
frontier = deque(["https://a.example/"])
seen_urls = {"https://a.example/"}
seen_content = set()
next_allowed = {} # host -> earliest time we may fetch it again
clock = 0.0
while frontier:
url = frontier.popleft()
host = urlsplit(url).netloc
clock = max(clock, next_allowed.get(host, 0.0))
next_allowed[host] = clock + POLITENESS
content, links = WEB[url]
digest = hashlib.sha1(content.encode()).hexdigest()
status = "duplicate content, not stored" if digest in seen_content else "stored"
seen_content.add(digest)
print(f"t={clock:3.1f} fetch {url:<26} {status}")
for link in links:
absolute = normalise(url, link)
if absolute not in seen_urls:
seen_urls.add(absolute)
frontier.append(absolute)
print("unique URLs:", len(seen_urls), "| unique pages stored:", len(seen_content))t=0.0 fetch https://a.example/ stored
t=1.0 fetch https://a.example/about stored
t=2.0 fetch https://a.example/blog stored
t=2.0 fetch https://b.example/ stored
t=3.0 fetch https://a.example/blog/1 stored
t=4.0 fetch https://a.example/blog/2 duplicate content, not stored
t=4.0 fetch https://b.example/shop stored
unique URLs: 7 | unique pages stored: 6
Normalisation collapsed /about#team and HTTPS://A.EXAMPLE/about into URLs already seen, and the content hash caught the copied blog post. Notice how the politeness delay makes the single-threaded crawler wait for host a.example. A real frontier keeps many hosts in flight at once so that waiting on one never idles the fetchers.
5. The frontier: priority and politeness
The classic design (from the Mercator crawler) has two layers of queues:
- Front queues by priority: a URL's priority comes from PageRank-like importance, how often the page changes, or whether it's a seed. Higher-priority queues are picked more often.
- Back queues by host: each back queue holds URLs of one host, and a heap records when each host may be contacted next. A fetcher takes the host whose time has come.
import heapq
host_queues = {
"a.example": ["/1", "/2", "/3"],
"b.example": ["/x", "/y"],
"c.example": ["/only"],
}
delay = {"a.example": 1.0, "b.example": 2.0, "c.example": 1.0} # from robots.txt crawl-delay
ready = [(0.0, host) for host in host_queues] # (time host is available, host)
heapq.heapify(ready)
schedule = []
while ready:
t, host = heapq.heappop(ready)
path = host_queues[host].pop(0)
schedule.append(f"t={t:3.1f} {host}{path}")
if host_queues[host]:
heapq.heappush(ready, (t + delay[host], host))
print("\n".join(schedule))
print("6 pages fetched by t =", t)t=0.0 a.example/1
t=0.0 b.example/x
t=0.0 c.example/only
t=1.0 a.example/2
t=2.0 a.example/3
t=2.0 b.example/y
6 pages fetched by t = 2.0
Three hosts are crawled in parallel, each at its own polite pace. With millions of hosts, the fetchers are never idle even though each host sees at most one request per second or so.
6. Deduplicating at scale
- URL seen? With billions of URLs, an exact set is large (~100 GB). A Bloom filter at 1% false positives needs ~1.2 GB per billion URLs; a false positive just means a page is skipped.
- Content dedup: exact hashes catch identical pages; SimHash fingerprints catch near-duplicates (same article with a different ad block) by comparing the number of differing bits.
Crawler traps and robustness
| Trap | Defence |
|---|---|
Infinite calendars, ?page= loops |
Max depth per host, max URLs per host, URL length limit |
| Session ids in URLs | Strip known tracking/session parameters during normalisation |
| Slow servers ("tarpits") | Strict connect/read timeouts, max page size |
| Spam / link farms | Priority based on reputation; don't follow everything |
Duplicate hosts (www. vs bare) |
Canonical host mapping, rel=canonical |
Test yourself
What is the purpose of per-host back queues in the URL frontier?
- To sort URLs alphabetically
- To enforce politeness: one host is contacted at most at its allowed rate while other hosts are crawled in parallel
- To store page content
- To compute PageRank
Why normalise URLs before checking whether they were seen?
- To make them shorter
- Different spellings of the same URL (case, fragments, relative paths) would otherwise be crawled repeatedly
- Browsers require it
- To encrypt them
Why is a Bloom filter a good fit for the 'URL seen?' check?
- It never makes mistakes
- It is very compact, and its rare false positives only cause a page to be skipped
- It can list all URLs
- It supports deleting URLs