Skip to content

Design a Web Crawler

Advanced 75 min read Part 17 of 18

Design a 10-billion-page web crawler: URL frontier, politeness and robots.txt, DNS caching, fetchers, URL and content dedupe, coordination and checkpoints.

The Problem#

A web crawler (also called a spider or bot) is a program that explores the web automatically. It starts from a few known pages, downloads them, finds the links inside, downloads those pages, finds more links, and keeps going. Search engines use crawlers to build their indexes. Archives use them to preserve the web. Price trackers, SEO tools and research groups use them to collect data. And today, companies that train large language models (LLMs) use them to gather the text those models learn from.

What happens to the downloaded pages depends on the use case, and that changes parts of the design. A search engine must index pages and rank them (for example with link analysis such as PageRank) and recrawl them to stay fresh. An LLM data pipeline mostly needs clean text dumped into storage for later processing. Either way, an interview focuses on the crawling itself: how to traverse billions of pages efficiently, extract what we need, store it, and avoid harming the websites we visit.

In this case study we design a crawler whose output is text for training an LLM: crawl about 10 billion pages within 5 days, extract the text, and store it. We then show what changes for a continuously running search-engine crawler.

The hard parts are:

  • Scale against a deadline. 10 billion pages in 5 days is about 23,000 pages per second, sustained, from millions of different servers.
  • Politeness. We must not overload any website. Each site gets at most about one request per second, must be allowed to opt out through robots.txt, and must see a crawler that behaves predictably. At our scale, an impolite crawler is effectively a distributed denial-of-service attack.
  • The web is hostile and messy. Servers are slow, down, or return errors. Pages are huge, malformed, duplicated thousands of times, or generated infinitely by "crawler traps". DNS is slow. Nothing can be trusted to behave.
  • Fault tolerance. Over five days, machines will crash. The crawl must resume where it left off without losing or redoing large amounts of work.
  • Deduplication. The same URL is discovered many times, and the same content lives at many URLs. Without dedupe, we waste most of our budget.

A real-world analogy. Imagine a team of librarians asked to copy every book in every library in the country within a week. They start with a list of a few big libraries. Every book they copy contains references to other books, which go onto a giant to-do list (the URL frontier). Each library has rules posted at the door about which rooms are off-limits and how often visitors may come (robots.txt), and a polite librarian never sends ten people to one small library at once (politeness). Before driving anywhere, they look up the library's address (DNS), and they keep a notebook of addresses so they do not look up the same one twice (DNS caching). They tick off books already copied, and notice when two differently titled books have the same text (deduplication). And because some librarians will fall ill during the week, everyone records their progress in a shared ledger so others can pick up where they left off (checkpoints).

This case study builds on Asynchronous Processing and Message Queues, Probabilistic Data Structures for Big Data and Rate Limiting and Throttling.

Clarifying Questions#

QuestionTypical answerWhy it matters
What is the output used for?Text for LLM training (search indexing is a variant).Determines what we extract and whether we must recrawl for freshness.
How many pages?About 10 billion.Sets machine counts, storage and dedupe structures.
Deadline?Data available within 5 days of starting.About 23,000 pages per second sustained; drives parallelism.
Average page size?Plan for 2 MB worst case for bandwidth; HTML alone is typically tens of KB.Bandwidth sizing and storage; we fetch HTML, not images or scripts.
Are seed URLs provided?Yes, usually. If not, use popular sites, directories, and news and social sites.Seeds determine which parts of the web are reachable.
Non-text content (images, video, PDFs)?Out of scope.Simplifies fetchers and parsers; skip by content type.
JavaScript-rendered pages?Out of scope initially; mention headless browsers.Rendering costs 10 to 100 times more than a plain fetch.
Pages behind logins?Out of scope.No credential handling.
One-time crawl or continuous?One-time for now; discuss recrawling.Continuous crawling needs a scheduler and change-rate estimation.
Must we crawl the entire web?No; the vast majority of reachable pages. Some dark corners are unreachable.Allows coverage targets instead of completeness.
Politeness rules?Obey robots.txt, about 1 request per second per domain.Turns the problem into scheduling under per-host constraints.
Security, cost, legal compliance?Below the line, but mention them.Malicious pages, budgets, and copyright and privacy rules are real concerns.

Requirements#

Functional Requirements#

  1. Crawl the web starting from a given set of seed URLs, following links to discover new pages.
  2. Extract text from each page and store it for later processing.

Below the line: processing of the text (training), non-text data, JavaScript-rendered content, authenticated pages. We also accept that we cannot reach every page on the web; a crawl covers most of the reachable web, not all of it.

Non-Functional Requirements#

  1. Fault tolerance: handle failures gracefully and resume without losing progress.
  2. Politeness: adhere to robots.txt and never overload a website's servers.
  3. Efficiency: complete the crawl of about 10 billion pages in under 5 days.
  4. Scalability: scale out to 10 billion pages and beyond by adding machines.

Below the line: security against malicious actors (though we must still defend against malicious pages), cost constraints, and legal compliance, all of which a real deployment must address.

A note on estimation: rather than computing every number up front, many interviewers prefer that you compute numbers at the moment a design decision depends on them. We give the main ones below and return to them in the scaling deep dive.

Capacity Estimation#

See Back-of-the-Envelope Estimation and Numbers Every Engineer Should Know.

Throughput. 5 days is 432,000 seconds. 10 billion pages ÷ 432,000 s ≈ 23,000 pages per second, sustained. Plan for 30,000 to 40,000 per second of capacity to absorb retries, slow periods and a margin.

Bandwidth, worst case. If we planned with 2 MB per page (full page weight including images and scripts), 23,000 pages/s × 2 MB = 46 GB/s ≈ 370 Gbps. That is a lot, but it is spread over many machines.

Bandwidth, realistic. We only fetch HTML, not images or scripts. Typical HTML is tens of kilobytes, often compressed on the wire. At 100 KB per page, 23,000 pages/s is 2.3 GB/s ≈ 18 Gbps. Bandwidth is not the hardest constraint; latency, politeness and DNS are.

Concurrency by Little's law. The number of requests in flight equals throughput times latency. A fetch to an arbitrary server on the internet takes on average perhaps 0.5 to 2 seconds (DNS, TCP and TLS handshakes, server think time, transfer). At 23,000 pages/s and 1 second each, about 23,000 fetches must be in flight at all times. A single machine with asynchronous I/O can hold thousands of open connections, so this is tens of machines' worth of connection capacity, not thousands.

Machines. From a bandwidth view: a network-optimised cloud instance offers up to about 200 Gbps. At 2 MB per page that is 12,500 pages/s in theory. Assume 30% usable after latency, DNS, politeness and retries: about 3,750 pages/s per machine. Then 10 billion ÷ 3,750 ≈ 2.7 million machine-seconds ≈ 31 machine-days, so 8 such machines finish in about 3.9 days. From a connection view: at 3,000 concurrent connections per machine and 1 second per fetch, each machine does about 3,000 pages/s, so 8 to 12 machines. The two views agree on the order of magnitude: around ten large fetcher machines, or many more smaller ones. In practice, load testing decides; the interview point is that you can reason to a defensible number.

How can we fetch thousands of pages per second if each domain allows one per second? Because we crawl millions of domains in parallel. Each fetcher holds thousands of connections to different sites simultaneously. Any one domain sees at most one request per second, while the aggregate is enormous.

The politeness ceiling for big sites. At 1 request per second, a site with 10 million pages needs 10 million seconds, about 116 days, far beyond our 5-day budget. So for the largest sites we will either crawl only a sample within the deadline, use a higher rate where the site permits it (many large sites can handle more and say so through their own policies), or use official data dumps where they exist (Wikipedia, for example, publishes database dumps). This is a subtle point that strong candidates raise.

Storage.

  • Raw HTML: 10 billion × 100 KB ≈ 1 PB (or 20 PB at the 2 MB worst case). Compressed with gzip or Zstandard at about 4 to 5 times: about 200 to 250 TB.
  • Extracted text: perhaps 5 to 20 KB per page, so 50 to 200 TB before compression.
  • URL metadata: 10 billion crawled URLs plus several times as many discovered but not crawled. At about 200 bytes per URL record: 2 TB for crawled and perhaps 10 TB including the discovered set.
  • Content hashes: 10 billion × 8 to 16 bytes ≈ 80 to 160 GB, or about 12 GB in a Bloom filter at a 1% false-positive rate (see the dedupe deep dive).

DNS. With 23,000 fetches per second and pages clustered on hosts, the number of distinct hostnames is in the hundreds of millions. Without caching, that is up to 23,000 DNS lookups per second, each taking tens to hundreds of milliseconds through the DNS hierarchy. With a cache, lookups drop to roughly the rate of new hostnames discovered.

Parsing. HTML parsing and text extraction take on the order of 5 to 50 ms of CPU per page. At 23,000 pages/s that is 115 to 1,150 CPU-seconds per second: roughly 100 to 1,000 cores, which is why parsing scales separately from fetching.

QuantityValue
Pages10 billion in 5 days
Fetch rateabout 23,000 per second (plan 30,000 to 40,000)
Concurrent fetchesabout 23,000 to 40,000
Bandwidthabout 18 Gbps realistic, up to 370 Gbps worst case
Fetcher machinesabout 8 to 12 large instances
Raw HTMLabout 1 PB, about 250 TB compressed
URL metadataabout 2 to 10 TB
Parsing CPUabout 100 to 1,000 cores

Core Entities#

  • URL: a page address, normalised, with its crawl state (discovered, queued, fetched, parsed, failed), depth from a seed, priority and the locations of its stored HTML and text.
  • Domain (host): a website, with its parsed robots.txt rules, crawl delay, last fetch time, rate limit and error statistics.
  • Page content: the raw HTML (stored in blob storage) and the extracted text (also in blob storage).
  • Content hash: a fingerprint of page content used to skip duplicates.
  • Frontier entry: a URL waiting to be crawled, with its priority and earliest allowed fetch time.

API Design#

This is not a user-facing system, so instead of a REST API we define its system interface: what goes in and what comes out.

  • Input: seed URLs (and configuration such as depth limits, per-domain rates and content filters).
  • Output: extracted text from web pages, written to blob storage, plus metadata (URL, fetch time, content hash) for downstream processing.

An operator-facing control API is still useful for running crawls:

POST /v1/crawls
{ "seeds": ["https://en.wikipedia.org/", "https://www.bbc.com/"],
  "maxDepth": 15, "defaultRatePerDomain": 1.0, "deadline": "2026-12-08T00:00:00Z" }
-> 201 { "crawlId": "c-2026-12" }
 
GET /v1/crawls/c-2026-12/status
-> 200 { "fetched": 4120000000, "queued": 9800000000, "failed": 210000000,
         "pagesPerSecond": 24310, "etaHours": 68 }
 
POST /v1/crawls/c-2026-12/pause

Data flow#

Agreeing on the data flow before drawing boxes helps align with the interviewer:

  1. Take a URL from the frontier and resolve its hostname to an IP address with DNS.
  2. Fetch the HTML from the web server at that IP.
  3. Extract text from the HTML.
  4. Store the text.
  5. Extract links from the HTML and add new ones to the frontier.
  6. Repeat until the frontier is empty or the deadline arrives.

