Design a web crawler
Read first: Queues and logs, DNS and CDNs
A crawler has a fixed fetch rate, a per-host delay, and a queue of URLs that are due. Dedup happens on a canonical form before you enqueue, and again with a unique key so two workers cannot insert the same page. You split the budget between refresh and discovery so the index does not go stale, and a host's robots rules are instructions you cache rather than a path you memorize.
A crawler does not have a person waiting on one request. It has a budget of fetches per second, a host that can tell you to slow down, and two ways to waste the budget. You can fetch the same address again, or you can discover forever and never refresh a page you already indexed. Politeness and that split decide the design. The queue is how you enforce both.
Requirements
The user of the crawl is a search index for a seeded set of sites, documentation and a slice of the public web you chose to cover. A person queries that index later. They are not in this design except as the reason freshness matters.
Functional requirements:
- Fetch pages, extract text and links, and hand the text to the index pipeline.
- Discover new addresses from the pages you fetch and from site maps operators publish, which are files that list what they want found. A site map is a hint. It is not an order to fetch everything today.
- Do not fetch a path the host’s robots rules disallow, and do not outrun the delay those rules ask for.
- Recrawl on a schedule so a page that changed is not stuck at the copy you saw last year.
- Rebuild the work list from durable state if the queue is lost.
Non-goals:
- Crawling the entire public web. The seed list is the product. Say that in the first minute so you do not invent a thousand-machine fleet.
- Rendering every script-heavy page in a browser. This design fetches the document and parses links and text. A browser farm is a cost discussion you open only if they ask.
- A perfect near-duplicate detector for prose that was lightly edited. You will hash the extracted text and catch identical bodies. Fuzzy duplicates are a later system.
- Ignoring an operator who tells you to stop. You identify yourself with a stable agent string so they can find you and block you. You do not disguise the crawler.
Assumption: completeness is allowed to take days for a large new site. Freshness of pages already in the index is not allowed to fall to zero while you drink that site.
Estimation
Assumptions:
- 80 million pages in the corpus once you are in steady state. Not the whole web. A seeded product.
- Average document size 60 KB. Extracted text averages 5 KB. Both assumptions.
- Freshness tiers: 10 percent of pages recrawled daily, 30 percent weekly, 60 percent every 30 days.
- Average 400 pages per host, so about 200,000 hosts.
- Default politeness is one fetch per second per host, and slower when the host asks. Assumption.
- You do not apply a user-traffic peak multiplier. A crawl should be flat. A spike is how you become an incident on someone else’s site.
daily tier 0.10 * 80e6 = 8.00e6 fetches
weekly tier 0.30 * 80e6 / 7 = 3.43e6
monthly tier 0.60 * 80e6 / 30 = 1.60e6
total = 13.03e6 fetches per day
13,030,000 / 86400 = 151 per second
13,030,000 / 1e5 = 130 per second
A day is 86,400 seconds. The 1e5 shortcut gives 130, about 14 percent under the exact 151. You schedule a flat 150 fetches per second. One million fetches a day would be about 12 per second. You are a bit over ten times that, on purpose, all day.
150 * 60 KB = 9 MB/s inbound, about 72 Mbps
80e6 * 5 KB extracted = 400 GB of text
times 3 replicas of the text = about 1.2 TB
raw documents, if you kept them all, 80e6 * 60 KB = 4.8 TB
You do not keep every raw document forever. Daily fetch volume is 13 million times 60 KB, about 780 GB a day. A 7 day retention of raw bytes, so you can reparse after a bug, is about 5.5 TB, and that retention is the expensive part. Extracted text is what the index needs. Raw bytes can live in object storage with a retention rule and their own checksums. Cost here is “three copies of the text is 1.2 TB, raw retention is a week of fetch volume,” not a price quote.
Politeness turns the global 150 into a parallelism requirement. At one fetch per second per host you need about 150 hosts in flight to fill the budget. You have about 200,000 hosts. You are not short of hosts. You are short of permission to hit one of them harder. If only 10 hosts are due, you crawl at about 10 per second and you leave budget unused. That is correct. You do not borrow against a host’s delay to catch up.
High-level design
flowchart LR
seeds[Seed hosts] --> frontier[Due queue]
table[URL table] --> frontier
frontier --> lease[Per host lease]
lease --> worker[Fetch worker]
worker --> rules[Robots cache]
worker --> dedup[Canonical check]
dedup --> table
worker --> text[Extracted text]
The URL table is the source of truth: canonical key, host, next time due, last fetch, content hash, status. The frontier is a queue of due work, competing consumers, acked after the table is updated. If the queue disappears, a scheduler re-enqueues from next due in the table. The queue is an optimization so workers are not polling 80 million rows. The table is what you can rebuild from.
Shard the table by host. One host’s addresses live together, and the worker that holds the host lease is the one reading them. Sharding by the full address instead would let many workers fetch one host at once, which is the politeness bug.
Two kinds of due work sit in the frontier, even if they share a broker: refresh of addresses you already have, and discovery of addresses you do not. Workers pull with a budget split, below. A single FIFO will let a million new links from one site stand in front of every refresh, or the reverse, depending on which you happen to push first. Priority is the design. FIFO is how you lose it.
Deep dive
Politeness per host
The global rate is not a politeness cap. The per-host delay is. Default assumption: one request per second per host, burst of one. If the host’s rules ask for a longer delay, you wait the longer of yours and theirs. Your default is a floor on courtesy, not a target you force when they asked for slower.
A worker must hold the host’s lease to fetch. The lease lasts 30 seconds, an assumption, and the worker renews it while it still has due addresses and the delay has elapsed. A second worker that picked up a duplicate queue message for the same host does not fetch. It delays or requeues. The lease is the mutex. The queue will, under at-least-once delivery, hand you duplicates. That is fine if the lease is real and a bug if the lease is “whoever dequeued it.”
When the worker dies, the lease expires and someone else may take the host. You might fetch one extra time a bit early. That is a small politeness dent. Handing the host to two live workers is a large one. Expiry is what keeps a dead worker from blocking a host forever. Set it longer than a slow fetch and shorter than “this host is stuck until a human notices.”
Reuse connections to a host. Do not open a new one per address and call it 150 per second of progress. DNS is cached for the record’s TTL. DNS with a short TTL means more lookups and a faster change when they move the site. Do not keep using an address for an hour if the record was allowed to be cached for a minute.
A fetch that redirects is a different host, with that host’s rules and that host’s delay. You do not spend the first host’s budget on the second, and you do not apply the first host’s allow list to the second. Cap redirects. Assumption: 3 hops. A loop must not pin a worker.
Robots rules, in words
Before the first fetch from a host, the worker retrieves that host’s robots rules. Operators publish a small document that lists path prefixes they do not want fetched and, sometimes, a delay between requests. You parse it, cache it, and treat a disallowed prefix as not fetchable. Those addresses never go out on the wire. If you had already queued them, the worker drops them.
If the document is absent, you use your default delay and you may fetch. Absence is not a trap. Failure is different. If the request for the rules fails, you do not treat the failure as permission. You back off that host and try the rules again later. Crawling a host whose wishes you failed to read is how a bad morning at their edge becomes “the crawler ignored us.”
Cache the parsed rules. Assumption: refresh them about every 12 hours, and sooner if an operator complains. A long cache is how you keep fetching a path they disallowed this morning. A very short cache multiplies rule fetches. Twelve hours is a choice you can defend and then change.
You send a stable agent string on every request, including the rules fetch, so an operator can see who you are in their logs and can block you. Hiding is a product decision you are not making.
A site map, the file some sites publish that lists addresses they would like crawled, is an input to discovery. You still dedupe, you still apply the robots rules, and you still count those fetches against the host’s delay and against the per-host discovery cap. A site map of a million addresses is not a million fetches today.
Dedup
Two strings can be the same page. Canonicalize before you enqueue, and write the policy down, because an unwritten policy will be “improved” by each new hire:
- Lowercase the host.
- Drop the fragment. The piece of the address after the marker that means “inside this page” is not a different document for this crawler.
- Remove a default port.
- Sort query parameters.
- Drop tracking parameters on a list you maintain. Assumption: the list exists, and a bad entry can merge two pages that were actually different. Review the list. Do not let it grow in a handler.
- Pick a trailing-slash rule and apply it the same way every time.
The durable dedup is a unique key on the canonical hash in the URL table. A worker that inserts a duplicate loses the insert and does not schedule a second copy. Check-then-insert without the unique key races: two workers both see “new” and both enqueue.
A Bloom filter in front of the table saves lookups. It is a probabilistic set. If it says the address is new, it is new, and you insert. If it says the address might be known, you check the table. False positives cost a lookup. A false negative would drop a page you have never seen, so you do not use a structure that can do that, and you do not treat the filter as the source of truth. The table is the source of truth. The filter is rebuilt from the table if it is lost. Bloom filters show up in storage engines for the same “skip what cannot be here” reason. Here the set is addresses.
Content dedup is a second stage. Hash the extracted text. If two addresses return the same hash, the index stores one body and both addresses if you care about both. You still fetched both, unless the canonical rule already collapsed them. Content hash does not replace URL dedup. URL dedup is what stops you fetching the same address every minute.
Freshness versus completeness
You have 150 fetches per second. Every fetch spent on a new address is a fetch not spent refreshing. In steady state, assumption, put 70 percent of the budget on refresh and 30 percent on discovery. When the corpus is young and the index is empty, invert that. The rate stays 150 either way. Only the mix changes.
A page’s next due time starts from its tier. When you fetch and the content hash changed, shorten the interval, down to a floor. When it did not change, lengthen the interval, up to a cap. Assumption: floor of one day for ordinary pages and one hour for a tier you marked as news, cap of 30 days. That is a policy, not a measurement of the web. It spends fewer refreshes on pages that sit still, and it notices a page that started changing.
Completeness is the discovery budget plus a per-host cap. Assumption: 5,000 new addresses per host per day, and a depth cap of 8 links from that host’s seed. A new site with a million pages takes many days. That is acceptable. A new site that is allowed to occupy the entire 150 per second will freeze freshness for the 80 million pages you already promised to keep current.
The trap you design for is an infinite generator: a calendar or a list that always links to the next date or the next page number, with no last page. Depth and the per-host cap stop the budget bleed. Also stop scheduling a pattern whose only change is an ever-increasing counter once you have followed it past a limit you set. You will not name every trap in the interview. You will say the caps exist so one pattern cannot own the month.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Flat rate, no peak | You do not burst a host to catch a daily quota | A backlog takes days, and a “catch up” instinct is a bug |
| Shard and lease by host | One host is fetched at its delay, even if the queue duplicates | A hot host’s other addresses wait, and a lease expiry can double-fetch once |
| Shard by address | Even spread in the table | Many workers hit one host and your politeness is fiction |
| Unique key on the canonical form | Two workers cannot both own a new address | You must write the canonical rules down or the key splits one page into two |
| Bloom filter in front | Most new addresses avoid a table read | A loss of the filter is fine, a false “new” is not, so the table stays authoritative |
| 70 percent refresh | The index tracks pages you have | A large new site is ingested slowly |
| 70 percent discovery | The corpus grows fast | Everything you already indexed goes stale |
The budget row is the product decision. Politeness is not a trade you get to reopen because the index is behind.
Failure modes
- A host starts failing. Workers retry, the host is the one in trouble, and your retries make it worse. This is the retry storm, pointed at someone else. A breaker per host pauses that host for minutes. Exponential backoff with full jitter applies to the host, not to a single address, or you will rotate through their addresses and keep the load constant. Other hosts continue. Retries are per dependency, and here the dependency is the host.
- Dedup store down. If you fail open, you enqueue addresses you have already crawled and you hammer hosts you meant to visit once. Fail closed on discovery: do not enqueue new work you cannot dedup. Keep refreshing from the due rows you already trust, if you can read them. If you cannot read the table at all, stop. A crawler that cannot remember what it has seen is an outage you inflict on other people.
- DNS resolver down. Hosts whose addresses are still inside TTL can be fetched. New hosts wait. When the resolver returns, do not stampede it with every worker’s backlog in the same second. The lease and the flat rate already smooth fetches. Lookups need the same courtesy.
- Queue lost, table alive. Rebuild the frontier from next-due. Until you do, nothing is fetched, which is a safe failure. The unsafe failure is a second frontier built while the first one is still being consumed, so every host is fetched twice. Rebuild by pausing workers, or rebuild into a generation the lease records, so old messages are ignored.
- Robots document cached as allow, operator just disallowed a prefix. You may fetch it until the cache refreshes. The 12 hour assumption is the exposure. Shorten it when they complain, and drop queued addresses that match the new rules before you fetch them.
- Infinite link generator. Discovery for one host hits the 5,000 cap and stops, while refresh for the rest of the corpus continues. Symptom if you forgot the cap: the frontier’s age for refresh grows without bound and the new addresses all share one path pattern. The cap is the fix, not a bigger fleet.
- A link that points at your own network. The crawler will be aimed at internal addresses if it follows whatever it finds, or if a seed is wrong. Refuse addresses that resolve to private networks, and run the fetchers where they cannot route to your control plane anyway. That is the server-side request class of bug. Security basics apply because the address was supplied by a page, which means it was supplied by anyone who can edit a page.
- Truncated body stored as the page. Checksum the bytes and reject a short read. Object storage has the same rule for a reason. A partial document indexed as truth is a freshness bug you will not notice from QPS.
In the interview
First five minutes: seeded corpus, not the whole web, a flat rate from the tier math, politeness per host, dedup on a canonical key, budget split between refresh and discovery. The number is about 13 million fetches a day, 151 per second exact, 130 with the shortcut, scheduled at 150. One hundred fifty hosts in flight at one per second each fills it. The bottleneck is not “can we fetch faster.” It is a single host, a trap, or a discovery flood that starves refresh.
Skip a ranking lecture. The index is downstream. Skip a browser-rendering farm unless they force the requirement.
The question that follows is usually “a site with a million pages appears” or “you are hammering one host.” For the million pages, the per-host cap and the 30 percent discovery budget mean it trickles in. For the hammering, the lease and the delay are why a second worker must not fetch. The tradeoff you admit: completeness is slow on purpose, because spending the whole budget on new pages makes the index lie about the pages you already have.
Check yourself
How many fetches per second is a corpus of 80 million pages with 10 percent recrawled daily, 30 percent weekly, and 60 percent every 30 days?
Daily is 8 million, weekly is about 3.43 million, monthly is 1.6 million, about 13 million a day. Divided by 86,400 that is about 151 per second. The 1e5 shortcut gives about 130. You schedule a flat 150. You do not multiply by a peak. A crawl spike is load on someone else’s site, not a user-traffic pattern you have to absorb.
Why does the frontier have to be leased per host instead of letting any worker fetch any due address?
A global rate of 150 per second with a per-host delay of one second means you want 150 different hosts in flight, not 150 fetches to one host. If workers take whatever address is next, many of them will share a popular host and your politeness rule exists only on paper. The lease makes one worker the only fetcher for that host until it expires.
The dedup table is down. Why is failing open and continuing to enqueue a bad default?
You cannot tell a new address from one you fetched an hour ago, so discovery refetches the corpus and ignores per-host budgets you already satisfied. Fail closed on discovery. Refresh only what the table already recorded, and if you cannot read the table, stop. A paused crawler is an internal incident. An unbounded recrawl is an incident for every host you touch.
What do you do when the request for a host's robots rules fails?
You do not treat the failure as permission to fetch. You back off that host and retry the rules later. An absent rules document is different: the operator did not publish one, so you use your default delay and you may fetch. A failed read means you do not know their wishes. Caching a previous success has a TTL, and you should not stretch that TTL just because the latest read failed.
You have 150 fetches per second and a new host publishes a million addresses. Why does freshness say you should not spend the day on them?
Every discovery fetch replaces a refresh. A day at 150 per second is about 13 million fetches, so a million new addresses is a large fraction of the day if you let one host take it. The pages you already index would miss their tier. A per-host discovery cap and a 30 percent discovery share make that site arrive over many days. Completeness is allowed to be slow. A stale index of the corpus you already claim to have is the failure you are avoiding.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Marc Brooker and the AWS Builders' Library; O'Neil and others, LSM trees and Bloom filters; Alex Xu, ByteByteGo volumes.