Design: web crawler

In one sentence

A URL frontier with one queue per host feeds fetch workers that obey robots.txt; new links pass a Bloom-filter seen-check, pages pass content dedup, and each host gets one request at a time.

Every link passes the seen-check before the frontier, and every page passes content dedup before storage.

How it works

  • Scale: ~1B pages/month is ~400 pages/s and ~185 TB of raw content (assumptions).
  • The URL frontier has priority front queues and per-host back queues; a heap schedules each host's next fetch.
  • Politeness by construction: hosts sharded by hash(host), one request in flight per host, cached robots.txt.
  • Dedup twice: normalized URLs through a Bloom filter, page content through exact hashes and SimHash.
  • Cap depth and URLs per host so infinite calendars and faceted search can't trap the crawler.

Check yourself

Answer to mark it learned; your answers aren't scored.

A site owner complains your crawler opened 40 parallel connections to their server. Each of your 40 workers is rate-limited to 1 request/s per host, and URLs are spread round-robin across workers. What's the fix?

Go deeper

Bloom filter calculator Interactive labDo this round in 45 minutes System design round
Full explanation

Requirements

Functional: start from seed URLs, crawl ~1B pages/month (assumption), store raw HTML for an indexer, and recrawl pages that change. Non-functional: polite (never overload a host, obey robots.txt), robust to spider traps and broken HTML, horizontally scalable, restartable after crashes.

Questions I'd ask: what is it for (search index, LLM training data, monitoring)? HTML only, or PDFs too? Do we render JavaScript? How fresh must pages be?

