Design a Web Crawler
How to design a web crawler that fetches a billion pages a month, including the URL frontier, politeness, duplicate detection and crawler traps.
On this page
A web crawler downloads web pages automatically. It starts from a small set of seed URLs, fetches each page, extracts the links, and adds the links it has not seen before to a list of pages still to fetch. Search engines use crawlers to collect the pages that they later index.
The fetch loop itself is simple. The design is hard because the crawler must not overload any website, must not fetch the same page twice, must survive sites that generate endless URLs, and must keep hundreds of downloads in flight. The steps below follow A Framework for Any Design.
Clarify the problem
Design a web crawler.
What is the crawler for, for example a search index or an archive, and does it fetch only HTML or other file types as well?
It feeds a general search index, and it only needs HTML pages.
How many pages does it need to fetch, and how fresh do they have to be?
About a billion pages a month. Popular pages should be refreshed more often than the rest.
Then my priorities are to never overload a website, to avoid wasting fetches on duplicate pages, and to spend the fetch budget on the pages that matter most. Indexing is out of scope.
- Functional: start from seed URLs, fetch HTML pages, extract links and add the new ones to the to-do list, store every fetched page, and recrawl pages over time, with important pages recrawled more often.
- Non-functional: the crawler sends at most one request at a time to any one site, with a gap between requests, and obeys robots rules. It fetches about 1 billion pages a month and schedules each URL once per crawl cycle. It keeps working when sites are slow or hostile, and a crash loses no frontier state.
- Out of scope: indexing, ranking, rendering JavaScript, media files and pages behind a login.
Estimate the scale
A month has about 30 × 86,400 ≈ 2.6 million seconds. The crawler sets its own pace, so the target is a steady rate with headroom.
- Fetch rate: 109 pages ÷ 2.6 × 106 seconds ≈ 385 pages a second, which we round to 400. Plan for 800 a second to allow catching up.
- Bandwidth: 400 pages a second × 100 KB = 40 MB/s, about 320 Mbit/s.
- Open connections: at about 1 second per fetch, Little's law (in flight = rate × time) gives 400 open downloads, or 800 with headroom.
- Politeness ceiling: at one request a second per site, a site with 1 million pages takes about 11.6 days to crawl once. Large sites, not bandwidth, limit freshness.
How much storage does one month of raw HTML take, before compression?
- 1 billion pages fetched a month
- About 100 KB of HTML per page
Show the working
- 109 × 100 × 103 B = 1014 B = 100 TB
- HTML compresses by about 4 times, so the crawler stores about 25 TB a month in object storage
Estimate 100 TB (anything from 30 TB to 300 TB is a good answer)
A crawler has no public users. Write down the messages between its internal parts and the message it sends to the indexing team.
Compare with a model answer
The frontier needs an operation to add URLs, which is used for seeds and for parsed links alike. It needs an operation that gives a fetcher the next URL it may fetch now, and one that reports the result. Each fetched page produces an output record for the indexer.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
frontier.add(urls: [ { url, priority, discovered_from } ])
-> accepted count; URLs already seen are dropped silently
frontier.lease(fetcher_id) -> { url, host, lease_id, lease_until }
-> or "nothing ready, retry in N ms" when every host is cooling down
frontier.complete(lease_id, result)
result: fetched(status, content_hash) | not_modified | failed(reason, retry_after?)
-> an expired lease is handed out again, so a dead fetcher loses no URL
event PageFetched { url, fetched_at, status, content_hash, blob_key }
-> published to a stream that the indexer consumesThe API decision to argue is that fetchers lease URLs instead of popping them. If a fetcher pops a URL and then crashes, the URL is lost for good, because it is already marked as seen and will never be added again. A leased URL goes back out after lease_until passes. The cost is that a slow fetcher that is still alive may cause a second download.
What records does the crawler keep about URLs, hosts and page content, and what does it ask of each one?
Compare with a model answer
There is a URL record keyed by the URL hash, holding whether the URL has been seen and when it is next due. There is a host record with the robots rules and the next time a request is allowed. Page bytes go to object storage. The question "have I seen this URL?" is asked about 50 times per page, so it gets its own structure.
Model the data
-- one row per known URL, partitioned by host hash
urls: url_hash BIGINT PRIMARY KEY -- 8-byte hash of the normalised URL
url TEXT -- up to about 2 KB
host TEXT
priority SMALLINT
next_fetch_at TIMESTAMP
last_status SMALLINT
content_hash BIGINT NULL -- fingerprint of the last body
-- one row per host
hosts: host TEXT PRIMARY KEY
robots_rules TEXT -- parsed robots.txt, refreshed daily
crawl_delay_ms INT -- 1,000 unless the site asks for more
next_allowed_at TIMESTAMP
ip_cache TEXT, ip_expires TIMESTAMP
-- page bodies: object storage, key = url_hash + fetch date, gzip-compressedThe URL table is accessed by hash for lookups and inserts, plus a scan for URLs that are due, and it never needs joins. That fits a wide-column or key-value store such as Cassandra, partitioned by host so that the machine that schedules a host also owns its URLs. Page bodies are large and written once, so they belong in blob storage.
URLs must be normalised before they are hashed, otherwise one page appears under many hashes. Normalising means lowercasing the scheme and host, removing the default port and the #fragment, and sorting and pruning query parameters. For example, HTTP://Example.com:80/a?b=2&a=1#top becomes http://example.com/a?a=1&b=2.
Sketch the crawl loop: where URLs wait, which component downloads them, where the page bodies go, and how newly found links come back without creating duplicates.
Compare with a model answer
A frontier hands URLs to fetchers. The fetchers download each page, store the body and pass it to parsers. The parsers extract links, drop the ones already seen and add the rest to the frontier.
High-level design
A crawl is a breadth-first search of the web. The frontier is the queue, and the seen-URL set is the visited set.
request and replyasynchronous message
- in flight
- 1
1The frontier leases
bakery.example/menuto a fetcher for 60 seconds, because the host's delay has passed and the page is high priority.- in flight
- 1
- bytes
- 92 KB
2The fetcher downloads the page with non-blocking I/O, so no thread waits. The response is 200 OK, 92 KB, and takes about 1 second.
- in flight
- 1
- bytes
- 92 KB
3The body is compressed and stored together with its fingerprint.
- in flight
- 0
- links found
- 0
4The fetcher sends a message to the parsers and completes its lease with the frontier, which frees the fetcher for the next URL.
- links found
- 50
5A parser extracts 50 links from the page, then normalises and hashes each one.
- links found
- 50
- new
- 10
6The parser sends all 50 hashes to the seen set in one insert-if-absent batch. 40 of them were already known, because most links point to pages the crawler has seen.
- links found
- 50
- new
- 10
7The 10 new URLs go to the queues of their hosts.
- host delay
- 4 s
8Later the same host returns
503twice. The frontier doubles that host's delay to 2 seconds and then to 4 seconds, so a struggling site gets less traffic.
Deep dives
The URL frontier: politeness and priority
The frontier has two jobs. It must never send two requests to the same host at once or too close together, and it must hand out the most valuable URLs first. A single first-in, first-out queue does neither. Pages link mostly to other pages on their own site, so one page produces a run of URLs for the same host, and a FIFO queue would send them to fetchers back to back.
The usual design has two layers. The front layer is a small number of priority queues. A URL goes into a high-priority queue when its page changes often or has many incoming links. The back layer has one queue per host. The host queues are refilled from the priority queues with a preference for the high ones. To decide which host to serve next, the frontier keeps a min-heap of hosts ordered by the time each host may next be fetched.
host, ready_at = heap.peek()if ready_at > now: wait until ready_atheap.pop(); url = queue[host].pop()lease url to fetcheron complete: heap.push(host, now + delay[host])- heap (host @ ready time)0a @ 9.81b @ 10.32c @ 11.0
- now
- 10.0 s
1Three hosts are in the heap, each ordered by the time it may next be fetched. The clock reads 10.0 s.
- heap (host @ ready time)0b @ 10.31c @ 11.0
- now
- 10.0 s
- busy
- a
2Host
ahas been ready since 9.8 s, so its next URL is leased. Hostaleaves the heap, which means no second fetcher can use it. - heap (host @ ready time)0b @ 10.31c @ 11.0
- now
- 10.0 s
- busy
- a
3Another fetcher asks for work. The top of the heap is
bat 10.3 s, which is still in the future, so the fetcher waits 0.3 s. - heap (host @ ready time)0c @ 11.0
- now
- 10.3 s
- busy
- a, b
4At 10.3 s host
bis ready and its next URL is leased. - heap (host @ ready time)0c @ 11.01a @ 11.9
- now
- 10.9 s
- busy
- b
5The fetch from
afinishes at 10.9 s. With a 1 s delay, hostagoes back into the heap at 11.9 s.
To scale the frontier, split it by host across about 10 machines using consistent hashing. Each host then lives on one machine, so politeness needs no coordination.
Deduplicating URLs
With 50 links per page and 400 pages a second, the seen set answers 20,000 lookups a second, almost all of them "already seen", and holds 10 billion URLs. Two details keep it correct. The check must be insert-if-absent, a single atomic step, so that two parsers cannot both add the same link. And a crash between marking a URL as seen and queueing it would lose that URL for good, so a periodic sweep of the URL table re-queues any URL that is marked as seen but has no fetch scheduled.
Full URLs or hashes. Storing every URL as text is exact but takes about 1 TB for 10 billion URLs, and every check is a network read. Instead, the crawler can store only an 8-byte hash of each normalised URL, split across machines by hash. For 10 billion URLs that is 80 GB, or 8 GB on each of 10 machines. With 64-bit hashes you expect only about 3 accidental matches among 10 billion URLs, so the set is effectively exact.
Bloom filter. A Bloom filter is a bit array with k hash functions. Adding a URL sets k bits, and checking a URL reads them. If any bit is 0 the URL is definitely new. If all bits are 1 the URL is probably seen, because other URLs may have set those same bits. A 1% false-positive rate needs about 9.6 bits per URL and 7 hash functions, so 1010 URLs take about 1010 × 9.6 bits ≈ 12 GB.
The false positives are the catch to state out loud. A new URL that is wrongly reported as seen is never crawled, and it hits the same bits every time it is found, so it stays skipped for as long as that filter is used. At 100 billion URLs the exact hash set would need 800 GB while the filter needs 120 GB, and that is where the filter becomes worth its cost.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Full URLs in a database | The answer is exact, and you can inspect what has been seen. | It takes about 1 TB, and every check is a network read. | The crawl is small, or you need a durable record behind a faster check. |
| 8-byte hashes, sharded in memory Usual default | It takes 80 GB in total, 8 GB on each of 10 machines, and is effectively exact. | It needs 80 GB of memory in total. | The seen set must not drop pages. This is the default here. |
| Bloom filter | It takes about 12 GB at a 1% false-positive rate. | About 1% of new URLs are wrongly treated as seen and never crawled. | Memory is the hard limit and losing a few pages is acceptable. |
Choosing which URLs to crawl first
A crawl is closer to a breadth-first search than a depth-first one, because following one chain of links deep into a single site would hit that host's politeness limit immediately and would reach important pages late. The priority of a URL combines signals such as how many pages link to it, how close it is to a seed, and how often its page has changed in the past.
Deduplicating content
Different URLs often serve the same page, for example mirror sites and links that only differ in a ?ref= parameter. The crawler stores a 64-bit fingerprint of each page body, about 8 GB for 1 billion pages, and skips parsing any body whose fingerprint it already knows.
DNS and fetch throughput
A fetch spends nearly all of its time waiting for the network. With non-blocking I/O, 10 machines with 80 open connections each cover the planned 800 downloads in flight.
DNS is a common hidden bottleneck. An uncached lookup takes 10 to 200 ms, and standard resolver calls often block a thread. The fix is to run a caching resolver next to the fetchers, keep each address for its time to live, and resolve a host just before its turn comes up.
Slow and hostile responses
Some servers send data very slowly, return an enormous body, or redirect in a loop, and a few of them could use up the open connections of the whole crawl. The fetcher therefore sets a connect timeout and a total timeout for each request, stops reading a body after a size limit such as a few megabytes, follows at most a handful of redirects, and skips responses whose content type is not HTML. A URL that fails these limits is reported as failed, and the host's delay grows as it does for errors.
Robots rules and crawler traps
Before crawling a host, the fetcher downloads its /robots.txt file and the frontier caches the rules for a day. The crawler skips disallowed paths and honours any longer crawl delay. A server error on that request means the host is off limits for now, and a 404 means it has no rules.
Some sites generate endless URLs. Examples are a calendar whose "next month" link never ends and filters that combine into millions of pages. The crawler defends against traps with limits: a maximum URL length of about 2,000 characters, a maximum path depth, and a maximum number of pages per host per crawl cycle. It also flags any host where most pages turn out to have duplicate fingerprints.
Bottlenecks and failures
At 10 times the load, about 4,000 fetches a second, the fetchers and parsers scale out by adding machines, and bandwidth grows to 3.2 Gbit/s. The seen set approaches 100 billion URLs, where a Bloom filter pays off. The limit that does not move is politeness, because large sites cannot be fetched faster. Freshness therefore has to come from better priorities and from conditional requests with If-Modified-Since, where a 304 Not Modified response costs almost nothing.
| When this fails | What happens | What you do |
|---|---|---|
| A fetcher | The URLs it holds on lease wait until their leases expire. | After 60 seconds the frontier leases those URLs to other fetchers. |
| A frontier machine | The hosts it owns are not crawled, and the rest of the crawl continues. | The queues are stored on disk and replicated, so a standby takes over that range of hosts from the last checkpoint. |
| A seen-set shard | Links in its hash range cannot be checked. | A replica takes over, or the shard is rebuilt from the URL table, and parsers retry. The crawler must never treat an unknown answer as "new". |
| The DNS resolver | Hosts with a cached address keep working, and new hosts wait. | Run two resolvers, skip hosts whose lookup fails, and retry them later. |
| A website | Requests time out or return 5xx errors. | Back off exponentially, and after several days of failures lower the host to the lowest priority. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | Draws a queue, fetchers and a database, and proposes a global rate limit to avoid overloading sites. |
| Mid | Estimates the fetch rate and storage, uses a queue per host, hashes URLs for the seen set, and respects robots rules. |
| Senior | Builds the frontier from priority queues plus per-host scheduling, partitioned by host. Compares a hash set with a Bloom filter, uses leases instead of pops, and names politeness as the limit on freshness. |
Why not use a Bloom filter? It is much smaller.
A filter for 10 billion URLs takes about 12 GB, compared with 80 GB for the hashes. But roughly one in a hundred new URLs is wrongly reported as seen, and because it hits the same bits every time, it is not crawled for that whole cycle. 80 GB spread over ten machines is cheap, so I would rather be exact. If the crawl grew to 100 billion URLs, I would switch to a filter.
Follow-up questions
How do you decide when to recrawl a page?
Schedule each page according to how often its fingerprint changed on earlier fetches, and recrawl important pages sooner. Conditional requests make an unchanged page cost only a 304 response, so recrawling is cheap.
How would you crawl pages that need JavaScript to render?
Detect pages whose useful content only appears after scripts run, and send only those to a separate pool of headless browsers. Rendering takes far more CPU than parsing HTML, so it stays an exception.
How do you know the crawler is healthy?
Watch the fetch rate, the duplicate share and the error rate per host. The most useful measure is the age of the oldest high-priority URL that is already due, because it shows whether important pages are going stale.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".