Design a web crawler
Fetch a page, extract its links, repeat, a billion times a month. The hard parts are politeness per host, deduplicating URLs and content, and deciding what to fetch again.
The problem
The first web crawlers appeared in 1993, when the web was small enough to walk in full. By 1994 crawlers were already overloading small servers, and Martijn Koster proposed robots.txt so that site owners could tell robots what to leave alone. The convention spread by agreement long before it was written down formally as RFC 9309 in 2022.
The naive design is a queue of URLs and a pool of threads. Each thread takes a URL, downloads it, extracts the links and appends them to the queue. A team that runs this against the real web hits four problems within hours:
- The queue fills with links from whichever large site was reached first, so every thread hits the same host and the site blocks the crawler.
- The same page is fetched again and again under slightly different URLs.
- A calendar page with a “next month” link produces URLs for ever.
- Threads spend much of their time blocked on DNS lookups.
Interviewers like this question because there is no user-facing request path to hide behind. You have to design a pipeline, reason about a queue that is too big for memory, and show that you can be a good citizen of a network you do not control.
Requirements
Functional
- Start from a set of seed URLs and discover pages by following links.
- Fetch HTML pages and store them for downstream consumers such as an indexer.
- Obey
robots.txtand a per-host rate limit. - Avoid fetching the same URL twice in a cycle, and detect duplicate content.
- Revisit pages to keep the copy fresh, sooner for pages that are important or change often.
Out of scope unless asked: rendering JavaScript, images and video, pages behind a login, and the indexing and ranking that consume the crawl.
Non-functional
- Scale: 1 billion pages a month.
- Politeness: at most one request in flight per host, with a delay between requests. This is a hard requirement.
- Robustness: survive malformed HTML, slow servers, huge responses and traps.
- Durability of progress: a crash must not lose the frontier or repeat a month of work.
- Freshness: important pages revisited within a day, the long tail within a month.
- Extensibility: adding a new content type or processing step should not change the fetch loop.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Fetch rate | 1B per month / 2.6M seconds | about 400 per second, design for 800 |
| Bandwidth | 400 per second x 100 KB of HTML | 40 MB per second, about 320 Mbit/s |
| Page storage | 1B x 100 KB, compressed about 4 to 1 | 100 TB raw, about 25 TB a month |
| Known URLs | assume 10 new URLs survive per page fetched | 10 billion |
| Bloom filter | 10B x 10 bits | 12.5 GB |
| Exact seen set | 10B x 16-byte hash | 160 GB before overhead |
| Hosts in flight | 400 per second at 1 request per host per second | at least 400, in practice thousands |
The 100 KB page size and the factor of 10 for discovered URLs are assumptions; say so and move on.
Two conclusions drive the design. First, the hardware is modest: a few hundred megabits of bandwidth and a few dozen machines. Second, the limits are elsewhere. Politeness means throughput comes only from spreading work across many hosts, and the state needed to remember 10 billion URLs does not fit in one process without care.
API
A crawler has no public API. It has internal interfaces between its stages, and those are what to write on the board.
POST /v1/seeds { "urls": ["https://example.org/"], "priority": "high" }
Frontier (internal RPC)
Lease(worker_id, max_hosts) -> [ { host, urls[], delay_ms, lease_expires_at } ]
Complete(host, results[]) status and fetch time per URL; host becomes eligible again after its delay
Add(urls[]) from the URL filter and the recrawl scheduler
Output stream
page.fetched { url, fetched_at, status, content_hash, storage_ref }
A lease has an expiry. If a fetcher dies, its hosts become available again when the lease runs out, and the URLs are fetched a second time. Fetching is idempotent, so that is harmless.
Data model
URL record, keyed by a 128-bit hash of the normalised URL:
| Column | Notes |
|---|---|
url_hash, url, host |
the hash is the key; the host is the shard key |
status, priority |
queued, fetched, failed, excluded |
last_fetched_at, next_fetch_at |
drive recrawl |
etag, last_modified |
for conditional GET |
content_fingerprint |
to detect change and duplicates |
fetches, changes |
history used to estimate the change rate |
Host record: parsed robots.txt rules and when they were fetched, the crawl delay, the next time the host may be contacted, resolved IP addresses, and a count of consecutive errors for backoff.
Page store: object storage. Billions of tiny objects are slow and expensive to list and read, so fetchers append pages to large compressed archive files (WARC is the standard format) and record the file and offset.
The URL and host tables are sharded by a hash of the host name. All of a host’s URLs then live together, which is what the frontier and the recrawl scheduler both want. See sharding for the general trade-off of that choice: big hosts make big shards.
High-level architecture
The fetch loop. A fetcher leases a batch of hosts from the frontier. For each URL it checks the cached robots.txt rules, resolves the host through a local DNS cache, and issues an HTTP GET with a timeout and a size cap. It appends the response to the page store and puts a pointer on the fetched-pages stream.
Parse and filter. Parser workers read the stream, compute a content fingerprint, and check it against the fingerprint store. If the content is new they extract links. Each link goes to the URL filter, which normalises it, drops excluded patterns, and asks whether it has been seen. Unseen URLs are recorded in the URL store and added to the frontier. The parser also writes the fetch result back to the URL record.
Recrawl. A scheduler scans the URL store for records whose next_fetch_at has passed and re-enqueues them.
Putting a stream between fetching and parsing means a slow parser never holds a network connection open, and the two pools scale separately. It is a log, not a work queue, so a new consumer can replay pages without a fresh crawl.
Deep dives
The frontier: priority and politeness
The frontier has two jobs that pull against each other. It must hand out important URLs first, and it must never hand out two URLs for the same host too close together. The design from the Mercator crawler (Heydon and Najork, 1999) separates the two.
Step 1 of 8
The frontier has two layers. Front queues decide which URLs matter most. Back queues decide when each host may be contacted. Every newly discovered URL enters at the top.
Read the steps as text
- The frontier has two layers. Front queues decide which URLs matter most. Back queues decide when each host may be contacted. Every newly discovered URL enters at the top.
- The prioritiser scores each URL. A news home page that changes every hour goes into the high priority front queue. A deep archive page on a blog goes into the low one.
- The router pulls from the front queues, choosing the high queue more often than the low one, and moves each URL into the back queue that belongs to its host. One back queue holds URLs for one host only.
- A heap holds one entry per back queue, keyed by the earliest time that host may be contacted again. A fetcher thread asks the heap which host is due now, and removes that entry while it works.
- The thread takes one URL from that host's back queue and downloads it. No other thread can pick this host, because its entry is out of the heap until the fetch finishes.
- When the fetch finishes, the host goes back into the heap with a later time, such as now plus one second. Until that time arrives, every thread works on other hosts.
- Meanwhile another thread serves blog.example from its own back queue. Throughput comes from crawling many hosts in parallel, never from hitting one host harder.
- When a back queue runs empty, the router refills it from the front queues and may hand it to a new host. Priority is decided at the front and politeness at the back, so an important site cannot be starved and a small site cannot be flooded.
Front queues express priority. There is one FIFO queue per priority level, and a prioritiser assigns each URL a level from signals such as how many pages link to it and how often it has changed. A selector takes from high-priority queues more often than from low ones, so low-priority URLs are slow, never starved.
Back queues enforce politeness. Each back queue holds URLs for exactly one host, and a table maps host to queue. A min-heap holds one entry per back queue, keyed by the earliest time that host may be contacted. A fetcher pops the heap, waits until that time if needed, takes one URL from the queue, fetches it, and pushes the host back with a new time. When a back queue empties, it is refilled from the front queues. A rule of thumb from that design is about three times as many back queues as fetcher threads, so a thread rarely has to wait.
Across machines. Assign each host to one frontier shard by hashing the host name, ideally with consistent hashing so that adding a shard moves few hosts. One shard then owns everything about a host: its queue, its next-contact time and its robots rules. Politeness is local state, and no distributed lock is needed. Links to hosts owned by other shards are forwarded in batches. The frontier holds billions of URLs, so only the head of each queue sits in memory and the rest is on disk.
robots.txt. Fetch it before the first request to a host, and cache the parsed rules. RFC 9309 says a cached copy should not be used for more than 24 hours unless the file is unreachable. A 4xx response means no rules exist. A 5xx response means the crawler must treat the whole site as disallowed until the file is readable again.
Deduplicating URLs and content
Normalise first. Lowercase the scheme and host, drop the default port and the fragment, resolve . and .. segments, and remove known tracking parameters. Without this, one page appears under dozens of spellings.
The URL-seen test runs for every extracted link, tens of thousands of times a second, so it must be in memory. A Bloom filter at 10 bits per URL fits 10 billion URLs in 12.5 GB with about 1% false positives. It never says “new” for a URL it has seen. It sometimes says “seen” for a new URL, and that URL is then lost. For a broad crawl, losing 1% of long-tail URLs is often acceptable. Where it is not, treat “possibly seen” as a prompt to check the exact store, which now receives only a small share of lookups.
Content duplicates arise even when URLs differ: mirrors, session ids in the path, printer-friendly versions. A hash of the body catches exact copies. Near-duplicates, such as pages that differ by a timestamp or an advert, need a similarity-preserving fingerprint. SimHash produces a 64-bit value in which similar documents differ in only a few bits. Google’s 2007 paper on near-duplicate detection reported that 64-bit fingerprints with a Hamming distance of at most 3 worked well across 8 billion pages. A duplicate is recorded as an alias and not stored again.
Traps are sets of URLs that never end: calendars, faceted search with every combination of filters, session ids that make each visit look new, and pages generated deliberately to snare robots. No single check stops them. Use several budgets together: a cap on pages per host per cycle that grows with the host’s importance, limits on URL length and path depth, lower priority for URLs with many query parameters or repeated path segments, and a blocklist that operators can edit.
Recrawl policy
A page is fetched again when the expected value of a fresh copy is highest. Two inputs matter: how important the page is, and how likely it is to have changed.
Estimate the change rate from history. If the fingerprint differed on the last visit, shorten the interval, say by half. If it did not, lengthen it. Clamp the result, for example between one hour and 30 days. A news front page settles at the minimum and an archived article drifts to the maximum.
Make unchanged pages cheap. Send If-None-Match with the stored ETag, or If-Modified-Since, and a server that supports conditional requests answers 304 Not Modified with no body. Sitemaps with lastmod dates are a useful hint, though not every site keeps them accurate.
Bottlenecks and failure modes
- DNS. Resolver calls are often synchronous and slow, and a crawler makes far more distinct lookups than a normal application. Run a local caching resolver, use asynchronous lookups, and resolve a host when it enters a back queue, before a fetcher needs it. See DNS.
- Fetcher crash. Leases expire and the hosts return to the heap. Some URLs are fetched twice.
- Frontier shard lost. Queues are persisted and replicated. In the worst case, rebuild the shard from URL records whose status is queued.
- Slow or hostile servers. Set connect and total timeouts, cap the response size and the number of redirects, and back off per host on 429 and 503, honouring
Retry-After. - One huge host. At one request a second, a host yields 86,400 pages a day, so a site with 100 million pages would take over three years. Give big hosts a budget and crawl their most important pages.
- Bloom filter filling up. The false positive rate climbs once the filter holds more than it was sized for. Monitor the fill ratio and rebuild a larger filter from the exact store.
- Poison pages. A page that crashes the parser is retried a few times and then moved to a dead-letter queue.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Frontier structure | Front queues plus per-host back queues | One priority queue | Keeps priority and politeness independent; more moving parts |
| Host ownership | One shard per host by hash | Shared queue with a lock per host | No coordination on the hot path; big hosts make uneven shards |
| URL-seen test | Bloom filter in front of an exact store | Exact store only | Memory-speed answers; about 1% of lookups need a second check |
| Content dedup | Exact hash and SimHash | Exact hash only | Catches near-copies; fingerprint lookups cost more |
| Recrawl | Adaptive interval per page | Fixed cycle for everything | Spends fetches where pages change; needs history per URL |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Ask what the crawl is for (search index, archive, price monitoring), because that sets freshness and scope. Confirm HTML only, no JavaScript rendering. Say politeness and robots.txt are hard requirements, not extras.
- 5:00 to 9:00
Capacity estimates 4 min
Derive pages per second, bandwidth, monthly storage and the size of the seen set. State the conclusion that hardware is modest and the real limits are per-host politeness and deduplication state.
- 9:00 to 12:00
Interfaces 3 min
There is no public API. Describe seed submission, the frontier's lease and complete calls, and the stream of fetched pages that downstream consumers read.
- 12:00 to 16:00
Data model 4 min
URL record, host record and the page archive. Explain why you shard by host and why pages are packed into large archive files instead of one object each.
- 16:00 to 25:00
High-level design 9 min
Draw the loop. Frontier, fetchers with DNS and robots caches, page store, parser, URL filter, back to the frontier. Narrate one URL going all the way round, then add the recrawl scheduler.
- 25:00 to 33:00
Deep dive: the frontier 8 min
Front queues for priority, one back queue per host, a heap of next-contact times. Then explain how hosts are partitioned across machines so politeness needs no distributed lock.
- 33:00 to 39:00
Deep dive: deduplication and traps 6 min
URL normalisation, Bloom filter in front of an exact store, content hashes and SimHash for near-duplicates. Name two kinds of crawler trap and the budgets that contain them.
- 39:00 to 43:00
Failure modes and trade-offs 4 min
Fetcher crash, frontier shard loss, slow or hostile servers, DNS as a hidden bottleneck. Mention recrawl policy if it has not come up.
- 43:00 to 45:00
Wrap-up 2 min
Summarise the loop in three sentences and name what you would add next, such as JavaScript rendering or per-IP politeness.
Key takeaways
- A crawler is a loop, and the frontier is the component that decides what the loop does next. Spend your design time there.
- Split the frontier in two. Front queues express priority, back queues hold one host each, and a heap of next-contact times enforces politeness.
- Assign each host to exactly one frontier shard, so the per-host rate limit is local state and needs no distributed lock.
- A Bloom filter at about 10 bits per URL answers "have I seen this?" in memory with roughly 1% false positives. Back it with an exact store when missing a page matters.
- Deduplicate content as well as URLs. An exact hash catches mirrors, and SimHash catches pages that differ only in an advert or a timestamp.
- Throughput comes from crawling many hosts at once. At one request a second, a single host yields at most 86,400 pages a day however many machines you own.
- Recrawl by observed change rate and importance, and use conditional GET so an unchanged page costs a 304 and no body.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What are the two layers of a Mercator-style URL frontier?
Front queues, one per priority level, decide what is fetched sooner. Back queues, one per host, with a heap of next-contact times, decide when each host may be contacted.
How do you enforce per-host politeness across many crawler machines?
Partition hosts by hash of the host name so each host is owned by one frontier shard. That shard alone schedules the host, so the delay is local state with no distributed lock.
How big is a Bloom filter for 10 billion URLs at 1% false positives?
About 10 bits per URL with 7 hash functions, so 100 billion bits, which is about 12.5 GB.
What does a crawler do when robots.txt returns 404, and when it returns 503?
404 (any 4xx): no rules exist, so crawl freely. 503 (any 5xx) or unreachable: assume everything is disallowed and try again later. Cache the file for at most about a day.
Exact versus near-duplicate content detection?
Exact uses a hash of the body and catches mirrors and URL aliases. Near-duplicate uses SimHash, where similar pages have fingerprints within a few bits of each other.
Name three defences against crawler traps.
A page budget per host, limits on URL length and path depth, and lower priority for URLs with many query parameters or repeating path segments. Add a manual blocklist for the rest.