System design practice

Web Crawler

medium queues rate-limiting probabilistic external-api object-storage durability

A polite crawler with a durable frontier, per-host rate limits and a Bloom filter for seen URLs.

Solve it in your browser Read the lesson first

Design the crawler behind a search engine's index: it starts from a few seed URLs, downloads pages, finds the links in them and keeps going, for billions of pages a month. It must be polite: a website that the crawler hammers blocks it, or goes down.

Functional requirements

Use these use case and scenario names exactly: the traffic, requirements and tests in problem.proschi refer to them.

Scale

Constraints

What is given

problem.proschi declares web, the websites (an external system that answers a fetch in about 300 ms), and holds the traffic, requirements and tests. Add the frontier, the fetchers, the per-host state, the page store, the parsers, the seen-URL set, the connections and the two use cases. Both use cases start where the work waits: the frontier hands a URL to a fetcher, and a queue of fetched pages hands a page to a parser; each is acknowledged (the response to that first step) when the work is done.

How your design is checked

You write the design as text in Proschi. Tests run in your browser: a simulation of the traffic above checks latency, availability, cost and what happens when a machine fails. How the simulation works.

Start designing

Lesson · 12 min read

Learn it: Web Crawler #

Web Crawler: a polite loop that never forgets a URL #

A crawler looks like the simplest program in the world: download a page, find its links, download those. At a few billion pages a month it becomes a lesson on queues: the work list outgrows your pace, almost every link is one you have seen, and the websites are someone else's servers that you must not knock over.

What you'll learn #

The problem, explained #

Who uses it. A search engine's indexing pipeline. Nobody waits on a single fetch, but the crawl rate decides how fresh the index is.

Functional requirements.

Non-functional requirements.

What is given, and why. given.proschi declares the websites as one external system answering in about 300 ms. They are slow, they fail, and you cannot add replicas to them: the crawler has to be reliable around them.

What the tests check.

Back-of-the-envelope #

