Lesson 34 of 38Case studies
Design a Web Crawler
Design a polite crawler for a billion pages a month: the URL frontier, DNS, Bloom filter dedupe, near-duplicates, spider traps, and recrawls.
Search engines, price trackers, SEO tools, archive projects, and the teams collecting training data for AI models all run crawlers. Fetching one page is a single HTTP request, which is why this question looks easy. The difficulty is everything around it at scale: never hammering one small website, never fetching the same page twice, not getting lost in a calendar that generates infinite pages, and deciding which of a few billion known URLs deserve a visit today. In the Web Scraping lesson you scraped one site carefully by hand. Here you design the machine that does it for the whole web.
Requirements
Functional
- Start from a list of seed URLs and discover new pages by following links.
- Fetch HTML pages, store the raw content, and hand it to downstream systems (indexing, analytics).
- Recrawl known pages so stored copies stay fresh.
Non-functional
- Scale: 1 billion pages a month.
- Politeness: obey
robots.txt, keep at most one connection per host, and leave a delay between requests. A crawler that knocks a small site over gets blocked and makes headlines. - Freshness: pages that change often are revisited often.
- Resilient to traps and junk: infinite URL spaces, duplicate content, huge files, and slow servers must not stall the crawl.
- Extensible: new content types or processing steps plug in without a redesign.
Out of scope: rendering JavaScript for every page (a separate, much more expensive headless browser tier for the few pages that need it), building the search index, and ranking.
Back-of-the-envelope numbers
| Quantity | Math | Result |
|---|---|---|
| Fetch rate | 1B pages / (30 × 86,400 s) | about 385 pages/s, plan for 1,000/s peak |
| Page size | average HTML | about 100 KB |
| Bandwidth | 385 × 100 KB | about 40 MB/s, roughly 300 Mbps |
| Raw storage | 1B × 100 KB | about 100 TB a month, about 25 TB compressed |
| Links found | 1B pages × about 50 links | about 50B link extractions a month, mostly duplicates |
| Seen-URL set | 10B URLs × 100 bytes as a plain set | about 1 TB, too big for RAM |
The last row is the one that shapes the design. Checking "have I seen this URL?" happens 50 billion times a month, it has to be fast, and an exact set of every URL does not fit in memory. That is the job for a Bloom filter, which the back-of-the-envelope lesson's habit of sizing things first makes obvious.
Also notice that 385 pages a second is not the hard part. A few machines can fetch that. The hard part is that each host can only take a request every few seconds, so you need thousands of hosts in flight at once to reach that rate.
API and interfaces
A crawler has few public endpoints. Its interfaces are internal:
POST /v1/seeds { "urls": ["https://example.com/"], "priority": 5 }
GET /v1/urls/{url_hash} -> last fetch time, status, content hash, next due
GET /v1/hosts/{host} -> robots rules, crawl delay, budget used todayDownstream consumers read fetched pages from a stream (for example a Kafka topic pages.fetched carrying the URL, fetch time, status, and the object storage key for the body), not from the crawler's API.
Data model
urls (url_hash PK, url, host, depth, priority, last_fetched, last_status,
content_hash, simhash, change_count, next_due)
hosts (host PK, robots_txt, robots_fetched_at, crawl_delay_ms, ip,
pages_today, error_rate)URL rows are huge in number and accessed by key, so a wide-column or key-value store fits well. Raw pages go to object storage, usually packed many to a file in the WARC format, the standard archive format that Common Crawl and the Internet Archive use. Packing matters: a billion tiny objects a month costs far more in requests and metadata than a few thousand large files.
High-level design
Seed URLs enter the front queues. There is one queue per priority level; a news homepage gets a higher priority than page 900 of a forum.
Deep dive 1: the URL frontier and politeness
The frontier answers one question thousands of times a second: which URL should a fetcher take next? It balances two goals that pull against each other. Priority says fetch the most important URLs first. Politeness says never hit the same host too often. A single FIFO queue fails both: a site with a million links floods the queue, and the crawler hammers that one site while the rest of the web waits.
The classic answer, from the Mercator crawler, splits the frontier in two:
- Front queues handle priority. Score each URL (PageRank-like importance, how often the page changes, depth from the seed) and put it in one of, say, 10 priority queues. A selector pulls from them with a bias toward high priority, so low priority URLs still move.
- Back queues handle politeness. Each back queue contains URLs of one host only. A heap holds one entry per back queue: the earliest time that host may be contacted. A fetcher pops the heap, waits until that time, fetches one URL, and pushes the host back with
now + delay. When a back queue empties, the router refills it with a new host from the front queues.
The delay per host comes from robots.txt where a site sets Crawl-delay (a common extension, not part of the standard; Google ignores it), or from your own default, often a few seconds and scaled by how slowly the server responds. A host that answers in 3 seconds is telling you it is struggling.
robots.txt is now a standard, RFC 9309. Fetch it once per host and cache it. The RFC says crawlers should not use a cached copy for more than 24 hours. How you treat errors matters: if robots.txt returns a 4xx, you may crawl everything; if it returns a 5xx or cannot be reached, treat the whole site as disallowed until you can read it. That rule exists because a server returning 503 is overloaded, and the last thing it needs is you.
Deep dive 2: fetchers and DNS
A fetch spends nearly all its time waiting on the network, so fetchers use asynchronous I/O: one process with an event loop can hold thousands of connections open, as you saw with async code in Python and Node. A thread per connection would need thousands of threads per machine.
Each fetch needs guardrails:
- Timeouts for connect, for the first byte, and for the whole download. A server that sends one byte a second will otherwise hold a connection for hours.
- A size cap, a few megabytes for HTML. Stop reading beyond it.
- Content type checks. Skip videos and archives unless you want them; check the
Content-Typeheader before reading the body. - Redirect limits, about five, with loop detection.
- Conditional requests. On a recrawl, send
If-None-Matchwith the stored ETag orIf-Modified-Since. A304 Not Modifiedcosts almost no bandwidth.
DNS quietly becomes the bottleneck. Every new host needs a lookup, a lookup can take 10 to 200 ms, and many standard library resolvers are blocking calls. At thousands of hosts in flight, the shared upstream resolver starts throttling you. Run a caching resolver on each crawler machine, use an async DNS client, respect TTLs, and store the resolved IP with the host record. The IP also helps politeness: hundreds of small sites on one shared hosting server should share one politeness budget, because they share one machine.
Deep dive 3: deduplication, exact and near
There are two different duplicate problems: the same URL seen twice, and different URLs with the same content.
URL normalization comes first, so that equal URLs look equal. Lowercase the scheme and host, drop default ports and #fragments, resolve relative links, and strip known tracking parameters such as utm_source. Keep the path's case, because paths can be case sensitive.
What does this print?
from urllib.parse import urlsplit, urlunsplit
DEFAULT_PORTS = {"http": 80, "https": 443}
def normalize(url):
s = urlsplit(url)
scheme = s.scheme.lower()
host = s.hostname # already lowercased
netloc = host if s.port in (None, DEFAULT_PORTS[scheme]) else f"{host}:{s.port}"
return urlunsplit((scheme, netloc, s.path or "/", s.query, ""))
urls = [
"HTTP://Example.com/a#top",
"http://example.com:80/a",
"http://example.com/a?x=1",
"http://example.com/A",
]
print(len({normalize(u) for u in urls}))The seen filter. An exact set of 10 billion URLs is about a terabyte. A Bloom filter stores the same membership question in about 12 GB at a 1% false positive rate. It is a bit array of m bits and k hash functions. Adding a URL sets k bits. Checking a URL looks at those k bits: if any is 0, the URL is definitely new; if all are 1, it was probably seen. It can say "seen" for a URL it never saw (a false positive), but it never says "new" for a URL it did see.
For a crawler, that trade is good. A false positive means a few new URLs get skipped, about 1 in 100, and most pages are linked from many places, so they are usually found through another link or a sitemap. A false negative would mean fetching pages again forever, and Bloom filters never produce one.
The sizing formulas, for n items and target false positive rate p: m = -n ln p / (ln 2)^2 bits and k = (m / n) ln 2 hashes. At 1%, that is about 9.6 bits per item and 7 hashes. Run this and compare the measured rate with the theory.
Press Run (⌘ Enter) to see what happens.Two practical notes. A Bloom filter cannot delete items, and it fills up: insert more than n and the false positive rate climbs quickly. Size it for the URLs you expect plus headroom, or use one filter per time period and rebuild. And the filter only answers "seen?". The urls table is still the record of what was fetched and when.
Near-duplicate content. Many different URLs serve nearly the same page: printer versions, mirrors, pages that differ only in a date or an ad. An exact hash of the body misses these, because one changed byte changes the hash. SimHash builds a 64-bit fingerprint where similar documents get fingerprints that differ in only a few bits. Google's crawler work described treating pages within a Hamming distance of 3 on 64-bit SimHash as near-duplicates. MinHash estimates the Jaccard similarity of two documents' sets of word shingles, and pairs with locality-sensitive hashing to find similar pairs without comparing every pair. Either way, a near-duplicate page is stored once and its links still count, but you stop spending crawl budget on its copies.
Deep dive 4: spider traps
A spider trap is a URL space that never ends. Some are malicious, most are accidents:
- Infinite calendars: every month page links to the next month, forever.
- Session IDs in URLs:
?sid=8f2a...changes on each visit, so every link looks new. - Ever-deeper paths: a relative-link bug produces
/a/b/a/b/a/b/.... - Faceted search: filters for color, size, and price combine into millions of URLs for the same few products.
- Soft 404s: missing pages that return 200 with a "not found" body, which can link to more missing pages.
No single rule catches all of them. You layer limits:
Match each trap to the defense that best catches it.
The per-host budget is the most important one: a cap on pages per host per crawl cycle, scaled by how valuable the host is. A trap can only waste a site's budget, never the whole crawler's. Track the share of near-duplicates per host too; when it climbs, cut that host's budget.
Deep dive 5: storage and recrawl scheduling
Fetched pages are written to WARC files in object storage, and an event goes on a stream for the indexer and other consumers. The urls row gets the fetch time, status, content hash, and SimHash.
Pages change at very different rates. A news homepage changes every few minutes; an old documentation page might not change in years. Recrawling everything on a fixed schedule wastes most fetches on unchanged pages and still misses fast changes.
Use adaptive scheduling: after each fetch, compare the new content hash with the old one. If it changed, shorten that page's interval (for example, halve it); if not, lengthen it (double it), within a floor and a ceiling. Weight the result by importance, so a popular page that changes daily is checked daily. next_due is just last_fetched + interval, and the scheduler scans for due pages and feeds them back into the front queues. Sitemaps with lastmod dates and conditional GETs make each recrawl cheaper still.
Order the steps for one URL from the frontier to stored page.
- Tap the steps below in the right order.
Bottlenecks, failures, and 10x scale
- Distribution. Partition the work by host: hash the host name onto a consistent hashing ring of crawler nodes. Every URL for a host goes to the same node, so that node's back queue and heap enforce politeness locally, with no cross-node coordination. Links found for other hosts are batched and sent to the owning node. Adding a node moves only about
1/Nof hosts. - Hot hosts. A huge site like a major encyclopedia needs more throughput than one connection allows, but only with the site's agreement. Raise its delay limit by policy, not by accident.
- Node failure. Persist each node's frontier to disk or a durable queue, so a crash loses a few in-flight fetches, not millions of queued URLs. The Bloom filter is checkpointed periodically; losing recent additions only causes a few repeat fetches.
- Freshness vs coverage. At a fixed fetch budget, every recrawl is a new page you did not discover. Make the split an explicit setting.
- 10x (10 billion pages a month, about 4,000 pages a second): add crawler nodes on the hash ring, shard the Bloom filter by host along with the frontier, and scale object storage, which takes it in stride. The design does not change, because politeness was already local to each host.
- URL frontier
- The data structure that holds URLs waiting to be fetched and decides which one goes next, balancing priority and politeness.
- politeness
- Limiting load on each host: one connection at a time, a delay between requests, and obeying robots.txt.
- robots.txt
- A file at a site's root, standardized as RFC 9309, that tells crawlers which paths they may fetch.
- Bloom filter
- A compact bit array that answers 'possibly seen' or 'definitely not seen', with a tunable false positive rate and no false negatives.
- SimHash
- A fingerprint where similar documents differ in only a few bits, used to detect near-duplicate pages.
- spider trap
- A URL space that generates endless pages, such as an infinite calendar or session IDs in links.
- adaptive recrawl
- Revisiting a page sooner when it changed last time and later when it did not.