This is deliberately simple. Each step hides problems (politeness in step 1, failures in step 2, duplicates in step 5) that we solve in the deep dives.

High-Level Design#

We start with the simplest system that follows the data flow, then split and harden it in the deep dives.

1. Crawl the web starting from seed URLs#

The minimum: a frontier queue holding URLs to crawl, seeded with the starting list; a crawler service that takes a URL, resolves its hostname with DNS, and fetches the page from the external web server.

  • Frontier queue: the to-do list of URLs. Technology options include Kafka, Redis, or Amazon SQS; we choose in the fault-tolerance deep dive.
  • Crawler: takes URLs from the frontier and fetches them. We scale it out later.
  • DNS: turns hostnames into IP addresses. At our scale, DNS is a bottleneck worth its own deep dive.
  • Web servers: external, outside our control, and often slow or broken.

Ask the interviewer where seeds come from. Usually they are given. If not, good seeds are popular sites with many outbound links: major news sites, social platforms, web directories, Wikipedia, and the top of public domain-popularity lists.

2. Extract text and store it#

The crawler parses the fetched HTML, strips markup, scripts and boilerplate to get the text, and writes it to blob storage (Amazon S3, Google Cloud Storage or Azure Blob Storage). Blob storage is the natural home: it is cheap, durable (designed for eleven nines), scales to petabytes, and our output is large immutable files consumed in bulk by a training pipeline. See Object Storage and Blob Storage.

Text is written in large batched files (for example a few hundred megabytes of compressed JSON lines or a columnar format like Parquet), not one object per page. Ten billion tiny objects would be slow to list and expensive to request; a few hundred thousand large files are efficient for both writing and downstream training jobs. Many large crawl datasets use the WARC (Web ARChive) format for raw responses, which bundles many records per file.

The parser also extracts every link (<a href>), resolves relative links against the page's URL (../about on https://example.com/blog/post becomes https://example.com/about), normalises them, and adds new ones to the frontier. This closes the loop: the crawl keeps expanding until no new URLs are found or a limit is reached.

At this stage the single crawler does everything: DNS, fetching, parsing, link extraction. It works, but it is fragile (a crash loses in-flight work), impolite (nothing stops it from hammering one site), and wasteful (it crawls duplicates). The deep dives fix each problem.

The full high-level design#

After the deep dives, the crawler becomes a pipeline of independently scaled stages connected by queues, with shared state in a metadata database and in Redis.

The fetch path: from seeds to a downloaded page.

The store-and-parse path: from a downloaded page back to new URLs.

Components:

  • URL scheduler: decides which discovered URLs to crawl and when, based on priority, depth limits and per-host politeness. For a one-time crawl it can be thin; for recurring crawls it becomes the brain of the system.
  • Frontier queues: hold URLs ready to fetch. Messages carry only a URL id and small metadata, never page content.
  • Fetchers: check robots.txt rules and politeness, resolve DNS through a cache, fetch with strict timeouts and size limits, store raw HTML in blob storage, record metadata, and enqueue a parse job.
  • DNS cache and resolvers: local caches on each fetcher plus a shared caching resolver tier, backed by multiple upstream providers.
  • Politeness store: Redis holding per-domain locks, last-fetch times and rate-limit counters, shared by all fetchers.
  • Metadata DB: the URL table (state, depth, blob locations, content hash) and the domain table (robots rules, crawl delay, last crawl time). DynamoDB is a good fit; PostgreSQL or MySQL could also work at a smaller scale. See Amazon DynamoDB in Practice.
  • Parse queue and parser workers: read raw HTML from blob storage, extract text and links, write text to blob storage. Autoscaled on queue depth.
  • Dedupe: URL-level (have we seen this normalised URL?) and content-level (have we stored this exact content?).
  • Dead-letter queue: URLs that failed repeatedly, kept for inspection and possible later retry.

Key Flows#

Flow 1: Fetching one URL politely#

  1. A fetcher receives a frontier message containing a URL id (not the page itself).
  2. It loads the domain's robots rules and crawl delay (cached in the fetcher's memory, backed by the metadata DB). If robots.txt has never been fetched for this domain, it fetches and parses it first.
  3. If the path is disallowed, it marks the URL blocked and deletes the message. Done.
  4. It tries to take the domain's politeness lock in Redis (SET lock:example.com 1 NX PX 1000). If another fetcher holds it, this message is deferred: the fetcher extends its visibility timeout so it reappears later, and moves on to a different URL.
  5. With the lock, it fetches the page through the DNS cache, with connect, read and total timeouts, and a maximum body size.
  6. It writes the raw HTML to blob storage, updates the URL's metadata (state fetched, blob key, HTTP status, content hash), and enqueues a parse job containing only the URL id.
  7. Only then does it delete the frontier message. If it crashes before this point, the message becomes visible again and another fetcher retries.
  1. A parser worker takes a parse job and reads the raw HTML from blob storage.
  2. It extracts the main text (removing navigation, ads and boilerplate), the title, the language, and all outbound links.
  3. It computes a content hash. If the content was seen before, it records the duplicate and skips storing the text again.
  4. It writes the text to blob storage, batched into large files.
  5. It normalises the outlinks, checks them against the seen set of URLs, and inserts only new ones with depth = parent depth + 1, if under the maximum depth.
  6. The scheduler places new URLs on the frontier according to priority and host.

Flow 3: A fetch fails#

  1. The fetch times out or returns a 5xx error. The fetcher does not delete the message.
  2. It reads how many times the message has been received (ApproximateReceiveCount in SQS) and sets the next visibility timeout with exponential backoff and jitter: for example 30 s, 2 min, 8 min, 30 min, 2 h.
  3. The message reappears after the delay and any fetcher can retry it.
  4. After 5 failed attempts, the queue's redrive policy moves it to the dead-letter queue, and the URL is marked failed. We treat the site as offline for this crawl.
  5. 4xx errors such as 404 or 410 are permanent: the URL is marked gone immediately with no retry. 429 (Too Many Requests) and 503 with a Retry-After header slow down the whole domain, not just this URL.

Data Model#

The metadata DB holds small, frequently updated records; blob storage holds large immutable content. See Choosing a Database: A Decision Guide.

TableKeyStoreNotes
URLhash of normalised URLDynamoDB (partition key urlHash)State machine per URL; depth for trap protection. GSI on host for per-site queries.
DomainhostDynamoDB, cached in Redis and fetcher memoryRules, rate, last fetch, error counts.
RobotshostDynamoDB plus raw file in blob storageParsed rules cached in memory on fetchers.
Content hashcontent fingerprintDynamoDB with the hash as key, or a Bloom filterExact-duplicate detection.
Raw HTMLcrawl id + URL hashBlob storage, batched WARC-style filesKept so text extraction can be re-run without refetching.
Textcrawl id + batchBlob storage, compressed JSON lines or ParquetOutput for training.
Politeness statehostRedisLocks with TTL, sliding-window counters.

Why key URLs by a hash? URLs can be thousands of characters long. A fixed-size hash (for example the first 16 bytes of SHA-256 of the normalised URL) gives uniform partitioning in DynamoDB, constant-size keys, and a compact representation for the seen set. The full URL is stored as an attribute.

Keeping raw HTML. Storing raw HTML costs extra storage, but it makes the pipeline robust to changing requirements: if the ML team later wants image alt text included, or a better boilerplate remover, we re-run only the parse stage over stored HTML instead of refetching 10 billion pages.

Deep Dives#

1. Fault tolerance: split the crawler into stages#

The single crawler service does too much: DNS, fetching, text extraction, link extraction, and soon politeness checks. If any step fails, the whole unit of work fails, and if the process crashes, everything in flight is lost. Fetching is by far the most failure-prone step: servers are down, slow, moved, or return enormous responses.

Split the work into pipelined stages connected by queues:

  • Fetch stage: fetches HTML and stores it in blob storage. If a fetch fails, we retry just the fetch.
  • Parse stage (text and URL extraction): reads stored HTML, extracts text and links. These two tasks could be separate stages, but both are cheap, CPU-bound and work on the same parsed document, so combining them avoids parsing every page twice.

Pipelining has three benefits. Failures are isolated to one stage and retried there. Each stage scales independently: fetchers are I/O-bound and need many connections; parsers are CPU-bound and need many cores. And the system is robust to changing requirements: changing text extraction means re-running the parse stage over stored HTML, not refetching the web. Whenever you see a data processing question, think "pipeline of stages with durable hand-offs". See Pattern: Multi-Step Processes and Workflows.

Never put page content in the queue. Queues are optimised for many small messages, not multi-megabyte payloads (SQS messages are limited to 256 KB by default, and large Kafka messages hurt throughput and retention). The message is the URL id; the content lives in blob storage, referenced from the metadata DB. This is the "claim check" pattern.

How do we retry failed fetches?

Bad: an in-memory timer

Wait a few seconds in the fetcher's memory and try again. If the fetcher crashes, the timer and the URL are lost. And a site that failed a second ago will very likely still fail a few seconds later, so retries need to back off exponentially, over minutes to hours.

Good: Kafka with a manual backoff topic

Kafka has no built-in delayed retry, but we can build one. Failed URLs go to a retry topic with a "not before" timestamp in the message. A retry consumer reads them and, if the time has not come, waits (or re-publishes them to a later tier, such as retry-1m, retry-10m, retry-1h topics). This works and is used in practice, but it is a fair amount of machinery to build and operate: tiered topics, pausing consumers, and careful offset management.

Great: SQS visibility timeouts and a dead-letter queue

Amazon SQS provides the primitives directly. When a consumer receives a message, the message becomes invisible to other consumers for a visibility timeout (default 30 seconds, configurable up to 12 hours). If the consumer deletes the message, it is gone; if not, it reappears when the timeout expires.

To implement exponential backoff, on failure the fetcher calls ChangeMessageVisibility with a timeout computed from the message's ApproximateReceiveCount attribute (how many times it has been received):

delay = min(base * 2^(receiveCount - 1), maxDelay) + random_jitter
e.g. base = 30 s, maxDelay = 12 h:
  attempt 1 fails -> 30 s, attempt 2 -> 60 s, 3 -> 120 s, 4 -> 240 s

The queue's redrive policy with maxReceiveCount = 5 moves a message to a dead-letter queue (DLQ) after five receives. We treat such URLs as offline for this crawl, and engineers can inspect the DLQ for patterns (a whole hosting provider down, a bug in our fetcher). See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

There is rarely one right technology. What matters is a justified choice. If you do not know the details of a particular queue's retry semantics, say so and do not choose that area for a deep dive.

2. Crashes, checkpoints and not losing progress#

Over five days on dozens or hundreds of machines, crashes are certain. What happens when a fetcher or parser dies mid-task?

The answer is simple: start a new one, and make sure the in-flight work is not lost. The queue provides that guarantee as long as work is acknowledged only after its result is durable.

  • With Kafka, messages are retained in a log and not removed when read. Each consumer group tracks its position with offsets. A fetcher commits its offset only after the HTML is in blob storage and the metadata is updated. If it crashes, the partition is reassigned to another consumer, which resumes from the last committed offset and redoes the uncommitted work.
  • With SQS, messages stay in the queue until explicitly deleted. A received message is hidden for the visibility timeout; if the fetcher crashes, it becomes visible again and another fetcher picks it up. The fetcher deletes the message only after the HTML is stored.