Scale: 1B pages ÷ ~2.6M s ≈ **~400 pages/s**. At ~185 KB per page (Common Crawl's August 2026 average) that's ~185 TB/month of raw content.

High-level design

Seeds → URL frontier → fetch workers (async HTTP, cached DNS and robots.txt) → content dedup → page store (object storage, WARC files) → link extractor → URL normalizer → URL-seen filter → back into the frontier.

The hard parts

Politeness without losing throughput. The frontier (Mercator design) has front queues by priority and back queues that each hold one host. A heap keyed by each host's next allowed fetch time hands out work, so one host gets one request at a time while thousands of hosts run in parallel. Partition hosts across workers by hash(host): one worker owns each host's queue, robots.txt and DNS entry.

Dedup at billions. Normalize URLs (lowercase host, drop fragments and session ids, sort query params), then check a Bloom filter (~9.6 bits per URL at 1% false positives). For content, an exact hash catches copies and SimHash catches near-duplicates: a Google paper found 64-bit fingerprints with ≤ 3 differing bits work for 8B pages.

Code Polite frontier: per-host queues plus a heap
pythonPolite frontier: per-host queues plus a heap
import heapq, time
from collections import defaultdict, deque
from urllib.parse import urlsplit

class Frontier:
    def __init__(self, default_delay_s: float = 1.0):
        self.delay = default_delay_s
        self.queues = defaultdict(deque)   # host -> URLs: one back queue per host
        self.heap = []                     # (earliest next fetch, host)
        self.active = set()                # hosts in the heap or being fetched

    def add(self, url: str) -> None:
        host = urlsplit(url).hostname
        self.queues[host].append(url)
        if host not in self.active:        # idle host: eligible right away
            self.active.add(host)
            heapq.heappush(self.heap, (time.monotonic(), host))

    def next(self) -> tuple[str, str] | None:
        if not self.heap or self.heap[0][0] > time.monotonic():
            return None                    # no host is due yet
        _, host = heapq.heappop(self.heap)
        return host, self.queues[host].popleft()

    def done(self, host: str, crawl_delay_s: float | None = None) -> None:
        # Reschedule only after the fetch ends: one request in flight per host
        if self.queues[host]:
            due = time.monotonic() + (crawl_delay_s or self.delay)
            heapq.heappush(self.heap, (due, host))
        else:
            self.active.discard(host)
            del self.queues[host]
Real example

A worker owns shop.example. Its robots.txt (cached ≤ 24 h, per RFC 9309) disallows /cart. The site has ~2M product pages, but each links to ?sort= variants and appends a sessionid. Normalization strips sessionid and sorts parameters, so the Bloom filter sees ~2M URLs, not tens of millions. An event calendar links to next day forever; a depth limit and a per-host URL cap stop it. At 1 request/s, one pass over 2M pages takes ~23 days, so the frontier ranks pages that change most first.

Trade-offs +3 · −3

+ You gain

  • Politeness is structural: one owner per host and a heap, no global rate limiter to tune.
  • Host-sharded workers keep robots.txt, DNS and per-host state local, so they scale out with no coordination.
  • A Bloom filter checks billions of URLs in memory at ~1.2 bytes each.

− You pay

  • Bloom false positives silently skip ~1% of new URLs unless you confirm against a KV.
  • Politeness caps big sites: at 1 request/s, 2M pages take ~23 days per pass.
  • Recrawl freshness and new-page discovery compete for the same fetch budget.

Use it when

Search indexes, LLM training corpora, price or SEO monitoring: any job that must fetch a large, changing set of third-party pages politely.

Avoid it when

Sites with APIs, sitemaps or feeds, or a small corpus: use those, or Common Crawl's monthly archives, before building a crawler.

Numbers to know 5
  • Throughput: 1B pages/month ÷ ~2.6M s ≈ ~400 pages/s (assumption); plan ~800/s for a 2× peak.
  • Common Crawl, Aug 2026: 2.14B pages, 360 TiB uncompressed, ~185 KB per page.
  • Bloom filter: ~9.6 bits per item at 1% false positives, so 10B URLs ≈ 12 GB.
  • RFC 9309: cache robots.txt ≤ 24 h, parse ≥ 500 KiB, 5xx means assume complete disallow.
  • Near-duplicates: 64-bit SimHash with ≤ 3 differing bits suits 8B pages (Google, WWW 2007).
Common pitfalls 4
  • No URL normalization: session ids and sort parameters turn one page into thousands of "new" URLs.
  • Rate-limiting per worker instead of per host: 50 polite workers still hit one host 50 times at once.
  • Treating a 5xx on robots.txt as "no rules": RFC 9309 says assume complete disallow.
  • No depth limit or per-host URL cap: calendars and faceted search are infinite.
Interview questions 3

Answer out loud first, then reveal.

How do you guarantee politeness with 1,000 workers?Show answer

I make it structural instead of tuning a rate limiter. Hosts are partitioned by hash(host), so exactly one worker owns each host's queue, robots.txt and DNS cache. Inside that worker, a heap keyed by next allowed fetch time hands out a host only after its previous fetch finished plus the delay. One request in flight per host, thousands of hosts in parallel, and rebalancing moves whole hosts.

Your Bloom filter says a URL was seen. What if it's wrong?Show answer

Then we skip a page we never crawled; it can never cause a double crawl, because Bloom filters have no false negatives. At 1% that's acceptable for discovery, and the page often resurfaces through other links or the sitemap. For domains where coverage matters, I confirm positive hits against a sharded KV of URL hashes. I also size the filter for the expected count, because past it the false-positive rate climbs fast.

How do you decide what to recrawl, and when?Show answer

By estimated change rate times importance, not round-robin. I store each fetch's content hash: if it changed since the last visit I shorten the interval, if not I lengthen it, within bounds. Conditional GETs with ETag or If-Modified-Since make unchanged pages a cheap 304. A news homepage ends up checked hourly, an archive page monthly, and a fixed budget is split between recrawl and discovery.

Deep dive 3

URL frontier and politeness

Front queues order URLs by priority (link-based importance, change rate, freshness target). A router moves URLs into back queues, each holding a single host, and a min-heap stores when each host may be fetched again. A worker pops the heap, fetches one URL, and only then reschedules that host after its delay. Mercator's rule of thumb: about 3× as many back queues as crawler threads, so threads stay busy. Shard hosts across machines with consistent hashing on the host name, so robots.txt, DNS and politeness state never need coordination, and rebalancing moves whole hosts.

Dedup: URLs and content

A Bloom filter answers "seen?" in memory: ~9.6 bits per URL at 1% false positives, so 10B URLs fit in ~12 GB. It never says "new" for a URL it has seen; a false positive only means skipping a page never crawled, and those often come back through other links or sitemaps. Back it with a sharded KV of URL hashes when coverage matters. Content dedup runs after the fetch: an exact hash of the normalized body catches mirrors, and 64-bit SimHash catches pages that differ only in ads or timestamps.

robots.txt, traps and recrawl

RFC 9309 (2022) sets the rules: cache robots.txt for at most 24 h, parse at least 500 KiB, treat a 4xx as no restrictions and a 5xx as complete disallow. Google ignores crawl-delay; some other crawlers honor it. Traps (calendars, faceted filters, session ids) are infinite URL spaces: cap depth and URLs per host, and drop URLs whose path repeats. Recrawl by estimated change rate: shorten the interval when the content hash changed, lengthen it when not, and use If-Modified-Since or ETag so unchanged pages return a cheap 304.