Courses / System Design Interview / Chapter 35
Module 8 · Design Problems III: Links, Crawling and Collaboration · Chapter 35 of 49
Design a Web Crawler
Builds on Non-Functional Requirements: Availability, Scale, Latency and More, Back-of-the-Envelope Estimates, Design a Distributed Key-Value Store, Distributed Message Queues, Blob Stores, Distributed Task Schedulers and Design a Q&A Platform like Quora. Next up: Design a Messaging App like WhatsApp.
Part 1 · Requirements and estimates
What the crawler must do
A web crawler visits pages, follows their links and stores what it finds, so a search engine or an archive can work from a copy of the web instead of the web itself. This chapter designs a crawler that stays polite to the sites it visits and keeps running when those sites misbehave.
The functional requirements are short. Start from a list of seed URLs, fetch each page, extract the links it contains, add the new ones to the work to do, and store the page for later processing. Come back to a page after some time to see whether it changed. We leave out JavaScript rendering, ranking and building the search index: the crawler's output is a store of pages, and other systems read it.
The non-functional requirements carry the design. The crawler must be polite: it must never overload a site, and it must follow the rules a site publishes in its robots.txt file. It must be scalable, covering crores of pages a month by adding machines. It must survive bad input: pages with broken HTML, servers that never answer, and links that lead forever deeper into the same site. It should be extensible, so a new content type or a new filter does not mean a rewrite. And it should keep important pages fresher than unimportant ones.
A fast crawler and a polite crawler pull in opposite directions. Almost every decision in this chapter is a way of getting speed from many hosts while asking little from each one.
Estimating the crawl
The estimate below states each assumption as a named number, so you can change one and see what moves. The crawl is 50 crore pages a month, an average page is 100 KB of HTML, one fetch takes 0.8 seconds from DNS lookup to last byte, and the crawler runs twice as fast in its busy hours as on average. We also assume that text compresses about four to one, and that each page holds six links to other URLs.
import sys pages_per_month = 50 * 10**7 # 50 crore pages fetched each month seconds_per_month = 30 * 86_400 page_kb = 100 # average HTML size, an assumption # DNS + connect + download, an assumption fetch_seconds = 0.8 peak_factor = 2 # busy hours run at 2x average avg_rate = pages_per_month / seconds_per_month peak_rate = avg_rate * peak_factor bandwidth_mbps = peak_rate * page_kb * 1000 * 8 / 1e6 in_flight = peak_rate * fetch_seconds # Little's law: rate x time raw_tb = pages_per_month * page_kb * 1000 / 1e12 # assume text compresses about 4:1 stored_tb = raw_tb / 4 # each page links to many URLs urls_seen = pages_per_month * 6 url_bytes = 100 # one URL plus a few flags frontier_tb = urls_seen * url_bytes / 1e12 print(sys.version.split()[0]) print(f"pages per second, average : {avg_rate:,.0f}") print(f"pages per second, peak : {peak_rate:,.0f}") print(f"download bandwidth, peak : {bandwidth_mbps:,.0f} Mbps") print(f"fetches in flight : {in_flight:,.0f}") print(f"raw HTML per month : {raw_tb:,.1f} TB") print(f"compressed per month : {stored_tb:,.1f} TB") print(f"URLs seen per month : {urls_seen / 1e7:,.0f} crore") print(f"URL metadata per month : {frontier_tb:,.2f} TB")
Python 3.12.10. Assumptions are the first lines; change them and rerun.
3.12.10 pages per second, average : 193 pages per second, peak : 386 download bandwidth, peak : 309 Mbps fetches in flight : 309 raw HTML per month : 50.0 TB compressed per month : 12.5 TB URLs seen per month : 300 crore URL metadata per month : 0.30 TB
Output of the script.
The average is 193 pages a second and the peak is 386. Downloading at the peak takes about 309 Mbps, which a single ordinary network card can carry, so bandwidth is not the hard part. The number to notice is 309 fetches in flight. Little's law from the non-functional chapter turns 386 a second at 0.8 seconds each into 309. Slow sites push this number up, because each slow fetch holds a slot for longer.
What the numbers decide
The last two lines of the output matter more than they look. The crawler sees about 300 crore URLs a month, six for each page, but most of them are repeats of pages already seen. Even keeping only a 32-byte hash of each URL, 300 crore of them is 96 GB, more memory than each fetcher machine should spare, and the set grows every month. Deciding quickly whether a URL is new is a design problem of its own, and the fifth lesson solves it with a compact probabilistic structure.
| Number | What it decides |
|---|---|
| 386 pages a second at peak | Many fetcher machines, each running hundreds of concurrent fetches |
| 309 fetches in flight | Fetchers must be asynchronous, with a timeout on every request |
| 50 TB of HTML a month | Page bodies go to a blob store, compressed, with metadata kept separately |
| 300 crore URLs seen a month | A compact seen-check is needed, and the frontier must live on disk |
Notice what the estimate does not say: nothing in it limits how many pages one site receives. That limit is not a throughput number at all. It is a promise the crawler makes to each site, and the third lesson builds it into the queue.
Why does the crawler need hundreds of concurrent fetches when it only fetches 386 pages a second?
- Each fetch takes time, and Little's law says requests in flight equal rate times time per request. At 0.8 seconds each, 386 a second keeps about 309 fetches open at once.
Why store page bodies in a blob store instead of a database?
- The crawl adds about 12.5 TB a month compressed, written once and read in bulk. A blob store is built for that, and the database keeps only small metadata such as URL, state and content hash.
Part 2 · Components and data model
The parts of a crawler
A crawler is a loop with a memory. It takes a URL from the work list, fetches the page, pulls out links, drops the ones it has already seen, and puts the rest back on the work list. Each step in that loop becomes a component, and each component can be scaled on its own.
| Component | Job | Scales by |
|---|---|---|
| URL frontier | Holds URLs still to fetch and decides which one comes next | Partitioning hosts across machines |
| Fetcher workers | Resolve the host, respect robots.txt, download the page | Adding workers; each is asynchronous |
| DNS cache | Avoids a lookup for every URL on the same host | Per-worker cache over a shared resolver |
| Parser | Extracts links and text from the downloaded page | Stateless, so add more |
| Seen filter | Answers whether a URL or a page body was already crawled | Partitioning by URL hash |
| Page store | Keeps the downloaded content | The blob store scales by adding nodes |
| Recrawl scheduler | Decides when a stored page is due again | Reads the URL table by due time |
The URL frontier is the part worth singling out. It is not a plain queue. A plain queue would hand out URLs in arrival order, and arrival order is poor: a page with 200 links to one site would put 200 requests for that site in a row. The frontier chooses the next URL by two rules at once, which URL matters most and which host has been left alone long enough. The next lesson builds it.
The tables
Two tables carry the state. The host table holds what is true for a whole site: the gap to leave between requests, and the cached robots.txt with the time it was fetched. The url table has one row per URL, keyed by a hash of its normalised form, with its state, depth, next fetch time and a hash of the last body. The script creates both with SQLite and then adds three URLs, one of them twice.
import hashlib import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE host ( host TEXT PRIMARY KEY, crawl_delay_ms INTEGER NOT NULL DEFAULT 1000, -- politeness gap robots_body TEXT, -- cached robots.txt robots_fetched_at INTEGER -- unix seconds ); CREATE TABLE url ( url_hash BLOB PRIMARY KEY, -- sha256 of the normalised URL url TEXT NOT NULL, host TEXT NOT NULL REFERENCES host(host), depth INTEGER NOT NULL, state TEXT NOT NULL DEFAULT 'queued' CHECK (state IN ('queued','fetching','done', 'failed','blocked')), next_fetch_at INTEGER NOT NULL, -- unix seconds content_hash BLOB, -- sha256 of the body fail_count INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX url_due ON url (state, next_fetch_at); CREATE INDEX url_host ON url (host, state); """)
Python 3.12.10, standard library. The primary key rejects a repeated URL. Part 1 of 2; save all parts in one file, wc2_schema.py.
def add(url, host, depth, now): db.execute("INSERT OR IGNORE INTO host(host) VALUES (?)", (host,)) cur = db.execute( "INSERT OR IGNORE INTO url" "(url_hash,url,host,depth,next_fetch_at) VALUES (?,?,?,?,?)", (hashlib.sha256(url.encode()).digest(), url, host, depth, now)) return cur.rowcount print(add("http://a.example.com/", "a.example.com", 0, 100)) # same URL again print(add("http://a.example.com/", "a.example.com", 0, 100)) print(add("http://a.example.com/x", "a.example.com", 1, 100)) print(add("http://b.example.com/", "b.example.com", 0, 90)) print("due first:") for row in db.execute("SELECT url, depth FROM url WHERE state='queued'" " ORDER BY next_fetch_at, depth LIMIT 2"): print(" ", row) print("queued per host:") for row in db.execute("SELECT host, COUNT(*) FROM url" " WHERE state='queued'" " GROUP BY host ORDER BY host"): print(" ", row)
Continues wc2_schema.py (part 2 of 2), same file.
1 0 1 1 due first: ('http://b.example.com/', 0) ('http://a.example.com/', 0) queued per host: ('a.example.com', 2) ('b.example.com', 1)
Output of the script.
The first call to add returns 1, which means a row was inserted. The second call, with the same URL, returns 0: the primary key on url_hash made INSERT OR IGNORE skip it. That is the simplest seen-check, and it is exact, but at 300 crore URLs a month the index behind it is the 96 GB problem from the previous lesson. The query for due work reads the url_due index, so b.example.com comes first because its next_fetch_at of 90 is earlier than 100.
Why these keys
A hash of the URL as the key keeps rows a fixed size, which matters when URLs can be thousands of characters long. Two URLs that differ only by capital letters in the host or by a #fragment must hash the same, so the hash is taken after normalisation, which the fifth lesson covers.
The frontier and the URL table are partitioned by host, not by URL. If every URL of a site lands on the same shard, that shard owns the site's politeness state: the last time it fetched, the host's gap, the cached robots.txt. No other machine needs to be asked before a request goes out. Choosing the shard is a hash of the host name onto a ring of machines, the same consistent hashing as in the key-value store chapter, so adding a machine moves only a fraction of the hosts.
State is a column with a small set of values: queued, fetching, done, failed and blocked. The CHECK constraint makes a typing mistake an error instead of a stuck row. A fetcher that dies leaves rows in fetching, so a periodic sweep returns old fetching rows to queued. The claim is a lease, as in the task scheduler chapter: a claim that expires unless it is renewed.
One more field earns its place: fail_count. A page that fails once is probably a blip, but a page that fails five times in a row should wait a long time before the next try. Without the counter, a dead host fills the front of the queue with requests that cannot succeed.
Why does INSERT OR IGNORE count as a seen-check, and what is its cost at scale?
- The primary key on the URL hash rejects a repeat, so only new URLs insert. It is exact, but the index holds every hash ever seen, which is about 96 GB for 300 crore URLs.
Why partition the frontier by host and not by URL?
- All the politeness state for a site, such as the last fetch time and robots.txt, then lives on one machine, and no coordination is needed before a request.
What does the sweep that returns old fetching rows to queued protect against?
Part 3 · The URL frontier and politeness
Why politeness is a requirement
A site has a limited number of connections and a limited amount of processing time for each visitor. A crawler that sends fifty requests a second to one small site can slow it down for real users, or take it down. Sites respond by blocking the crawler's addresses, which ends the crawl of that site for good. Politeness is the right thing to do, and it is also what keeps the crawler allowed to crawl.
The rule is simple to state: keep a minimum gap between two requests to the same host, and keep few connections open to it at once. The gap is a number chosen per host. We use a default of one second, and a site can ask for a longer one in robots.txt. A large site may tolerate a shorter gap, and a site the crawler sees slowing down deserves a longer one.
The difficulty is that a good gap is a per-host fact, while the crawler's work list mixes tens of lakhs of hosts. The structure that fits is one queue per host, plus a way to find which host is allowed next.
Front queues and back queues
The frontier has two layers. The front layer orders URLs by priority: a home page before a page nine links deep, a news site before a forgotten blog. The back layer is a set of FIFO queues, one per host, so URLs for the same site wait in line behind each other. A min-heap holds one entry per host that has work, ordered by the time that host is next allowed to be fetched.
To pick the next URL, take the host at the top of the heap. If its allowed time has not arrived, wait until it does. Then pop one URL from that host's queue, fetch it, and push the host back onto the heap with a time of now plus its gap, or drop it from the heap if its queue is empty. The heap makes the choice in logarithmic time even with tens of lakhs of hosts.
Because a host's time moves forward by its gap after each fetch, a host with a long queue cannot starve the others. Hosts take turns, and the crawler's total rate is the number of active hosts divided by the gap. With 386 pages a second and a one-second gap, the crawler needs at least 386 hosts active at the same moment. This is why the crawler spreads wide across the web and does not dig deep into one site.
The frontier in code
The script below runs a small site on a local port. The site serves any path, and it records when each request arrives, keyed by the Host header, so three names (a.test, b.test, c.test) look like three sites. It first fetches five pages from each host in a plain loop, then repeats with the frontier and a gap of 200 ms. The crawler is the Frontier class: a dictionary of deques and a heap of (ready time, host) pairs.
import heapq, threading, time, urllib.request from collections import defaultdict, deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = 55532 # host -> arrival times seen by the site arrivals = defaultdict(list) # hosts in the order the site saw them order = [] class Site(BaseHTTPRequestHandler): def do_GET(self): arrivals[self.headers["Host"]].append(time.perf_counter()) order.append(self.headers["Host"]) body = b"<html>ok</html>" self.send_response(200) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): pass server = ThreadingHTTPServer(("127.0.0.1", PORT), Site) threading.Thread(target=server.serve_forever, daemon=True).start()
Python 3.12.10, standard library. The site and the crawler run in one process on port 55532. Part 1 of 5; save all parts in one file, wc3_frontier.py.
def fetch(host, path): req = urllib.request.Request(f"http://127.0.0.1:{PORT}{path}", headers={"Host": host}) with urllib.request.urlopen(req) as r: return r.status
Continues wc3_frontier.py (part 2 of 5), same file.
class Frontier: """A FIFO queue per host and a heap of (ready time, host).""" def __init__(self, delay): self.delay = delay self.queues = defaultdict(deque) # hosts with work, by ready time self.heap = [] self.in_heap = set() def add(self, host, path): self.queues[host].append(path) if host not in self.in_heap: heapq.heappush(self.heap, (time.perf_counter(), host)) self.in_heap.add(host) def next(self): """Return (host, path) once the host is due, else None.""" if not self.heap: return None ready_at, host = self.heap[0] wait = ready_at - time.perf_counter() if wait > 0: time.sleep(wait) heapq.heappop(self.heap) return host, self.queues[host].popleft()
Continues wc3_frontier.py (part 3 of 5), same file.
def release(self, host): """Call after the fetch ends: the gap counts from here.""" if self.queues[host]: due = time.perf_counter() + self.delay heapq.heappush(self.heap, (due, host)) else: self.in_heap.discard(host) def gaps(host): t = arrivals[host] return [b - a for a, b in zip(t, t[1:])] hosts = ["a.test", "b.test", "c.test"] # 1. Naive: three hosts, five URLs each, no gap rule. for h in hosts: for i in range(5): fetch(h, f"/p{i}") naive = min(min(gaps(h)) for h in hosts) arrivals.clear() order.clear()
Continues wc3_frontier.py (part 4 of 5), same file.
One page through the crawler
Watch for only new links returning to the frontier
Read it as steps
A URL leaves the frontier, the page is fetched and stored, and only new links come back.
The scene follows one URL around the loop. The frontier is where politeness is enforced, and the seen filter is what keeps the loop from running over the same pages again and again.
A site has 10,000 queued URLs and a 1 second gap. How long does the crawler take to fetch them, ignoring fetch time?
- About 10,000 seconds, nearly three hours. The gap caps the rate for one host, so a deep queue for a single site drains slowly.
Why does the frontier keep a heap of hosts rather than scanning all queues?
- The heap finds the host that is ready soonest in logarithmic time. Scanning tens of lakhs of queues for each fetch would be too slow.
The run fetched 15 pages in 0.81 seconds with a 200 ms gap. Why was it not 3 seconds?
Part 4 · robots.txt and sitemaps
The robots exclusion protocol
A site tells crawlers where they may go with a text file at /robots.txt. The format has been used for decades and was written down as RFC 9309 in September 2022. A file holds groups: each starts with one or more User-agent lines naming a crawler, followed by Allow and Disallow lines giving path prefixes. A group for * applies to any crawler with no group of its own. Crawlers match the product token without regard to letter case.
| Rule in RFC 9309 | What a crawler does |
|---|---|
| Most specific match wins | Of the Allow and Disallow lines that match a path, the one with the most characters decides, whatever the order in the file |
| Cache for at most 24 hours | A crawler should not use a cached copy longer than a day, unless the file is unreachable |
| Parse at least 500 KiB | A crawler may stop reading after its limit, which must be at least 500 KiB |
| 4xx response (unavailable) | The crawler may access any resource on the site |
| 5xx response (unreachable) | The crawler must assume complete disallow |
The RFC does not define a Crawl-delay line. Some crawlers honour it and some ignore it, and our frontier treats it as the host's gap when present. The file is also a courtesy protocol: it does not stop a bad crawler, it tells a good one what the site owner wants. Anything private needs real access control as well.
Checking the rules with real code
Python ships a parser in urllib.robotparser. The script serves a robots.txt from a local site and asks the parser whether four paths may be fetched by two crawler names. It then serves the same path with different status codes, to see what the parser does with a missing, forbidden or broken file, and finally swaps the order of two rules to test the "most specific match" rule.
import threading, urllib.robotparser import xml.etree.ElementTree as ET from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = 55532 ROBOTS = """\ User-agent: * Disallow: /private/ Allow: /private/press/ Crawl-delay: 2 User-agent: newsbot Disallow: / Sitemap: http://127.0.0.1:55532/sitemap.xml """ SITEMAP = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>http://127.0.0.1:55532/</loc> <lastmod>2026-11-01</lastmod></url> <url><loc>http://127.0.0.1:55532/news/1</loc> <lastmod>2026-11-20</lastmod></url> <url><loc>http://127.0.0.1:55532/news/2</loc></url> </urlset>"""
Python 3.12.10, standard library. A local site on port 55532 serves robots.txt and a sitemap. Part 1 of 4; save all parts in one file, wc4_robots.py.
class Site(BaseHTTPRequestHandler): def do_GET(self): code, body = 200, "" if self.path == "/ok/robots.txt": body = ROBOTS elif self.path == "/sitemap.xml": body = SITEMAP elif self.path == "/missing/robots.txt": code = 404 elif self.path == "/forbidden/robots.txt": code = 403 elif self.path == "/broken/robots.txt": code = 500 data = body.encode() self.send_response(code) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *a): pass server = ThreadingHTTPServer(("127.0.0.1", PORT), Site) threading.Thread(target=server.serve_forever, daemon=True).start() def parser_for(case): rp = urllib.robotparser.RobotFileParser( f"http://127.0.0.1:{PORT}/{case}/robots.txt") rp.read() return rp
Continues wc4_robots.py (part 2 of 4), same file.
rp = parser_for("ok") base = f"http://127.0.0.1:{PORT}" checks = [("crawler", "/news/1"), ("crawler", "/private/a"), ("crawler", "/private/press/x"), ("newsbot", "/news/1")] for agent, path in checks: ok = rp.can_fetch(agent, base + path) print(f"{agent:8} {path:18} allowed={ok}") print("crawl-delay for crawler:", rp.crawl_delay("crawler")) print("sitemaps:", rp.site_maps()) print("robots.txt status -> can fetch /page?") for case in ("missing", "forbidden", "broken"): ok = parser_for(case).can_fetch("crawler", base + "/page") print(f" {case:10}", ok) # Longest match (RFC 9309) against Python's first-match order. rules = "User-agent: *\nAllow: /private/press/\nDisallow: /private/\n" a = urllib.robotparser.RobotFileParser(); a.parse(rules.splitlines()) rules2 = "User-agent: *\nDisallow: /private/\nAllow: /private/press/\n" b = urllib.robotparser.RobotFileParser(); b.parse(rules2.splitlines()) print("allow first :", a.can_fetch("crawler", "/private/press/x")) print("disallow first:", b.can_fetch("crawler", "/private/press/x"))
Continues wc4_robots.py (part 3 of 4), same file.
Where the library and the RFC differ
Two lines of the output disagree with RFC 9309, and they are the reason to test a library before trusting it. First, /private/press/x was not allowed although the file has Allow: /private/press/, which is longer than Disallow: /private/. Python's parser applies the first rule that matches, in file order, as the last two output lines show: with the Allow line first it says True, and with the Disallow line first it says False. The RFC says the longest match wins in both cases. A crawler built on this parser would skip pages the site allows.
Second, a 403 for robots.txt made the parser answer False for everything, but the RFC puts every 4xx in the unavailable class, where the crawler may access any resource. A 404 gave True, as the RFC says, and the 500 gave False, which matches the RFC, but only by luck: the parser has no rule for 5xx, it simply never marked the file as read, and an unread parser answers False. A production crawler should write its own small matcher that implements longest match and treat 403 as the RFC does. A 403 may also mean the site is blocking this crawler on purpose, so a crawler may reasonably choose to be cautious. The point is to make that choice deliberately.
The crawler fetches robots.txt once per host, caches it in the host table from the second lesson with its fetch time, and refreshes it after at most a day. The fetcher checks the cache before every request. A host whose robots.txt is slow or failing gets a longer gap, so the crawler does not hammer it while it recovers.
Sitemaps
A sitemap is the opposite of robots.txt: a site's own list of the URLs it wants crawled. It is an XML file with a urlset element, one url per page, a required loc and an optional lastmod date. A single file may hold at most 50,000 URLs and 50 MB uncompressed. A sitemap index lists up to 50,000 sitemap files, so large sites fit. The robots.txt file can point to the sitemap with a Sitemap: line, which is how our script found it.
The last three lines of the output are the sitemap parsed with xml.etree. A sitemap is useful to a crawler in two ways. It names pages that no link leads to, and lastmod tells the recrawl scheduler which pages changed without fetching them. Treat lastmod as a hint, since sites can set it wrongly, and never as a command.
A robots.txt has Disallow: /a/ and Allow: /a/b/. May a crawler fetch /a/b/page, and which rule decides?
- Yes. Under RFC 9309 the most specific match, the one with the most characters, decides, so the Allow line wins. Python's parser may disagree when the Disallow line comes first.
The robots.txt request returns a 500. What may the crawler do?
- It must assume everything is disallowed and try again later. A 500 means the file is unreachable, not absent.
Why is the sitemap useful even for a site that is fully linked?
- Its lastmod dates let the scheduler find changed pages without fetching all of them, and it names pages that no link reaches.
Part 5 · De-duplication
Normalising URLs first
The same page can be written as many URLs. HTTP://Example.COM:80/a?b=2&a=1#top and http://example.com/a?a=1&b=2 are one page, and a crawler that treats them as two will fetch and store it twice. Before any seen-check the crawler normalises each URL to one canonical form: lower-case the scheme and host, drop the port when it is the default for the scheme (80 for http, 443 for https), drop the #fragment because the server never sees it, sort the query parameters, and give an empty path the value /.
There is a limit to what normalisation may do. Sorting query parameters is safe only if the site treats them as a set, and dropping a www. prefix is a guess. Rules that are always safe go in the code, and anything site-specific, such as a session id in the query, is learned per host or handled by content hashing below. The first lines of the output further down show eight inputs. The first two become the same string. The next ones are the bad cases we tried: a blank query value is kept (x= is not the same as no x), port 80 on an https address is not a default and stays, an IPv6 address keeps its brackets, and a port out of range or a non-web scheme such as mailto: returns None, which the caller treats as a link to skip. A version that dropped every port 80, or dropped blank values, would have merged different pages.
A Bloom filter for URLs seen
The 300 crore URLs a month from the first lesson cannot all sit in memory as hashes. The key-value store chapter used a Bloom filter to skip files that cannot hold a key. Here it is again with its arithmetic. It answers the question "have I seen this?" in a fraction of the space, in return for a small chance of a wrong yes. It is an array of m bits and k hash functions. To add an item, hash it k ways and set those k bits. To test an item, hash it the same way and check that all k bits are set. If any bit is clear, the item was never added: a Bloom filter has no false negatives. If all are set, the item was probably added, but other items may have set those same bits by chance.
The chance of a false positive can be derived. After n items are added, each bit is still zero with probability about e^(-kn/m), because each of the kn settings misses it with probability 1 - 1/m. A false positive needs all k bits of a new item to be set, so the rate is (1 - e^(-kn/m))^k. The best k for a given m and n is (m/n) ln 2. With 10 bits per item that is 7 hash functions.
For a crawler, a false positive means a new URL is wrongly believed seen and is never fetched. That is a small loss. A false negative would mean fetching a page twice, which the filter never causes. At 10 bits per URL, 300 crore URLs need 3.75 GB, against 96 GB of exact hashes, and the filter can be split by URL hash across the frontier shards. The filter cannot delete or list its contents, so the exact url table stays the record of truth and the filter sits in front of it as a fast first test.
Measuring the filter and near-duplicate pages
The script builds a filter for 1 lakh URLs at 10 bits each, checks that every inserted URL is found, tests 1 lakh URLs never inserted, and compares the false positive count with the formula. It also computes a simhash, a 64-bit fingerprint of page text. Each three-word shingle (a run of three consecutive words, the same idea as in the qa platform chapter) is hashed, every bit position votes up or down, and the sign of each vote gives one bit. Pages with mostly the same text give fingerprints that differ in only a few bits, so the Hamming distance (the count of differing bits) measures how alike two pages are.
import hashlib, math, re from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode def normalise(url): p = urlsplit(url) scheme = p.scheme.lower() try: port = p.port except ValueError: return None # port out of range if scheme not in ("http", "https") or not p.hostname: return None host = p.hostname.lower() # also drops user:password@ if ":" in host: host = f"[{host}]" # an IPv6 address default = 80 if scheme == "http" else 443 netloc = host + (f":{port}" if port and port != default else "") q = urlencode(sorted(parse_qsl(p.query, keep_blank_values=True))) # drop #fragment return urlunsplit((scheme, netloc, p.path or "/", q, ""))
Python 3.12.10, standard library. The URLs and sample texts are made up. Part 1 of 4; save all parts in one file, wc5_dedupe.py.
for u in ["HTTP://Example.COM:80/a?b=2&a=1#top", "http://example.com/a?a=1&b=2", "http://example.com", "https://example.com:443/a?x=&y=1", "https://example.com:80/a", "http://[::1]:8080/", "http://example.com:99999/", "mailto:asha@example.com"]: print(f"{u:38} -> {normalise(u)}") class Bloom: def __init__(self, m_bits, k): self.m, self.k = m_bits, k self.bits = bytearray((m_bits + 7) // 8) def _positions(self, item): d = hashlib.sha256(item.encode()).digest() h1 = int.from_bytes(d[:8], "big") h2 = int.from_bytes(d[8:16], "big") | 1 return [(h1 + i * h2) % self.m for i in range(self.k)] def add(self, item): for p in self._positions(item): self.bits[p >> 3] |= 1 << (p & 7) def __contains__(self, item): return all(self.bits[p >> 3] >> (p & 7) & 1 for p in self._positions(item))
Continues wc5_dedupe.py (part 2 of 4), same file.
n = 100_000 bits_per_item = 10 m = n * bits_per_item k = round(bits_per_item * math.log(2)) bf = Bloom(m, k) for i in range(n): bf.add(f"http://example.com/page/{i}") missed = sum(f"http://example.com/page/{i}" not in bf for i in range(n)) false_pos = sum(f"http://example.com/other/{i}" in bf for i in range(n)) theory = (1 - math.exp(-k * n / m)) ** k kib = m // 8 // 1024 print(f"bits per URL {bits_per_item}, hashes {k}, filter {kib} KiB") print(f"inserted URLs reported missing: {missed}") print(f"false positives: {false_pos} of {n} = {false_pos / n:.4%}") print(f"formula (1 - e^(-kn/m))^k = {theory:.4%}") print("set of the same URLs, bytes of strings alone:", sum(len(f"http://example.com/page/{i}") for i in range(n))) def simhash(text, bits=64): words = re.findall(r"\w+", text.lower()) shingles = [" ".join(words[i:i + 3]) for i in range(len(words) - 2)] v = [0] * bits for s in shingles: digest = hashlib.sha256(s.encode()).digest() h = int.from_bytes(digest[:8], "big") for b in range(bits): v[b] += 1 if h >> b & 1 else -1 return sum(1 << b for b in range(bits) if v[b] > 0)
Continues wc5_dedupe.py (part 3 of 4), same file.
Part 6 · Traps, limits and recrawl scheduling
Crawler traps
A crawler trap is a part of a site that generates an endless supply of new URLs. The classic one is a calendar page with a link to the next month, which has a link to the month after, with no end. Others are session ids appended to every link, filters that combine in any order, and relative links that grow a path segment each time (/a/b/a/b/a/b). Traps are mostly accidents, though some are deliberate. A crawler with no defence will spend its whole budget in one.
Because every trap URL is new, the seen filter does not help. The defences are limits. A depth limit stops following links after a fixed number of hops from the seed. A per-host page budget caps the pages taken from one site in a period. A URL length limit drops enormous URLs. A repeated segment check drops paths where one segment appears many times. None of these identifies a trap precisely. They bound the damage, and a log of which hosts hit a limit tells a person where to look.
A calendar trap in code
The local site serves /, a plain /about page, and /cal/YYYY/M, whose only link is to the next month. The crawler is a breadth-first loop with a depth for each URL and a safety budget of 200 fetches. It runs once with no depth limit and once with a limit of 3.
import re, threading, urllib.request from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer PORT = 55532 class Site(BaseHTTPRequestHandler): def do_GET(self): m = re.fullmatch(r"/cal/(\d+)/(\d+)", self.path) # a calendar with a "next month" link if m: y, mo = int(m[1]), int(m[2]) ny, nmo = (y + 1, 1) if mo == 12 else (y, mo + 1) body = f'<a href="/cal/{ny}/{nmo}">next month</a>' elif self.path == "/": body = ('<a href="/about">about</a> ' '<a href="/cal/2026/11">events</a>') else: body = "plain page" data = body.encode() self.send_response(200) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *a): pass
Python 3.12.10, standard library. Site and crawler share one process on port 55532. Part 1 of 3; save all parts in one file, wc6_traps.py.
server = ThreadingHTTPServer(("127.0.0.1", PORT), Site) threading.Thread(target=server.serve_forever, daemon=True).start() BASE = f"http://127.0.0.1:{PORT}" def crawl(max_depth, budget): seen, queue, fetched = {"/"}, deque([("/", 0)]), 0 deepest = 0 while queue and fetched < budget: path, depth = queue.popleft() html = urllib.request.urlopen(BASE + path).read().decode() fetched += 1 deepest = max(deepest, depth) if depth >= max_depth: continue for link in re.findall(r'href="([^"]+)"', html): if link not in seen: seen.add(link) queue.append((link, depth + 1)) return fetched, deepest, len(queue) print("no depth limit, safety budget 200 pages:", crawl(10**9, 200)) print("depth limit 3, budget 200 :", crawl(3, 200)) # Recrawl: halve the wait if the page changed, double it if not. def next_interval(interval, changed, lo=3600, hi=30 * 86_400): return max(lo, interval // 2) if changed else min(hi, interval * 2)
Continues wc6_traps.py (part 2 of 3), same file.
history = [False, False, False, True, True, False, True, False, False, False] interval = 86_400 for i, changed in enumerate(history, 1): interval = next_interval(interval, changed) hours = interval / 3600 print(f"visit {i:2} changed={changed!s:5} next in {hours:6.1f} h") server.shutdown()
Continues wc6_traps.py (part 3 of 3), same file.
Deciding when to come back, and the design in short
A crawl is never finished, because pages change. Fetching everything again on a fixed cycle wastes effort on pages that never change and misses news pages that change by the hour. The recrawl scheduler gives each URL its own interval, stored as next_fetch_at. The simple adaptive rule, shown in the second half of the script, halves the interval when the page changed since the last visit and doubles it when it did not, within a lower and an upper bound.
The bottom of the output shows ten visits. Starting at 24 hours, three unchanged visits stretch the wait to 192 hours. A change halves it to 96, and a second change to 48. The interval follows the page's real rhythm without anyone setting it. The sitemap's lastmod and the HTTP ETag or Last-Modified headers can make each visit cheaper: send them back with a conditional request, and an unchanged page returns 304 Not Modified with no body.
Priority should also shape the schedule. A page with many links pointing at it, or one a user asked for, deserves a shorter bound than an orphan page on a small site. The scheduler turns that into a number: a base interval divided by an importance score.
To close the design: the frontier, the fetchers and the page store scale out by host, and the seen filter by URL hash. The durable state is the host and url tables, so a crashed worker loses only the URLs it had claimed, and the sweep returns those to the queue. Extensions follow the same shape. Rendering JavaScript adds a heavier fetcher type and a separate, slower queue. A new content type, such as PDFs, adds a parser and changes nothing else. The trade-off at the centre never goes away: more speed asks for more hosts at once, and each host sets its own limit.
The seen filter does not stop a calendar trap. Why not, and what does?
- Every calendar URL is new, so the filter calls each one unseen. Limits stop it: a depth limit, a per-host budget and a cap on URL length.
A page was unchanged for three visits in a row. What does the adaptive rule do, and why?
- It doubles the interval each time, up to a bound. A page that does not change needs fewer visits, which frees fetch capacity for pages that do.
All chapters · Previous: Design a URL Shortener like TinyURL