The same holds for parsers: a parse job is deleted only after the text is written and new URLs are recorded.

Both give at-least-once processing: after a crash, some pages are fetched or parsed twice. That is acceptable if every step is idempotent:

  • Raw HTML is written to a deterministic key (raw/{crawlId}/{urlHash}), so a second write overwrites identical data.
  • Metadata updates are conditional ("set state to fetched if state is queued or fetching").
  • New URLs are inserted with "put if not exists", so discovering the same link twice creates one row.
  • Text output goes into batch files; duplicates from retries are removed downstream by URL hash, or each batch file is written atomically with a manifest so that a half-written batch is discarded and redone.

See Delivery Guarantees: At-Most, At-Least and Exactly-Once.

Checkpointing the crawl as a whole. Queues protect in-flight work, but the crawl also has global state: the frontier (billions of queued URLs), the seen set, per-domain politeness state, and dedupe structures. Losing any of these would be expensive.

  • Durable by construction: the URL table and the domain table are in the metadata DB, which is replicated and durable. The frontier can always be reconstructed from the URL table by selecting URLs in state discovered or queued.
  • Periodic snapshots of in-memory structures: if the seen set or content-hash set is a Bloom filter in Redis or in process memory, snapshot it to blob storage every few minutes (Redis RDB snapshots, or serialised bit arrays). After a restart, load the snapshot and replay the URLs added since, from the metadata DB.
  • Politeness state is soft: if Redis loses locks and counters, the worst case is a brief burst of slightly faster crawling to some domains. To be safe, fetchers can start conservatively after a Redis failover (for example half the normal rate for a few minutes).

Graceful degradation instead of stopping. If the metadata DB slows down, fetchers reduce their concurrency rather than failing. If blob storage throttles, fetchers back off with jitter. If the parse queue grows, parsers autoscale; fetching continues because raw HTML is safely stored. The pipeline absorbs failures at each stage boundary. See Pattern: Managing Long-Running Tasks.

Crawl-level progress tracking. A crawl that runs for days needs visible progress: pages fetched per second, frontier size, failure rates by error type, DLQ size, parse lag, and an estimated completion time. If the ETA drifts past the deadline, the operator can add fetchers, lower the maximum depth, or deprioritise low-value hosts.

3. The URL frontier: priority and per-host queues#

The frontier is the set of URLs discovered but not yet fetched, plus the logic that decides which one to fetch next. A plain FIFO queue is the simple answer, but it has two problems at web scale.

  1. Politeness. Pages link mostly to pages on the same site. A FIFO queue filled from one page of example.com holds dozens of consecutive example.com URLs. Many fetchers pull them at once and hammer one server.
  2. Priority. Not all URLs are equally valuable. A link from a high-quality page is worth more than the 50,000th page of a forum archive. A FIFO queue cannot express that.