pages fetched (about 4.5 billion a month)
1.8k/s
downloaded, about 470 TB a month
180 MB/s
links to deduplicate
90k/s
new URLs into the frontier
5.4k/s
Bloom filter for 10B URLs at 1%
≈ 12 GB
fetches in flight
≈ 540
QuantityArithmeticResult
Pages fetched2k × 88%about 1.8k/s
Pages a month1.76k × 2.6M sabout 4.5 billion
Bytes downloaded1.8k × 100 KB180 MB/s, about 470 TB a month
Links extracted1.8k × 5090k/s
New URLs1.8k × 35.4k/s into the frontier
Seen set, exact10B URLs × 8-byte hash80 GB, plus overhead
Seen set, Bloom filter at 1%10B × 9.6 bitsabout 12 GB
Concurrent fetches1.8k/s × 0.3 s (Little's law)about 540 in flight

Throughput is the goal, not latency. The p99 limits catch saturation: a fetcher pool or seen set that cannot keep up shows as a growing queue, and in the model as exploding latency.

The fetchers move bytes. Each page crosses a fetcher twice, in from the website and out to the page store: 360 MB/s through the pool, against 200 MB/s per service replica in the model. Bandwidth, not request count, sizes the fetchers: two replicas would run at 90%, four run at 45%, and at 60% with one lost. Little's law (in flight = rate × time each takes) gives about 540 fetches at once, so each fetcher holds many connections open with asynchronous I/O.

The seen set is the busiest component. 90k checks a second is close to one Redis node's 100k in the model, so it takes several nodes, enough to survive losing one: three run at 30%, and at 45% with one lost. A database doing 90k conditional inserts a second costs several times more.

The frontier grows. 5.4k new URLs a second go in, and only 1.8k a second leave for good. A real crawl never empties it; it prioritises (important URLs, often-changing pages) and drops or postpones the rest.

Concepts #

The URL frontier #

The frontier is the crawler's to-do list and its most valuable state: weeks of discovery, billions of URLs. It must survive restarts, and hand work to many fetchers in parallel without giving one host to two of them.

A log such as Kafka, partitioned by host, does this. The host is the partition key: many hosts share a partition (there are 100 million of them), but all of one host's URLs land in the same one. One consumer owns each partition, so one fetcher owns each host.

A log has no built-in "deliver later". A URL that is not yet due is written back to the log with a due time, and comes round again; a real crawler often adds a delay queue for these.

Deep dive Mercator's two-layer frontier

The classic design (Mercator's) has two layers. Front queues order URLs by priority. Back queues hold one host each, and a fetcher thread drains one back queue at a time, so the frontier itself enforces one request per host. A log partitioned by host gives you much of that.

Politeness: one host at a time #

Your crawler is a guest. Three rules keep it welcome:

RuleWhat it means
robots.txtFetch each host's robots.txt, cache it for a day or so, and never fetch what it disallows. Many sites also set a Crawl-delay in it: not part of the standard, but a polite crawler honours it.
One connection per host, with a delayCommonly a few seconds, or a multiple of how long the last response took: a slow site gets crawled more slowly.
Back off on errorsA host that answers 429 or 503, or times out, gets its delay doubled.

At 2k URLs a second, keep a small record per host (robots rules, earliest next fetch, current delay) in a fast store. Before fetching, read it: if the host is due, set the next allowed time and fetch; if not, put the URL back.

Deep dive In Proschi: rate-limited outbound calls
title "Rate-limited outbound calls"

jobs    "Jobs"          [AWS SQS] x2
worker  "Sender"        [Worker]  x2
limits  "Partner limits" [Redis]  x2
partner "Partner API"   [Third Party API]

jobs   -> worker  : deliver
worker -> limits  : check partner budget
worker -> partner : call

usecase "Send to partner" {
  jobs     -> worker  : job 81
  worker   -> limits  : INCR partner:7:second
  limits  --> worker  : 3 of 5
  worker   -> partner : POST /events
  partner --> worker  : 202
  worker  --> jobs    : delete message
}

Deduplicating URLs with a Bloom filter #

Most links point to pages already crawled or queued: navigation bars, footers, an article linked from fifty places. Without deduplication the frontier fills with copies and pages are downloaded again.

Normalise each URL (lowercase the host, drop the fragment, sort or strip tracking parameters), hash it, and ask: seen before?

A database table of seen URLs works, expensively: 90k conditional inserts a second need many nodes, paying for durability the set does not need, since a lost filter can be rebuilt from the frontier and the page store.

Content can repeat under different URLs (mirrors, session ids). A hash of the page body, or a SimHash for near duplicates, catches those after the fetch.

At-least-once crawling #

Where you acknowledge a URL decides what a crash does. Commit on receipt, and a crash mid-download loses it for good. Commit after the page is stored, and a crash redelivers it and fetches the page twice.

That is at-least-once, the right default: a duplicate fetch costs a little bandwidth, and storing a page under the hash of its URL makes the second write harmless (idempotent). The same holds for a URL going back to the frontier (busy host, failed fetch): commit only after the re-enqueue is acknowledged.

Failures and retries #

At billions of fetches a month, failure is constant: DNS errors, timeouts, resets, 5xx, pages that never finish. So a failed fetch is a normal scenario: record it, raise the host's delay (exponential backoff), and put the URL back with a retry count; after a few attempts, drop it until the next crawl cycle.

Set a short timeout too: a slow host should cost a fetcher seconds, not minutes. In the model, the -x call to the websites followed by a successful re-enqueue is a fallback: the use case completes, so a website's 99.9% does not cap the crawler's availability.

Designing it step by step #

1. Clarify. Pages a month (4.5 billion, about 1.8k a second), page size (100 KB), what is stored (raw HTML), politeness rules, re-crawl frequency (out of scope) and JavaScript rendering (no).

2. Draw the loop. Frontier → fetchers → page store → queue of fetched pages → parsers → seen set → frontier. Two consumer pools, each acknowledging its input only when its output is safely written.

3. Fetch path. Read the host's record. Due: set the next allowed time, fetch, store the page, publish an event for the parsers, commit. Not due: re-enqueue with a due time, commit. Fetch failed: back off, re-enqueue with a retry count, commit.

4. Parse path. Read the page from the store, extract and normalise links, check all of them (x50) against the seen set, enqueue the ~3 new ones (x3) partitioned by host, commit.

5. Size it. Fetchers by bandwidth (360 MB/s) and the seen set for 90k operations, each with one node lost; at least two of everything else. Add up the bill.

6. Wrap up. Prioritisation and re-crawl scheduling (often-changing pages first), DNS caching (resolution is slow and resolvers rate-limit), spider traps (infinite calendars: cap depth and URLs per host), content deduplication.

Common mistakes #

No politeness (wrong/no-politeness). Fetchers download whatever they get, as fast as they can: fastest on paper, blocked in practice by small sites hit with bursts of parallel requests. It fails A host is asked before it is fetched.

Enqueueing every link (wrong/enqueue-every-link). Without a seen set, all 50 links per page enter the frontier: 90k writes a second, mostly duplicates fetched again. It fails Links are deduplicated before they reach the frontier, and with the frontier that busy, losing one of its nodes pushes Parse links past 200 ms (survive any node failure).

A database as the seen set (wrong/seen-urls-in-a-database). Correct, durable and about $6,150 a month instead of $2,600, because eight NoSQL nodes are needed for 90k conditional inserts a second. It fails the budget.

The frontier in Redis (wrong/frontier-in-redis). Fast, until a restart loses billions of URLs and every re-enqueued one. It fails The frontier is a durable queue and Crawl page is durable.

Acknowledging before storing (wrong/ack-before-store). Committing the URL on receipt means a crash, or a site that times out, loses it forever. It fails A URL leaves the frontier only once its page is stored and Crawl page is durable.

Others. Deduplicating at fetch time; one global FIFO queue, which sends a burst of fetchers to one host whenever a page links to its own site; no fetch timeout, so slow hosts tie up the pool.

In the interview #

Open with the loop and two invariants, then the sizing numbers: 1.8k pages a second, 90k links a second to deduplicate, 180 MB/s downloaded.

Likely follow-ups:

Further reading #

Now design it

Review cards for this problem

Short questions on the ideas it needs, from the review cards. Review them daily so they stick.

More system design problems