The Mercator design (Heydon and Najork, "Mercator: A Scalable, Extensible Web Crawler", World Wide Web journal, 1999; the version taught in Manning, Raghavan and Schütze's Introduction to Information Retrieval, 2008, chapter 20) splits the frontier into two layers:

  • Front queues (priority). There are F FIFO queues, one per priority level. A prioritiser assigns each new URL a priority (from PageRank-like link signals, the host's quality, depth, or change rate) and appends it to the matching front queue.
  • Back queues (politeness). There are B FIFO queues, and each back queue holds URLs from only one host. A table maps host to back queue. When a back queue empties, the back-queue selector refills it by pulling from the front queues (biased towards high-priority queues) until it finds a URL for a host that has no back queue yet.
  • A min-heap of next-allowed times. Each back queue has one heap entry: the earliest time its host may be contacted again. A fetcher thread pops the heap minimum, waits until that time if needed, fetches the URL at the head of that back queue, then pushes the queue back with now + delay.

The rule of thumb given in that textbook treatment is to have about three times as many back queues as fetcher threads, so that whenever a thread is free, some host is ready. With 23,000 fetches in flight across the cluster, we want on the order of 70,000 active hosts in the back layer at any moment, which a web crawl easily provides.

This design gets politeness by construction: a host is in exactly one back queue, served by one fetcher at a time, with an explicit delay between requests. No distributed lock is needed within a partition. It is the classic answer and worth describing in a senior or staff interview.

How this maps to our managed-queue design. A fleet of stateless fetchers reading from SQS cannot easily implement per-host back queues, because SQS has no notion of "one consumer per host". There are three ways to proceed:

  • Lock and defer (what our base design does). Fetchers read any URL; before fetching, they check a per-domain lock and rate limit in Redis. If the domain is busy, they push the message back with a short visibility delay. This is simple, but it wastes reads when one domain dominates the queue: many messages are received only to be deferred.
  • Host-partitioned frontier. Partition URLs by hash(host) into P partitions (Kafka partitions or separate queues). Each fetcher owns some partitions and runs a Mercator-style back-queue structure in memory for the hosts it owns. Politeness is now local: no Redis lock on the hot path. This is what most large crawlers do, and it is the subject of Deep Dive 11.
  • SQS FIFO with message group = host. SQS FIFO queues deliver messages of the same message group in order and never to two consumers at once, which gives one-at-a-time per host. FIFO queues have lower throughput limits (thousands of messages per second per queue, more in high-throughput mode), so at 23,000 pages per second you need many of them, sharded by host. The per-request delay still has to be enforced by the consumer.

Priority in a managed queue. SQS has no priorities. Use separate queues (frontier-high, frontier-normal, frontier-low) and have fetchers poll them in a weighted pattern, for example 6:3:1, so low priority never fully starves. In Kafka, use separate topics the same way.

Where does the frontier live? At 10 billion URLs, it does not fit in memory. Mercator kept most of each queue on disk with small in-memory buffers at the head and tail. In our design the durable truth is the URL table in the metadata DB; queues hold a working window of the next few hundred million URLs, refilled by the scheduler in batches. This keeps the queues small and lets the scheduler re-prioritise as new link signals arrive.

4. Politeness and robots.txt#

Politeness means not harming the sites we crawl and following the rules they publish. It is both an ethical obligation and a practical one: impolite crawlers get IP-banned, rate-limited, reported to their hosting provider, or blocked by CDNs, and their data quality drops.

robots.txt

Every site may publish /robots.txt, a text file of rules for crawlers. It was a de facto convention from 1994 until it became a standard in RFC 9309, "Robots Exclusion Protocol" (Koster, Illyes, Zeller, Sassman; September 2022). An example:

User-agent: *
Disallow: /private/
Allow: /private/press/
Crawl-delay: 5
Sitemap: https://example.com/sitemap.xml
 
User-agent: BadBot
Disallow: /

The rules that matter for a crawler implementation:

  • Group matching. Find the group whose User-agent matches our crawler's product token (case-insensitive). If none matches, use the * group.
  • Longest match wins. Among Allow and Disallow rules matching the URL path, the most specific (longest) rule wins; on a tie, Allow wins. In the example, /private/press/release.html is allowed.
  • Wildcards. * matches any sequence and $ anchors the end, so Disallow: /*.pdf$ blocks PDFs.
  • Fetch failures. If robots.txt returns 4xx (such as 404), the crawler may access anything. If it is unreachable or returns 5xx, the crawler must assume complete disallow for now. A long outage (the RFC suggests 30 days) may be treated as "no rules" or as the last cached copy.
  • Caching. Crawlers should not use a cached copy for more than 24 hours unless the file is unreachable. One robots.txt fetch per host per day is the norm.
  • Size. Parsers must handle at least 500 KiB; content beyond that limit may be ignored.
  • Redirects. Follow at least five redirects for robots.txt.

Crawl-delay is not part of RFC 9309. Many sites still use it, and Bing and Yandex have historically honoured it, but Google does not; Googlebot adjusts its rate automatically and offers settings in Search Console instead. A polite crawler should honour Crawl-delay when present, capped to something reasonable (for example at most 60 seconds, or a 10-million-page site could never be crawled).

Where robots.txt fits in the flow. Before fetching any URL of a domain, the fetcher reads the domain's rules from the cache (Redis or local memory, backed by the DOMAIN/ROBOTS table). If they are missing or older than 24 hours, it fetches robots.txt first, parses it, and stores the compiled rules and Crawl-delay. Then it checks the URL path against the rules. Disallowed URLs are marked blocked_by_robots and never fetched. Compile the rules once into an efficient matcher, because the check runs 23,000 times per second.

Rate limiting per domain

Beyond robots.txt, a crawler must limit how fast it hits each server. The common default is at most one request per second per domain, one connection at a time, adjusted by Crawl-delay. Implement it with a shared rate limiter in Redis:

-- before fetching from domain d at time now (ms):
SET lock:{d} fetcherId NX PX 30000         -- one in-flight request per domain
if not acquired: defer URL (visibility 1-5 s + jitter), stop
next = GET next_allowed:{d}
if next and now < next: release lock, defer URL until next, stop
-- fetch the page ...
SET next_allowed:{d} (now + delay_ms) PX 86400000
DEL lock:{d}  (only if value == fetcherId, via Lua)

A sliding-window counter (ZADD timestamps, ZREMRANGEBYSCORE older than one second, ZCARD) generalises this to "N requests per window" for sites that allow more. See Rate Limiting and Throttling and Redis in Practice.

Jitter matters. If many fetchers are deferred for exactly one second, they all retry at the same instant, one wins, and the rest are deferred again: a synchronised thundering herd. Randomise the deferral (for example 1 to 3 seconds) so retries spread out.

Adaptive politeness. Fixed rates are a starting point. Better crawlers adapt to how the server behaves:

  • Response time. Mercator's approach was to wait a multiple (for example 10×) of the time the last download took before contacting the host again. A fast server serving small pages can be crawled faster; a struggling one gets breathing room automatically.
  • Errors. On 429 Too Many Requests or 503 Service Unavailable, honour Retry-After and slow down the whole domain, not just the URL. A burst of timeouts or 5xx errors from a domain should cut its rate (for example halve it), recovering slowly (additive increase, multiplicative decrease, like TCP congestion control).
  • Shared infrastructure. Thousands of small sites may sit on one IP address (shared hosting) or one CDN. Some crawlers also rate-limit per IP address, not only per hostname, so they do not overload a shared server through many different names.

Sitemaps. Sitemap: lines in robots.txt point to XML files listing a site's URLs, often with lastmod dates and priorities. They are an excellent source of URLs for the frontier and of change signals for recrawling, especially for pages that are poorly linked.

Identification. Use a clear user-agent string with a contact URL (for example ExampleBot/1.0 (+https://example.com/bot)), publish the IP ranges you crawl from, and give site owners a way to opt out. Major crawlers do all of this, and site operators often verify crawler identity by reverse DNS lookup of the source IP.

5. Scaling to 10 billion pages in five days#

The capacity estimate showed we need about 23,000 pages per second sustained. Where do the limits come from, and how do we remove them?

Fetchers are I/O-bound, so concurrency is everything. Each fetch spends almost all its time waiting: DNS lookup, TCP and TLS handshakes, server think time, and transfer. By Little's law (in-flight = throughput × latency), at 23,000 pages per second and about 1 second per fetch, we need about 23,000 fetches in flight across the cluster at all times.

  • Thread per request works up to a few thousand threads per machine, but each thread costs stack memory (typically 1 MB reserved by default on Linux JVMs) and context switches.
  • Asynchronous I/O (an event loop: epoll on Linux, as used by Node.js, Python asyncio, Go's runtime, Netty in Java) lets one process hold 10,000 or more open connections with little memory each. Each machine runs one event loop per core. This is how modern high-throughput crawlers are built.

Network is the real ceiling. Our estimate gave about 18 Gbps of download for 23,000 pages per second at about 100 KB average (much less with compression). A single large cloud instance has 25 to 100 Gbps of network bandwidth, but sustained per-flow and per-instance limits, NAT gateways, and egress-to-internet paths often cap you lower. A practical plan targets 30% to 50% of the advertised bandwidth per machine:

target per machine: about 1 Gbps useful after overheads
    1 Gbps = 125 MB/s; 125 MB/s / 100 KB = 1,250 pages/s
pages needed: 23,000/s
machines at 1,250/s: about 19 fetcher machines
machines at 3,750/s (3 Gbps each): about 7..8 machines
plus 25% headroom for retries, robots.txt and DNS => 10..25 machines

So "a few dozen fetcher machines" is the right order of magnitude. Do not claim a single machine can do it; per-machine limits (file descriptors, ephemeral ports, conntrack tables, TLS CPU cost) bite well before link speed.

Practical tuning on each fetcher machine:

  • Raise the file-descriptor limit (ulimit -n to 100,000 or more), widen the ephemeral port range, and enable TCP reuse of TIME_WAIT sockets for outbound connections.
  • Reuse connections with HTTP keep-alive and HTTP/2 when fetching several pages from the same host. A TLS handshake costs one or two extra round trips and noticeable CPU. Since politeness spaces requests to one host by a second or more, keep idle connections open for a few seconds per host, but cap the pool size.
  • Accept compression (Accept-Encoding: gzip, br): HTML compresses 4 to 10 times, cutting bandwidth proportionally. Decompression costs CPU but is cheap compared with network.
  • Batch writes. Write raw HTML to blob storage in larger objects (for example WARC files of about 1 GB containing thousands of records) instead of one object per page. 10 billion tiny objects means 10 billion PUT requests (S3 charges per request and limits per-prefix request rates to about 3,500 writes per second), while 1-GB batches mean about a million objects.

Parsers scale on CPU. Parsing HTML and extracting text and links takes about 5 to 50 ms of CPU per page, depending on size and the parser. At 23,000 pages per second, that is between 115 and 1,150 cores. Parsers are stateless, so autoscale them on parse-queue depth: container services such as Kubernetes or AWS Fargate, or serverless functions (AWS Lambda) for bursty workloads. Lambda is simple but costs more at sustained high volume; a long crawl is usually cheaper on reserved or spot instances.

Spot instances. Fetchers and parsers are stateless and their work is protected by queue semantics (Deep Dive 2), so they are perfect for spot or preemptible VMs at a large discount. A reclaimed instance's in-flight messages just reappear after their visibility timeout.

The politeness ceiling is a scheduling problem, not a hardware one. At one request per second, a host with 10 million pages takes 116 days. No amount of hardware fixes that; the crawl is fundamentally limited by its largest hosts. Options:

  • Accept that we will not get all of a giant host's pages in five days, and prioritise its best pages (by inbound links or sitemap priority).
  • Use official bulk sources where they exist: Wikipedia publishes full database dumps, and many large sites offer APIs or data exports.
  • Negotiate higher rates with large sites, or use their stated limits if they allow more than one request per second.
  • Start giant hosts first, so their long tails run in parallel with everything else.

The total crawl time is roughly max(total pages / cluster rate, largest host pages / per-host rate). A good interview answer names both terms.

The metadata DB at scale. Each page generates several metadata writes (state transitions, new URLs, content hash). At 23,000 pages per second with about 50 links each, the URL table sees about 1.2 million "is this URL new?" checks per second and tens of thousands of inserts per second. That is a key-value workload: DynamoDB, Cassandra or a sharded key-value store keyed by URL hash, rather than a single relational database. See Amazon DynamoDB in Practice and Pattern: Scaling Writes. Most of those checks never reach the database because a Bloom filter or local cache answers first (Deep Dive 8).

6. DNS resolution#

Every fetch to a new host needs a DNS lookup to turn a hostname into an IP address. That sounds trivial, but at crawl scale DNS becomes a bottleneck.

  • Volume. A large crawl touches hundreds of millions of distinct hostnames. Typical recursive lookups take 10 to 200 ms when uncached, and some much longer.
  • Blocking resolvers. Many standard library resolvers (like the classic gethostbyname) are synchronous, sometimes serialised behind a lock. The Mercator authors reported that DNS resolution was a major bottleneck: a large share of fetch-thread time was spent waiting on lookups, which led them to write their own multi-threaded resolver. Later crawlers took the same lesson; Heritrix, for example, does its own DNS lookups through the dnsjava library rather than the platform resolver.
  • Provider limits. Public and cloud resolvers rate-limit clients. AWS's VPC resolver, for example, allows about 1,024 packets per second per network interface; a crawler doing tens of thousands of lookups per second will hit that quickly.

Mitigations, in order of impact:

  1. Cache aggressively, respecting TTLs. Each fetcher keeps an in-process DNS cache (hostname → IPs, expiry). Because URLs for one host cluster together, hit rates are high. Respect record TTLs, with a floor (for example 5 minutes) to avoid pathological short TTLs and a ceiling (for example 24 hours) to pick up moves.
  2. Shared caching resolvers. Run a pool of caching DNS servers (Unbound, PowerDNS Recursor, or dnsmasq for small setups) close to the fetchers. They resolve recursively from the root and authoritative servers themselves, so they are not bound by a third-party provider's limits, and their caches are shared across all fetchers.
  3. Multiple upstream providers. If you rely on upstream resolvers, spread queries round-robin across several providers (for example your cloud's resolver, Google Public DNS, Cloudflare, Quad9) to stay under each one's rate limits and survive any one's outage.
  4. Prefetch. When a parser discovers URLs on new hosts, the scheduler can resolve those hosts asynchronously before the URLs reach the head of the queue. By the time a fetcher needs them, the IPs are cached.
  5. Negative caching. Cache NXDOMAIN (host does not exist) and repeated timeouts for a while (for example one hour), so dead domains do not cost a lookup on every one of their thousands of discovered URLs.
  6. Asynchronous resolution. Use a non-blocking resolver library (for example c-ares, or the async resolvers built into Go and Netty) so a slow lookup never blocks a fetch slot.

DNS is a nice place for a staff-level insight: few candidates notice that DNS, not bandwidth, can be the first bottleneck. See DNS: The Domain Name System.

DNS and politeness interact. Rate limits keyed by hostname miss the case where 10,000 hostnames point at one shared-hosting IP. Once you have resolved IPs, you can apply a second, per-IP rate limit (more generous, for example 5 to 10 requests per second per IP) to protect shared servers.

7. The fetcher: HTTP done defensively#

The fetcher talks to millions of servers we do not control. Some are slow, some are broken, some are hostile. It must stay fast for the good ones and contained against the bad ones.

Timeouts at every layer. A single hung connection holding a slot forever is a slow leak that eventually stalls the fleet.

TimeoutTypical valueWhy
DNS lookup2-5 sDead nameservers can hang for 30 s or more
TCP connect5-10 sUnreachable hosts
TLS handshake10 sOverloaded servers
Time to first byte15-30 sSlow dynamic pages
Total download60 s"Tarpits" that trickle one byte per second
Max body size10 MB, truncateInfinite or huge responses

Size and type limits. Send Accept: text/html,application/xhtml+xml and check Content-Type and Content-Length in the response headers before reading the body. If the type is not text (images, video, binaries) or the declared length exceeds the limit, close the connection. A separate HEAD request first is usually not worth an extra round trip; just read the headers of the GET and abort early. Some servers send no Content-Length (chunked encoding), so the body limit must also be enforced while streaming.

Redirects. Follow up to about five redirects (301, 302, 307, 308). Treat each redirect target as a URL in its own right: normalise it, check the seen set, check robots.txt for its host (which may differ), and record the redirect in the metadata so links to the old URL resolve to the new canonical one. A 301 (permanent) should update the URL table so future crawls go straight to the target. Watch for redirect loops.

Status code handling:

  • 200: store content.
  • 304 Not Modified: page unchanged since our last fetch (recrawls only, see below). Update last_checked, do nothing else.
  • 404, 410: permanent failure. Mark gone; do not retry this crawl.
  • Other 4xx (401, 403): mark failed; usually do not retry.
  • 429, 503: the server is asking us to slow down. Honour Retry-After, reduce the domain rate, and retry later.
  • Other 5xx, timeouts, connection resets: transient. Retry with exponential backoff (Deep Dive 1).

Conditional GET for recrawls. On later crawls, send If-None-Match: <etag> and If-Modified-Since: <last-modified> from the previous fetch. An unchanged page comes back as a tiny 304 with no body, saving bandwidth for both sides. Not all servers support it, and some dynamic sites always return 200, so content hashing (Deep Dive 9) is the backstop for change detection.

Encoding and character sets. Decompress gzip or Brotli bodies, then decode the bytes to text using the charset from the Content-Type header, the HTML <meta charset>, or detection as a last resort. Getting this wrong produces mojibake (garbled characters) in the training data, a real quality problem for multilingual corpora.

Defending against hostile pages. Treat all content as untrusted input.

  • Run parsers in sandboxed, memory-limited processes or containers. A malformed page should crash one worker, not the fleet.
  • Cap DOM depth, number of links extracted (for example 1,000 per page), and decompressed size (a decompression bomb, a tiny gzip that inflates to gigabytes, must be stopped by a streaming limit).
  • Never execute JavaScript in the main fetch path. If rendering is needed, do it in an isolated renderer pool (Deep Dive 12).
  • Do not follow links to private address ranges (10.x, 192.168.x, 127.0.0.1, cloud metadata endpoints such as 169.254.169.254). A malicious page could otherwise use our fetchers to probe internal infrastructure: a classic server-side request forgery (SSRF) risk. See Security Fundamentals for System Design.

Archive format. Store raw responses in WARC (Web ARChive, ISO 28500), the standard format used by the Internet Archive and Common Crawl. Each record holds the request, response headers and body, and metadata such as the fetch time and IP. Downstream tools understand it, and it makes our raw data re-parseable for years.

8. URL deduplication and normalisation#

Without dedupe, the crawler refetches the same page every time it finds a link to it. Popular pages have millions of inbound links, so the waste would be enormous, and cycles in the link graph would make the crawl run forever.

Normalise first. Two URL strings can name the same resource. RFC 3986 (Berners-Lee, Fielding, Masinter; 2005) defines safe normalisations, and crawlers add a few heuristic ones:

  • Lowercase the scheme and host: HTTP://Example.COM/a → http://example.com/a.
  • Remove the default port: :80 for http, :443 for https.
  • Decode unreserved percent-encodings (%7E → ~) and uppercase the rest (%2f → %2F).
  • Resolve dot segments: /a/./b/../c → /a/c.
  • Remove the fragment (#section): the server never sees it.
  • Heuristic: sort query parameters, drop known tracking parameters (utm_source, utm_medium, fbclid, gclid) and session ids (jsessionid, sid).
  • Heuristic, use with care: treat http and https, or www. and bare domains, as the same if the site redirects between them.
  • Respect <link rel="canonical"> when present: it is the site's own statement of the preferred URL.

Then hash the normalised URL (for example a 64-bit or 128-bit hash, xxHash or the first bytes of SHA-256) and use the hash as the key everywhere.

Option 1: check the metadata DB. Before adding a URL to the frontier, look up its hash in the URL table, and insert it with a conditional put if missing. This is exact and simple. The cost is about 1.2 million lookups per second (23,000 pages × 50 links). A well-provisioned DynamoDB or Cassandra cluster can handle that, but it is expensive, and many of those lookups are for the same popular URLs.

Option 2: a Bloom filter in front. A Bloom filter (Burton H. Bloom, "Space/Time Trade-offs in Hash Coding with Allowable Errors", Communications of the ACM, 1970) is a bit array of m bits with k hash functions. To add an item, set the k bits at its hash positions. To test an item, check those k bits: if any is 0, the item is definitely not present; if all are 1, it is probably present.

false-positive rate  p  ~ (1 - e^(-k n / m))^k
optimal k            k  = (m / n) ln 2
bits per item for p  m/n = -ln(p) / (ln 2)^2  ~ 1.44 log2(1/p)
 
n = 10 billion URLs, p = 1%:
  m/n = 9.6 bits, k = 7  => m = 96 Gbit = 12 GB
n = 10 billion URLs, p = 0.1%:
  m/n = 14.4 bits, k = 10 => 18 GB

A false positive here means we skip a URL we have never crawled. At 1%, we would lose about 1% of new URLs, which is acceptable for a training-data crawl but not for an archive. False negatives are impossible: a URL in the filter is always reported as present.

A 12-GB filter fits in one large Redis instance (RedisBloom provides BF.ADD and BF.EXISTS) or can be sharded by URL hash across fetchers or parsers that own those hashes. A scalable Bloom filter (Almeida et al., 2007) grows by adding layers when the estimated count is exceeded. See Probabilistic Data Structures for Big Data.

Option 3: batch dedupe with sorted runs. IRLbot (Lee, Leonard, Wang and Loguinov, "IRLbot: Scaling to 6 Billion Pages and Beyond", WWW 2008) crawled over 6 billion pages from a single server. Its key structure, DRUM (Disk Repository with Update Management), avoids random disk lookups entirely. New URLs are buffered in memory and in disk buckets partitioned by hash; when a bucket fills, it is merged against the sorted on-disk set of seen URLs in one sequential pass. Sequential I/O is orders of magnitude faster than random I/O on disks, so this turns millions of random checks into a streaming merge. The cost is latency: a URL may wait minutes before it is known to be new. The same idea works at cluster scale as a periodic MapReduce or Spark job: join newly discovered URLs against the seen set, emit the new ones to the frontier.

What to choose. The pragmatic design is layered:

  1. A per-parser LRU cache of recently seen URL hashes (popular links like the home page or "About" page repeat constantly) removes a large share of duplicates for free.
  2. A Bloom filter, sharded by hash, answers "definitely new" for most of the rest.
  3. The URL table's conditional insert is the source of truth for anything the filter says "maybe seen", if exactness matters; otherwise the filter's answer is accepted.

9. Content deduplication: exact and near-duplicate pages#

Different URLs often serve the same content: mirrors, syndicated articles, print versions, pages reachable under many query strings, and scraper sites copying others. Studies of web crawls have long found that a large fraction of pages, often quoted as around a quarter to a third, are exact or near duplicates of others. For an LLM training corpus, duplicates are actively harmful: they waste compute and make the model memorise repeated text. So we dedupe content, not just URLs.

Exact duplicates

Hash the extracted text (or the raw HTML, but text is better since boilerplate and timestamps differ) with a strong hash such as SHA-256, and check whether we have seen that hash before.

  • Bad: compare with every stored page. Obviously impossible at 10 billion pages.
  • Good: hash index in the metadata DB. Store content_hash with each page and keep a global index (or a separate CONTENT_HASH table keyed by hash, mapping to the first URL that had it). A lookup is a single key read, which a key-value store handles at our 23,000 per second. This is exact, simple and also records which URLs share content, useful later.
  • Alternative: a Bloom filter of content hashes. It saves memory (about 12 GB at 1% for 10 billion items) and is fast, but gives false positives (a unique page is treated as a duplicate and dropped) and cannot tell you which page it duplicated. Since we already have a metadata DB, the hash index is usually the more practical choice; the Bloom filter is a reasonable optimisation in front of it.

Exact-duplicate checks happen in the parse stage. A duplicate page still has its URL marked as fetched; we just do not store its text again, and optionally do not extract its links again (they are the same links).

Near duplicates

Exact hashes miss pages that differ by a timestamp, an ad, a navigation bar, or a comment count. We need a similarity measure and a way to find similar pairs without comparing every pair.

Shingling and Jaccard similarity. Break each document into shingles: overlapping sequences of w words (for example w = 5). Two documents are similar if their shingle sets overlap a lot, measured by Jaccard similarity: J(A, B) = |A ∩ B| / |A ∪ B|. This is the approach of Broder, Glassman, Manasse and Zweig, "Syntactic Clustering of the Web" (WWW6, 1997), which found large clusters of near-identical pages in an AltaVista crawl.

MinHash. Computing exact Jaccard similarity across billions of documents is too expensive. MinHash (Broder, "On the Resemblance and Containment of Documents", 1997) gives a compact signature: apply k independent hash functions to all shingles of a document and keep the minimum value for each. The key property:

Pr[ min h(A) == min h(B) ] = J(A, B)

So the fraction of the k minimums that match estimates the Jaccard similarity. With k = 128, the standard error is about sqrt(J(1-J)/k), roughly 0.04 at J = 0.5.

Locality-sensitive hashing (LSH) to find candidates. Even signatures cannot be compared all-pairs at 10 billion. Split each 128-value signature into b bands of r rows (for example 16 bands × 8 rows). Hash each band; documents that share any band hash become candidates. The probability that two documents with similarity s become candidates is 1 - (1 - s^r)^b, an S-curve with its threshold near (1/b)^(1/r):

b = 16, r = 8: threshold ~ (1/16)^(1/8) ~ 0.71
  s = 0.9 -> candidate with prob 1 - (1 - 0.43)^16 ~ 0.9999
  s = 0.5 -> candidate with prob 1 - (1 - 0.0039)^16 ~ 0.06

Candidates are then verified by comparing full signatures. This is how large training-data pipelines dedupe at scale; MinHash with LSH is a common choice in published LLM data pipelines.

SimHash. Charikar's "Similarity Estimation Techniques from Rounding Algorithms" (STOC 2002) gives another fingerprint, estimating cosine similarity instead of Jaccard. Each document becomes a 64-bit fingerprint: hash each feature (word or shingle) to 64 bits, add its weight to a 64-element counter for each 1-bit and subtract it for each 0-bit, then set fingerprint bit i to 1 if counter i is positive. Similar documents have fingerprints that differ in few bits.

Manku, Jain and Das Sarma ("Detecting Near-Duplicates for Web Crawling", WWW 2007) showed this works at Google scale: with 64-bit SimHash fingerprints, pages whose fingerprints differ in at most 3 bits (Hamming distance ≤ 3) are near duplicates, across a corpus of about 8 billion pages. To find all fingerprints within distance 3 of a query quickly, they keep several permuted, sorted copies of the fingerprint table. By the pigeonhole principle, if two 64-bit values differ in at most 3 bits, then when the bits are split into 4 blocks, at least one block is identical. So for each permutation, look up exact matches on the leading block and check the Hamming distance of the few candidates.

MinHash or SimHash? MinHash estimates Jaccard over shingle sets and tunes nicely with LSH bands; it is standard in training-data dedupe. SimHash gives tiny 64-bit fingerprints that are cheap to store and compare, which made it attractive for a crawler that checks every fetched page online. Either is a strong answer; knowing why the fingerprint works is what impresses.

Where to do it. Exact dedupe runs inline in the parse stage. Near-duplicate dedupe is often a batch job after the crawl (or per day of crawl), because LSH works best over the whole corpus at once and the crawl does not need the answer immediately. Online near-dup checks matter more for a search-engine crawler, where storing and indexing duplicates is wasteful.

10. Crawler traps, spam and quality#

A crawler trap is a set of URLs that never ends. Some are deliberate (to waste bad bots' time), most are accidental:

  • Calendars: "next month" links forever, into the year 3000.
  • Infinite parameter combinations: faceted search where every combination of filters is a URL (?color=red&size=m&sort=price&page=7).
  • Session ids in URLs: every visit produces new URLs for the same pages.
  • Relative-link bugs: a misconfigured server returns the same page for any path, and a relative link a/ makes /a/a/a/a/... endlessly.
  • Soft 404s: missing pages return 200 with a "not found" page, so broken links look valid.

Defences, layered:

  1. Maximum depth. Track depth (hops from a seed) for every URL and stop extracting links beyond a limit, for example 15 to 20. Valuable content is rarely that deep.
  2. Per-host page budgets. Cap the pages fetched per host per crawl, scaled by the host's importance (for example by its inbound links from other hosts, which are harder to fake). IRLbot made this a central idea: its STAR (Spam Tracking and Avoidance through Reputation) scheme allocates crawl budgets to domains based on in-degree from other pay-level domains, so link farms that link only to themselves get small budgets.
  3. URL pattern limits. Cap URL length (for example 2,000 characters), path depth (for example 10 segments), and repeated path segments (/a/a/a). Detect parameter explosions by counting distinct query-parameter values per path pattern.
  4. Content-based detection. If many URLs on a host produce identical or near-identical content hashes, it is a trap or soft-404 pattern; stop crawling that pattern. Check for soft 404s by fetching a random non-existent URL on the host and fingerprinting the response.
  5. Normalisation. Stripping session ids and tracking parameters (Deep Dive 8) removes a whole class of traps.

Spam and low-quality content. For a training corpus, quality filters run in the parse or post-processing stage: language identification, text-to-markup ratio, minimum length, repetition ratios, keyword stuffing, adult content and toxicity classifiers, and blocklists of known spam domains. Low-quality hosts get their budgets cut for the rest of the crawl. Published LLM data pipelines describe many such heuristic and model-based filters; the crawler's job is to collect provenance (URL, host, fetch time, status, language) so those filters have what they need.

11. Distributed coordination: who crawls what?#

With dozens of fetcher machines and hundreds of parser workers, we must decide how work is divided. There are two broad models.

Model A: shared queue, stateless workers (our base design). Every fetcher reads from the same frontier queue. Coordination happens through shared services: Redis for politeness locks and rate limits, the metadata DB for URL state. This is simple and elastic: add a fetcher and it starts pulling work immediately, remove one and its messages reappear. The costs are a Redis round trip on every fetch and wasted reads when one host dominates the queue.

Model B: partition by host. Assign each host to exactly one fetcher using a hash of the hostname. That fetcher owns all URLs of the host, keeps its robots.txt rules, DNS entries, open connections and politeness timer in local memory, and runs a Mercator-style back-queue structure. No distributed lock is needed: politeness is guaranteed because only one machine ever talks to a host.

  • Routing URLs. When a parser discovers a URL, it computes owner = hash(host) and sends the URL to that owner's queue (a Kafka partition per owner group, or an owner-specific queue). Partitioning by host also means URL dedupe can be local to the owner, since a URL's host determines its owner.
  • Host versus domain. Partition by registered domain (pay-level domain, such as example.co.uk) rather than full hostname if you also want to rate-limit across subdomains like a.example.com and b.example.com. The Public Suffix List tells you where the registered domain begins.
  • Consistent hashing. Use consistent hashing so adding or removing a fetcher moves only about 1/N of hosts instead of reshuffling everything. UbiCrawler (Boldi, Codenotti, Santini and Vigna, "UbiCrawler: A Scalable Fully Distributed Web Crawler", Software: Practice and Experience, 2004) used exactly this: agents share no central coordinator, and each host is assigned by consistent hashing so that the system tolerates agent failures by reassigning only the failed agent's hosts. See Consistent Hashing and Partitioning and Sharding.
  • Skew. Hosts vary enormously in size, so hash ranges vary in load. Use many virtual nodes per fetcher, and move giant hosts (which are limited by politeness anyway, so they consume little bandwidth) or tiny-host-heavy ranges between fetchers based on measured load.

Membership and failover. In model B, the system must know which fetchers are alive and which partitions each owns.

  • With Kafka, the consumer group protocol does this: partitions are spread across live consumers and reassigned when one fails or joins. Use the hostname hash as the message key so all URLs of a host land in the same partition, and the partition's consumer is its owner. On failover, the new owner rebuilds per-host state (robots.txt from cache, timers start conservative).
  • Without Kafka, use a coordination service such as ZooKeeper or etcd: each fetcher registers an ephemeral node or a lease with a TTL; a leader (elected through the same service) assigns partitions and reassigns them when a lease expires. See ZooKeeper and etcd and Leader Election and Coordination Services.
  • Split brain. If a fetcher is partitioned from the coordinator but still running, two machines may briefly own a host and double its rate. Fencing (a partition epoch number checked before each fetch) or simply tolerating a brief doubled rate is the usual answer. Doubling one request per second to two for a few seconds harms nobody.

Which model to choose? For a five-day, 10-billion-page crawl on a managed cloud stack, model A is simpler to build and explain, and Redis handles 23,000 lock operations per second easily (a single Redis instance handles around 100,000 simple operations per second, and the keys shard by domain naturally). Model B is what large production crawlers converge on, because it removes the hot-path dependency and gives politeness for free. In an interview, presenting A first and then explaining when and why to move to B is a strong staff-level answer.

Geographic distribution. Crawlers can run fetchers in several regions so each host is crawled from a nearby region, reducing latency and cross-ocean bandwidth. Assign hosts to regions by the IP's location. This adds complexity (per-region queues, cross-region dedupe) and is rarely needed for a one-off crawl, but long-running search crawlers use it.

12. Recrawl, freshness and dynamic content#

The interview problem is a one-time crawl. But the moment someone asks "what about next month?", the design must handle recrawling: keeping a corpus fresh as the web changes. This is the main job of a search-engine crawler, where most fetches are refreshes rather than new URLs.

How often do pages change? Very unevenly. News home pages change every few minutes; most pages change rarely or never. Cho and Garcia-Molina's studies (for example "The Evolution of the Web and Implications for an Incremental Crawler", VLDB 2000) tracked hundreds of thousands of pages daily and found change rates differ by orders of magnitude between sites and domains (.com pages changing much faster than .gov or .edu), and that changes of a page are well modelled as a Poisson process with a page-specific rate λ.

Estimating the change rate. For each URL, keep a small history: how many recent fetches found the page changed (by content hash or 304). A simple estimate is λ ≈ changes / elapsed time, with corrections for the fact that several changes between two visits look like one. Cho and Garcia-Molina's "Estimating Frequency of Change" (ACM Transactions on Internet Technology, 2003) gives better estimators for exactly this.

Which refresh policy maximises freshness? The intuitive answer, "revisit each page in proportion to how often it changes", is wrong. Cho and Garcia-Molina ("Effective Page Refresh Policies for Web Crawlers", ACM Transactions on Database Systems, 2003) showed that with a fixed total crawl budget, a uniform policy (visit every page equally often) beats the proportional policy on average freshness. The optimal policy is between them and penalises pages that change too often: a page that changes every minute is stale again almost immediately whatever you do, so spending budget on it buys little freshness. Visit fast-changing pages somewhat more, but not in proportion, and give up on the fastest.

freshness of a page refreshed every I with change rate lambda:
  F = (1 - e^(-lambda I)) / (lambda I)
lambda I = 0.1  -> F = 0.95   (rarely changes: almost always fresh)
lambda I = 1    -> F = 0.63
lambda I = 10   -> F = 0.10   (changes 10x per visit: refreshing barely helps)

The URL scheduler. A recrawl system adds a scheduler that computes, for each known URL, its next due time from its change rate, its importance and the policy above. Due URLs are pushed into the frontier with a priority, alongside newly discovered URLs. Separate queues (for example "fresh" for news and sitemaps with recent lastmod, "normal", and "slow") let the fetch fleet split its budget by policy. Sitemaps and RSS feeds are cheap change signals: one fetch tells you which of a site's pages changed. Search engines also accept push notifications (for example the IndexNow protocol supported by Bing and others), which turns polling into events.

Dynamic, JavaScript-rendered content. Many modern sites ship a nearly empty HTML shell and build the page in JavaScript. A plain HTTP fetch sees no text. Options:

  • Skip it for a training corpus, accepting the loss, if the share of such pages is small.
  • Headless browser rendering with Chromium via Puppeteer or Playwright: load the page, run scripts, wait for network idle, then extract the rendered DOM. This costs one to several seconds of CPU and hundreds of MB of memory per page, perhaps 100 times the cost of a plain fetch. Google has described rendering pages in a second wave with an evergreen Chromium-based renderer.
  • Render selectively: detect pages whose extracted text is tiny but whose HTML is script-heavy, and send only those to a separate renderer pool with its own queue, autoscaling and sandboxing. Politeness still applies: one rendered page can make dozens of sub-requests to the same host.

Freshness for the training-data use case. A training crawl rarely needs minute-level freshness. A monthly or quarterly snapshot crawl, plus conditional GETs to skip unchanged pages, is usually enough. Common Crawl, for example, publishes periodic snapshots rather than a continuously fresh index.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Fetcher machine crashesIn-flight fetches lostQueue semantics: delete or commit only after the blob is stored; messages reappear after the visibility timeout; idempotent writes
Target site down or slowRetries pile up; fetch slots heldPer-layer timeouts; exponential backoff with jitter via visibility timeout; DLQ after 5 attempts; domain-level circuit breaker
Giant host (millions of pages)Crawl cannot finish in 5 days at 1 request per secondStart it first; prioritise its best pages; use dumps, APIs or sitemaps; accept partial coverage
One domain floods the queueFetchers waste reads deferring the same domainHost-partitioned frontier with per-host back queues; jittered deferral; per-host budgets
DNS resolver limits or latencyFetchers block on lookups; throughput collapsesLocal caches respecting TTLs; own caching resolvers; several upstream providers; prefetch; negative caching; async resolver
Redis politeness store failsNo rate limiting; risk of hammering sitesRedis replicas with failover; fetchers start at half rate after failover; locks with TTLs so stale locks expire
Metadata DB hot partitions or throttlingURL inserts and state updates slow; crawl stallsKey by URL hash, not host; Bloom filter and LRU cache in front; batch writes; on-demand or provisioned capacity with headroom
Blob storage request-rate limitsPUT throttling (503 Slow Down)Batch pages into large WARC objects; spread keys across prefixes; retry with backoff
Parse backlog growsSlower discovery of new URLs; frontier starvesAutoscale parsers on queue depth; raw HTML is safe in blob storage, so fetching continues
Crawler trapsUnbounded URL growth; wasted budgetDepth limit; per-host budgets; URL length and pattern limits; duplicate-content detection per host
Hostile content (bombs, huge pages, SSRF)Worker crashes, memory exhaustion, internal network probingStreaming size limits; sandboxed parsers; block private IP ranges; content-type filtering
Being blocked by sites or CDNsLost coverage, reputation damageStrict robots.txt compliance; adaptive rate on 429/503; clear user-agent and contact page; published IP ranges

What Interviewers Expect#

Mid-level#

  • Lay out a sensible data flow: seeds → frontier → fetch → store HTML → extract text and links → new URLs back into the frontier.
  • Produce a working high-level design with a queue for the frontier, fetchers, parsers, blob storage for content and a database for metadata.
  • Know that robots.txt exists and must be respected, and that crawlers need some rate limiting per domain.
  • Handle basic failures: retry failed fetches, avoid crawling the same URL twice with a seen set.
  • With prompting, do the basic capacity estimate (pages per second, storage) and see that many machines are needed.

Senior#

  • Split the crawler into stages with durable queues between them, explain why (isolation, independent scaling, re-runnable parsing), and keep content out of the queue.
  • Design retries properly: exponential backoff with jitter, a dead-letter queue, and the difference between permanent (404) and transient (503, timeouts) failures.
  • Go deep on politeness: robots.txt rules and caching, Crawl-delay, a per-domain rate limit with a lock in Redis, jitter to avoid synchronised retries, and adapting to 429 and Retry-After.
  • Show the five-day scaling maths: about 23,000 pages per second, bandwidth per machine, number of fetchers, and why the politeness ceiling for giant hosts dominates.
  • Discuss URL and content dedupe with concrete choices (normalisation, Bloom filter sizing, hash index), and explain crash recovery with idempotent processing.

Staff+#

  • Lead the conversation into three or more deep areas without prompting, choosing those most important to the stated goal (for a training corpus: quality, dedupe, throughput; for search: freshness and priority).
  • Bring non-obvious insights: DNS as an early bottleneck and how to fix it (own resolvers, several providers, prefetch); the frontier as front queues for priority plus per-host back queues for politeness; partitioning by host to make politeness local.
  • Reason about near-duplicate detection (MinHash with LSH or SimHash) and when to run it online versus in batch.
  • Cover traps and adversarial content: budgets by inbound links, SSRF, decompression bombs.
  • Discuss recrawl policy with the counter-intuitive uniform-versus-proportional result, and how the design evolves from a one-time crawl into a continuous one.
  • Be explicit about trade-offs and what you would build first, measure, and change later.
Deep Dive: the maths of a crawl, worked end to endShow

This block collects the numbers a staff engineer should be able to derive on a whiteboard, with the reasoning behind each.

1. Throughput from the deadline.

pages = 10^10, deadline = 5 days = 432,000 s
required rate = 10^10 / 432,000 ~ 23,150 pages/s
with 25% headroom for retries, robots.txt, redirects: ~29,000 requests/s

Retries and redirects are real traffic: if 10% of URLs need one retry and 10% redirect once, requests exceed pages by 20%. robots.txt adds one request per host per day, small in total (hundreds of millions of hosts over five days is about 1,000 per second, but it sits on the critical path of a host's first fetch).

2. Concurrency from Little's law. L = λ × W. With λ = 29,000 requests per second and W ≈ 1 s average (DNS cached, connection reused, a few hundred ms of server time and transfer), L ≈ 29,000 concurrent requests. If the average climbs to 3 s because of slow sites, L rises to 87,000. This is why timeouts matter: a 60-second tarpit holds one slot for as long as 60 normal fetches.

3. Bandwidth. The average HTML page is around 100 KB uncompressed in our estimate. Compressed on the wire, perhaps 20 to 30 KB.

uncompressed: 23,150 x 100 KB = 2.3 GB/s = 18.5 Gbps
gzip ~4x:     ~4.6 Gbps on the wire
per machine at 1 Gbps useful: 5..19 machines (compressed vs not)

4. Storage.

raw HTML: 10^10 x 100 KB = 1 PB uncompressed; WARC-gzip ~ 200-300 TB
extracted text: ~10% of HTML size ~ 100 TB, compresses to ~30-40 TB
metadata: 10^10 URLs x ~200 bytes = 2 TB (plus indexes, replicas: ~6-10 TB)

5. Bloom filter sizing. From m/n = -ln p / (ln 2)^2:

False-positive rateBits per URLHash functionsSize for 10 billion
10%4.836 GB
1%9.6712 GB
0.1%14.41018 GB
0.01%19.21324 GB

Each extra 4.8 bits per item cuts the error rate by 10×. Note that the filter must be sized for the final count; if you size for 1 billion and insert 10 billion, the false-positive rate climbs towards 100%. Plan for the total discovered URLs, which is often several times the number you will crawl, since most discovered URLs are never fetched.

6. The politeness ceiling.

host with P pages at 1 request/s needs P seconds
P = 432,000 pages is the most a single host can give in 5 days
P = 10,000,000 -> 116 days; P = 1,000,000 -> 11.6 days

The completion time is max(N / R, P_max / r), where N is total pages, R the cluster rate, P_max the largest host's page count and r the per-host rate. The first term is solved with machines; the second only with policy (priorities, budgets, bulk exports, negotiated rates).

7. Hosts in flight. To keep 29,000 requests in flight at one request per second per host with ~1 s fetches, at least about 29,000 distinct hosts must be ready at any moment, and more like three times that so a free fetcher always finds a ready host. A crawl over hundreds of millions of hosts satisfies this easily, but a crawl restricted to a few thousand domains (a vertical crawler for e-commerce, for example) does not, and is then bounded by politeness, not hardware.

8. Queue sizing. If the frontier queue holds the working window of URLs for the next hour, that is 23,150 × 3,600 ≈ 83 million messages of ~200 bytes each, about 17 GB. SQS has no practical limit on queue size (in-flight messages are limited to about 120,000 per standard queue, which matters here: 29,000 in flight is within the limit, but long visibility deferrals count as in flight too, so deferral-heavy designs can hit it). Kafka retains whatever disk allows.

Deep Dive: real crawlers and what each taught usShow

Mercator (Compaq Systems Research Center, late 1990s). Written in Java by Allan Heydon and Marc Najork. Its lasting contributions are the modular design (protocol modules, processing modules, pluggable URL filters), the two-layer frontier of priority front queues and per-host back queues, the content-seen test with document fingerprints to skip duplicate pages, a URL-seen test with an in-memory cache in front of a disk-based set, and the observation that DNS was a major bottleneck that justified a custom resolver.

IRLbot (Texas A&M, 2007-2008). Lee, Leonard, Wang and Loguinov showed that a single server could download over 6 billion pages in about 41 days, if the data structures are designed for disk. Three ideas stand out:

  • DRUM for URL-seen checks: batch, bucket by hash, and merge with the on-disk set sequentially, avoiding random I/O.
  • STAR for spam and traps: budgets per domain proportional to in-degree from other domains, so link farms cannot claim large budgets.
  • BEAST for politeness under budgets: delays URLs from low-budget domains in multiple queues rather than holding them in memory.

The paper also shows how quickly a naïve seen-set or frontier collapses as the crawl grows into billions: a lesson about data structures, not just machines.

UbiCrawler (University of Milan and CNR Pisa, early 2000s). Boldi, Codenotti, Santini and Vigna built a fully distributed crawler with no central coordinator, assigning hosts to agents with consistent hashing. Agents can join or fail, and only the affected hosts move. This is the template for the host-partitioned model in Deep Dive 11.

Googlebot. Google publishes guidance rather than internals, but some facts are documented: it supports robots.txt as standardised in RFC 9309 (Google led that standardisation and open-sourced its robots.txt parser in C++ in 2019), it does not support Crawl-delay, it adjusts its crawl rate automatically based on how a site responds (slowing down on errors and 429/503), and it renders JavaScript with an evergreen Chromium. Site owners can see crawl statistics in Search Console.

Heritrix (Internet Archive, mid-2000s onwards). An open-source, archival-quality Java crawler that writes WARC files. It emphasises faithful capture (every response, headers and all), configurable politeness and scope rules, and checkpointing of the crawl state. It is the crawler behind much web-archiving work.

Apache Nutch and StormCrawler. Nutch (started by Doug Cutting and Mike Cafarella around 2002-2003) is a batch crawler; its need for distributed storage and processing led to the ideas that became Hadoop. Nutch crawls in rounds: generate a fetch list from the crawl database, fetch, parse, update the database. StormCrawler (and its successors) is a streaming crawler built on Apache Storm, closer to our continuous pipeline.

Common Crawl. A non-profit that publishes regular snapshots of the web, each with billions of pages, as WARC, WAT (metadata) and WET (extracted text) files on public cloud storage. Its crawler (CCBot) respects robots.txt. Many LLM training datasets start from Common Crawl and then filter and dedupe it heavily, which shows that for training data, the post-crawl pipeline matters as much as the crawl.

What they share. Every production crawler converges on the same core: a prioritised, host-aware frontier; robots.txt and rate limits per host; aggressive DNS caching; URL normalisation and a seen set; content fingerprinting; budgets against traps; and durable, resumable state. The differences are in scale, freshness goals, and whether the output is an index, an archive or a dataset.

Deep Dive: the life of a URL, and a failure walkthroughShow

Every URL moves through a small state machine stored in the metadata DB. Making the states explicit is what makes the crawl resumable: after any crash, the state tells you exactly what remains to be done.

Walkthrough: a fetcher dies mid-download. Fetcher F7 receives URL U (ApproximateReceiveCount = 1), acquires the Redis lock for example.com, and starts downloading. The machine is reclaimed by the cloud provider.

  1. The Redis lock has a 30-second TTL, so example.com is unlocked within 30 seconds; no other host is affected.
  2. U's message was never deleted. When its visibility timeout (say 120 seconds) expires, it becomes visible again.
  3. Fetcher F12 receives it (ApproximateReceiveCount = 2), checks politeness (next_allowed may still be in the future if F7 had set it, so F12 may defer briefly), fetches U, writes the blob to raw/{crawlId}/{urlHash} and conditionally updates U's state from queued or fetching to fetched.
  4. F12 deletes the message and enqueues a parse job.

Nothing was lost, and nothing was duplicated except one partial download. If F7 had in fact finished writing the blob before dying, F12's write overwrites it with identical content, and the conditional state update is a no-op if state was already fetched. The parse job may be enqueued twice; the parser checks state fetched → parsed conditionally, so the second job exits early.

Walkthrough: a hosting provider goes dark. A provider hosting 200,000 small sites has a four-hour outage. Within minutes, fetchers see connection timeouts for thousands of hosts.

  • Each URL backs off exponentially (30 s, 1 min, 2 min, 4 min, 8 min). Without more, five attempts would be exhausted in about 15 minutes and all those URLs would go to the DLQ, even though the outage is temporary.
  • A better design adds a host-level circuit breaker: after, say, 10 consecutive failures, mark the host (or the IP block) as down for an increasing period (10 min, 30 min, 2 h) and park its URLs without spending attempts. Probe with a single request when the period ends.
  • Because hosts on one provider share IP ranges, a per-IP or per-autonomous-system breaker catches the whole outage at once.
  • DLQ monitoring should alert on spikes by host or IP, which separates "200,000 sites are down" from "our fetcher has a bug".

When the provider recovers, the breakers close one by one and the parked URLs flow back. The crawl loses four hours on those hosts but no data.

Walkthrough: Redis fails over. The primary politeness Redis dies; a replica is promoted within seconds, but recent writes (locks, next_allowed values) may be lost because replication is asynchronous. Fetchers that see a connection reset reconnect and switch to a conservative mode for five minutes: half their normal concurrency per host and doubled delays. Lost locks mean at worst two fetchers hit one host once each within a second; the conservative mode makes that rare and harmless. See Redis in Practice.

Walkthrough: a parser bug corrupts text extraction. Three days in, someone notices the extracted text drops all content inside <article> tags for one popular CMS. Because raw HTML is stored, the fix is a parser deploy and a re-parse job over the affected batches, read from blob storage. No refetching, no extra load on any website. This is the pay-off of separating fetch from parse.

Deep Dive: variants and how the design changesShow

The same skeleton serves several products. What changes is the objective.

Search-engine crawler (continuous). The goal is coverage plus freshness for an index. Most fetches are refreshes, so the scheduler (Deep Dive 12) dominates: change-rate estimation, importance scores from the link graph, sitemaps and push signals like IndexNow. Fetches feed an indexing pipeline rather than a text dump. Latency from discovery to index matters for news, so a fast lane exists for high-priority hosts. JavaScript rendering is a first-class stage. See the search engine case study for the indexing side.

LLM training-data crawler (this problem). The goal is volume and quality of text in a time window. Freshness matters little; dedupe and quality filtering matter enormously. Provenance (URL, fetch time, licence signals, robots.txt state at fetch time) must be recorded for compliance and dataset documentation. Opt-outs are increasingly important: several AI crawlers publish separate user-agent tokens so site owners can block AI training while allowing search crawling, and a responsible crawler honours those choices.

Vertical or focused crawler. For example, a price tracker crawls a few hundred e-commerce domains deeply and frequently. Politeness dominates the design because the host count is small: the cluster is bounded by hosts × per-host rate, not by machines. Extraction is structured (prices, stock, titles), often with per-site templates or schema.org markup, and changes are detected per field. Focused crawling (Chakrabarti, van den Berg and Dom, "Focused Crawling: A New Approach to Topic-Specific Web Resource Discovery", WWW 1999) uses a classifier to follow only links likely to lead to on-topic pages. See the price tracker case study.

Archival crawler. The goal is faithful capture for posterity, as the Internet Archive does. Every response is kept, including images, CSS and scripts needed to replay the page; dedupe stores references to identical payloads (WARC "revisit" records) instead of dropping them. Exact fidelity beats efficiency.

Small-scale crawler (one machine). For a few million pages, all of this collapses into one process: an async HTTP client, an in-memory frontier with per-host queues, a SQLite or RocksDB seen set, and files on disk. Knowing when not to build the distributed version is part of good judgement.

Evolution path for our crawler. Start with model A (shared queue, Redis politeness), measure, then move to host partitioning when Redis round trips or deferral waste show up in the metrics. Add near-dup dedupe as a batch job after the first crawl. Add recrawling with conditional GETs when the second crawl is requested. Add a renderer pool only when the share of JavaScript-only pages justifies its cost.

Deep Dive: law, ethics and being a good citizenShow

A crawler that is technically excellent but ignores the norms of the web will be blocked and may create legal risk. Interviewers increasingly ask about this, especially for AI training data. This is not legal advice; the law varies by jurisdiction and is changing, so real projects involve legal review.

  • robots.txt is a convention, now standardised, not a law. RFC 9309 says the rules are not a form of access authorisation. Still, ignoring it is widely seen as bad faith and has featured in disputes. Honour it fully, including user-agent-specific rules aimed at AI crawlers.
  • Terms of service, logins and paywalls. Do not crawl behind logins, bypass paywalls, or solve CAPTCHAs. Content that requires authentication is outside the scope of a public crawl.
  • Personal data. Pages contain names, emails and phone numbers. Data protection laws such as the EU's GDPR apply to processing personal data even if it is public. Training pipelines typically filter or mask personal information and honour removal requests.
  • Copyright. Copying content for training raises copyright questions that are being argued in courts in several countries. The crawler should record provenance and licence signals (for example Creative Commons markers) so downstream decisions can be made per document.
  • Load and cost on others. Every request costs the site owner bandwidth and compute. Politeness limits, conditional GETs and compression are not just technical niceties; they reduce the burden we impose.
  • Transparency. Identify the crawler clearly, publish what it is for and how to opt out, and answer abuse reports quickly.
Deep Dive: observability for a five-day crawlShow

A long crawl needs dashboards that answer "are we on track?" and "is anything hurting a site?" at a glance. See Observability: Logs, Metrics and Traces.

Throughput and ETA. Pages fetched per second (overall and per fetcher), bytes per second, and an ETA computed from the remaining frontier size divided by the current rate. Alert if the ETA passes the deadline.

Health of each stage. Queue depth and age of the oldest message for the frontier, parse and DLQ queues. A growing parse queue means scale parsers; a growing DLQ means investigate. Fetch latency percentiles (p50, p95, p99) broken down into DNS, connect, TLS, first byte and download.

Errors by class. Rates of timeouts, DNS failures, 4xx, 5xx, 429, robots-blocked, oversized, wrong content type. A sudden shift (for example 429 doubling) usually means our politeness is too aggressive somewhere.

Politeness compliance. Maximum observed requests per second to any single host (should never exceed the configured limit), number of hosts with open circuit breakers, and robots.txt fetch failures. This metric protects reputation; page it like a production incident.

Quality and dedupe. Duplicate rate (exact and near), average extracted text length, language mix, and pages dropped by quality filters. A sudden change usually means a parser regression or a trap.

Resource usage. Open connections and file descriptors per fetcher, CPU per parser, Redis operations per second and latency, metadata DB throttling events, blob storage 503 Slow Down responses.

Sample a small fraction of fetches (for example 0.1%) for full tracing across fetch, store, parse and dedupe, so a single bad URL can be followed end to end.

Deep Dive: parsing, link extraction and text extractionShow

The parse stage looks simple ("get the text and the links") but has many sharp edges, and its output is the product.

Robust HTML parsing. Real-world HTML is often malformed: unclosed tags, broken nesting, stray bytes. Use a parser that implements the HTML5 parsing algorithm from the WHATWG standard, which defines how browsers recover from every kind of error (for example html5ever in Rust, Gumbo or lexbor in C, jsoup in Java, or lxml with an HTML5 front end in Python). Regex-based extraction breaks on edge cases and is a common source of bad links and garbled text.

Link extraction rules.

  • Extract href from <a> and <area>, plus <link rel="canonical">, <link rel="alternate" hreflang> and, depending on scope, <iframe src> and <frame src>.
  • Resolve relative URLs against the page's base URL: the final URL after redirects, or the <base href> element if present. ../img/a.html on https://ex.com/blog/post/ becomes https://ex.com/blog/img/a.html under RFC 3986's resolution algorithm.
  • Skip javascript:, mailto:, tel: and data: links and anything not http or https.
  • Respect <meta name="robots" content="noindex, nofollow"> and the X-Robots-Tag HTTP header: nofollow means do not follow links from this page for crawling purposes, and noindex means do not include this page in an index (for a dataset, treat it as a signal to exclude). Link-level rel="nofollow" is a hint about endorsement; many crawlers still discover the URL but do not pass link credit.
  • Record anchor text with each link. It describes the target page, often better than the target describes itself, and was a key signal in early search engines.
  • Apply the depth limit, per-page link cap and scope filters (allowed domains, file extensions to skip such as .jpg, .zip, .exe) before sending links to the frontier.

Text extraction and boilerplate removal. For a training corpus, we want the main content, not menus, footers, cookie banners and "related articles" lists that repeat on every page of a site.

  • Basic: strip tags, scripts and styles, collapse whitespace. Keeps all boilerplate.
  • Better: heuristics on text density and link density. Blocks with long sentences and few links are content; blocks that are mostly links are navigation. Kohlschütter, Fankhauser and Nejdl's "Boilerplate Detection using Shallow Text Features" (WSDM 2010) showed that simple features like word count and link density per block classify boilerplate well; it is the basis of the boilerpipe library.
  • Best for scale: a well-tested extraction library (trafilatura, jusText, Mozilla's Readability algorithm) combined with site-level boilerplate learning: text blocks that appear on many pages of the same site are template, so remove them. This is cheap to compute in the batch dedupe job, since repeated blocks show up as repeated shingles.

Language and encoding. Run language identification (fastText's language identification model or CLD3 are common) on the extracted text and record the language and confidence. Multilingual crawls need correct charset decoding before this (Deep Dive 7), or the language detector sees noise.

Structured data as a bonus. Many pages include JSON-LD or microdata with schema.org vocabulary (articles, products, recipes, events). Extracting it is cheap and gives clean titles, authors, dates and prices. It is optional for a text dataset and central for vertical crawlers.

Output format. Write extracted text as compressed batch files (for example JSON Lines or Parquet, about 1 GB each), each record holding the URL hash, final URL, fetch time, language, content hash and text. Batching is friendlier to blob storage and downstream analytics than one object per page, and Parquet lets the training pipeline read just the columns it needs. Keep the mapping from each record back to its raw WARC record so any document can be traced to its exact source bytes.

Cost check. At 5 to 50 ms of CPU per page for parsing plus extraction, 10 billion pages need between about 14,000 and 140,000 CPU-hours. On spot instances at a few cents per vCPU-hour, that is a modest line item next to bandwidth and storage, which is why re-parsing from stored HTML is an affordable way to fix extraction bugs.

Deep Dive: seeds, scope and what to crawl firstShow

With a five-day deadline and a politeness ceiling, we will not fetch everything we discover. Most crawls discover several times more URLs than they fetch. So the order of the crawl decides the quality of the result.

Choosing seeds. Seeds should be diverse, high quality and well connected, so the crawl reaches most of the valuable web within a few hops.

  • Curated lists of popular domains (public top-site rankings), directories, and Wikipedia's outbound links, which point to a broad, editorially filtered set of sites.
  • The URL lists from a previous crawl, or a public snapshot such as Common Crawl's URL index, which jump-start coverage immediately.
  • Sitemaps of seed domains, which list pages that are poorly linked internally.
  • For a multilingual corpus, seeds per language and country-code domain, or the crawl will be dominated by English.

Scope rules. Decide up front what is in and out: schemes (http, https), content types (HTML only for a text corpus), maximum depth, excluded domains (known spam, adult content if required, sites that opted out), and maximum URLs per host. Scope rules run in the parser before URLs enter the frontier, which keeps the frontier and seen set small.

Breadth-first is a surprisingly good order. Najork and Wiener ("Breadth-First Crawling Yields High-Quality Pages", WWW 2001) crawled 328 million pages with Mercator in breadth-first order and found that pages discovered early had higher average PageRank than those discovered later. Intuitively, important pages have many inbound links, so a breadth-first crawl from good seeds reaches them sooner. Plain FIFO order is therefore a sensible baseline for the frontier.

Better: prioritise by estimated importance during the crawl. Full PageRank needs the whole link graph, which we do not have until the crawl ends. Online approximations work well:

  • Inbound link counts from distinct hosts, updated as parsers discover links. A URL linked from 500 different sites is worth fetching before one linked from a single page.
  • OPIC (Abiteboul, Preda and Cobena, "Adaptive On-Line Page Importance Computation", WWW 2003) gives every page some "cash". When a page is fetched, its cash is split among the pages it links to, and the crawler fetches pages with the most accumulated cash first. Over time this converges towards a PageRank-like importance, computed incrementally with no global iteration.
  • Host quality signals from earlier crawls or the current one (text quality, duplicate rate, spam scores) raise or lower the priority of all a host's URLs.

The front queues of the Mercator frontier (Deep Dive 3) are exactly where these priorities plug in: the prioritiser maps the score to one of F priority levels.

Putting dedupe and priority together. The diagram shows where each filter sits between parsing and the frontier. Cheap filters run first so the expensive ones see less traffic.

When the budget runs out. At the deadline, the frontier still holds billions of URLs. That is expected and fine: by construction they are the lowest-priority ones. Record them, because they seed the next crawl and tell you which hosts were under-covered.

Key Takeaways#

  • Pipeline the crawl into stages (frontier → fetch → store raw HTML → parse → dedupe → new URLs) joined by durable queues. Failures stay in one stage, each stage scales on its own resource, and stored HTML makes parsing re-runnable. Keep payloads out of queues: pass ids, store content in Object Storage and Blob Storage. See Asynchronous Processing and Message Queues.
  • Retries need backoff, jitter and a dead-letter queue. SQS visibility timeouts with ChangeMessageVisibility and a redrive policy give this almost for free. Add a host-level circuit breaker so outages do not burn every URL's attempts. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  • Acknowledge work only after its result is durable, and make every write idempotent. At-least-once processing plus idempotency is what makes a five-day crawl survive crashes. See Delivery Guarantees: At-Most, At-Least and Exactly-Once and Idempotency and Safe Retries.
  • Politeness is a hard requirement. Follow robots.txt as standardised in RFC 9309 (24-hour caching, 4xx means allowed, 5xx means disallow), honour Crawl-delay with a cap, limit each domain to about one request per second, and adapt to 429 and Retry-After. See Rate Limiting and Throttling.
  • The frontier is priority plus politeness: front queues order by value, per-host back queues and a heap of next-allowed times enforce spacing. Partitioning hosts across fetchers with consistent hashing makes politeness local. See Consistent Hashing.
  • Do the maths: 10 billion pages in 5 days is about 23,000 pages per second, about 23,000 fetches in flight by Little's law, tens of fetcher machines, and a politeness ceiling of about 432,000 pages for any single host. See Back-of-the-Envelope Estimation.
  • DNS is an early bottleneck. Cache with TTLs, run your own caching resolvers, spread load across providers, prefetch, and cache negatives. See DNS: The Domain Name System.
  • Dedupe URLs and content. Normalise URLs per RFC 3986, then check a Bloom filter (about 12 GB for 10 billion URLs at 1%) in front of the metadata DB. Hash text for exact duplicates; use MinHash with LSH or SimHash for near duplicates. See Probabilistic Data Structures for Big Data.
  • Defend against traps and hostile content with depth limits, per-host budgets, URL pattern limits, streaming size limits, sandboxed parsers and blocked private IP ranges. See Security Fundamentals for System Design.
  • Recrawling is a scheduling problem: estimate change rates, prefer near-uniform refresh over proportional refresh, and use conditional GETs, sitemaps and push signals to spend the budget well.