Design a Web Crawler
A web crawler downloads billions of pages by following links, without hammering any one site, without crawling the same page twice, and without getting stuck in infinite loops of generated pages. This lesson designs one for a search engine, with the URL frontier, politeness, deduplication and recrawl scheduling that interviewers want to hear about.
What you will learn
- The crawl is a loop: take a URL, fetch, parse, store, add new URLs to the frontier.
- The frontier has two layers: priority queues for what matters, per-host queues for politeness.
- One host is only ever fetched by one worker, with a delay between requests and robots rules respected.
- Deduplicate URLs with normalisation and a seen set, and content with fingerprints.
- Detect traps with depth limits, URL length limits and per-host page budgets.
- Recrawl pages at rates based on how often they change and how important they are.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The crawl loop
- Step 4: The URL frontier
- Step 5: Politeness and robots rules
- Step 6: Fetching and DNS
- Step 7: Parsing and storing pages
- Step 8: Deduplicating URLs and content
- Step 9: Crawler traps
- Step 10: Recrawling and freshness
- Step 11: Scaling out
- Step 12: The follow-up questions
- Recap
Short on time? Read the answer outline for design a Web Crawler.
Practice this question with MaxThe question
Welcome to lesson ten of the InterviewDryRun system design course. Today we design a web crawler: the program that starts from a few web pages, follows their links to more pages, and keeps going until it has downloaded a large part of the web, so that a search engine can index it.
The basic idea fits on a napkin: take a page, find its links, visit them. A first-year student can write that in an afternoon. What makes it a system design question is everything that goes wrong at scale. Billions of pages. Websites that would be knocked over if we sent them a thousand requests a second. The same page reachable through a hundred different URLs. Sites that generate infinite pages, like a calendar with a next month link that never ends. And pages that change, so the crawl is never finished.
Max asks
“Design a crawler that fetches and indexes billions of pages politely and without loops.”
That is how Max, our AI interviewer, asks it. Notice the two words the interviewer has given you as hints: politely, and without loops. Politeness means we must never overload a website. Without loops means deduplication and trap detection. Those two topics, plus the URL frontier that ties them together, are where you should spend most of your time.
The plan: requirements and numbers, then the crawl loop as a high-level design. Then deep dives on the URL frontier, politeness, fetching and DNS, parsing, deduplication of URLs and of content, crawler traps, recrawling, and scaling across many machines. Then the follow-up questions.
Step 1: Clarify the requirements
- 01Start from seed URLsThen follow links found on each page
- 02Download and store pagesHTML first; images and documents out of scope
- 03Extract linksFeed new URLs back into the crawl
- 04Hand pages to the indexerIndexing itself is another system
- 05RecrawlRevisit pages to catch changes
Start with questions, and narrow the scope, because a crawler can serve many purposes: a search engine, an archive, price monitoring, or training data. Ask which one. We will assume a general search engine.
We start from a list of seed URLs, popular sites in many languages and categories. We download each page, extract its links, and add those links to the list of pages to visit. Ask about content types. Say you will crawl HTML pages, and treat images, videos and documents as out of scope, or as a later extension.
The crawler stores what it downloads and hands it to the indexer, which builds the search index. Indexing is a separate system; ask the interviewer to confirm. And the crawl is continuous: pages change, so we must come back to them. How often will be a key design question later.
- 01ScaleBillions of pages, refreshed regularly
- 02PoliteNever overload a site; obey its robots rules
- 03RobustSurvive broken HTML, slow servers, traps
- 04EfficientDo not fetch or store the same thing twice
- 05PrioritisedImportant pages first and more often
Now the qualities, which are really the interesting requirements here. Scale: billions of pages. And politeness: we must never send so many requests to a website that we slow it down for its real users, and we must obey the site's robots file, which says which parts of the site crawlers may visit.
Robustness: the web is full of broken HTML, servers that hang, servers that return infinite data, and malicious pages designed to trap crawlers. The crawler must survive all of them without human help.
Efficiency: do not download the same page twice, and do not store the same content twice. And priority: the web is too big to crawl completely and keep fresh, so we must decide what matters most. A news site's front page matters more than page nine thousand of an old forum.
Step 2: Back-of-the-envelope estimates
Let us size it.
Say we want to crawl five billion pages a month. A month is about two and a half million seconds, so that is about two thousand pages a second on average. Plan for peaks of around five thousand.
The average page, with its HTML, is around a hundred kilobytes. Two thousand pages a second times a hundred kilobytes is two hundred megabytes a second of inbound traffic, over one and a half gigabits a second. That is a lot for one machine, but trivial for a fleet.
Storage: five billion pages times a hundred kilobytes is around five hundred terabytes a month, before compression. HTML compresses well, often by five times, and deduplication removes more. Still, we are clearly in distributed object storage territory, and we will keep only the latest few versions of each page.
And the frontier: the set of URLs we know about but have not yet fetched is much larger than what we fetch, tens of billions, because every page links to many others. That means the list of URLs to crawl cannot live in memory on one machine. Keep that in mind; it shapes the frontier design.
One more useful number: how long does a fetch take? Often a second or more, because we are waiting on servers all over the world. So to reach two thousand fetches a second, we need thousands of fetches in flight at once. That tells us fetching must be massively concurrent and asynchronous, not one thread waiting per request.
Step 3: The crawl loop
The high-level design is a loop, and it helps to draw it as one. It starts with seed URLs going into the URL frontier, which is the data structure that decides what to crawl next.
Fetchers take URLs from the frontier, resolve the host name, download the page, and handle redirects, timeouts and errors.
The raw page goes into the page store, which is object storage, along with metadata: the URL, when it was fetched, the response code and headers.
Parsers read stored pages, extract the text for the indexer, compute a fingerprint of the content, and pull out every link, turning relative links into full URLs.
And every extracted link goes through deduplication: have we seen this URL before? Only new URLs go into the frontier, and the loop continues. Separating fetching from parsing, with storage in between, is deliberate: fetchers are limited by the network and waiting, parsers by CPU, so we scale them separately.
Now, everything interesting happens inside the boxes. The frontier is where politeness and priority live. Deduplication is where loops are prevented. Let us go through them one at a time.
It also helps to say what is not in this loop. The crawler does not decide how pages rank in search results, and it does not build the search index. Its contract with the rest of the search engine is simple: here is a stream of fresh pages, with their links and fingerprints. Drawing that boundary clearly keeps the interview focused on the parts the interviewer asked about.
Step 4: The URL frontier
The frontier is the heart of a crawler, and this is the diagram that interviewers want to see. A naive frontier is one big queue: first in, first out. That fails on both of our key requirements. It has no notion of importance, and since pages link mostly to their own site, a plain queue fills up with thousands of URLs from the same host in a row, which we would then fetch back to back. That is the opposite of polite.
So the frontier has two layers. The front layer handles priority. Each new URL gets a score, based on things like how important its site is, how many pages link to it, and how often it changes. Then it is placed into one of several priority queues.
The back layer handles politeness. URLs are taken from the priority queues, favouring the high-priority ones, and routed into per-host queues, one queue for each website. Each host queue has a next allowed time: the earliest moment we may fetch from that host again.
A fetcher asks for work by taking the host whose next allowed time is earliest and has passed, fetches one URL from that host's queue, and sets its next allowed time a few seconds into the future. So we fetch from many different hosts in parallel, but each individual host gets at most one request every few seconds. Politeness falls out of the data structure, rather than being something each fetcher has to remember.
Since the frontier holds tens of billions of URLs, it cannot live entirely in memory. Keep the heads of the queues in memory and the tails on disk, in a log-structured store, loading more as the in-memory part drains. And split the frontier across many machines by host, which we will discuss when we scale out.
Step 5: Politeness and robots rules
- 01Robots fileFetch it per host, cache it for a day, obey it
- 02One connection per hostNever fetch one site in parallel
- 03Adaptive delayWait several times the last response time
- 04Back off on errorsSlow down on 429 and 503
- 05Identify yourselfA clear user agent with a contact page
Let us be concrete about politeness. Before crawling any host, fetch its robots file, which lists which paths crawlers may and may not visit and sometimes a requested delay. Cache it per host for about a day, and check every URL against it before fetching. Ignoring it is both rude and a fast way to get blocked.
Fetch each host from only one connection at a time, and wait between requests. A good rule is to wait several times as long as the last response took. If a site responds in a hundred milliseconds, we might come back in a second. If it takes three seconds, it is probably struggling, so we wait much longer. The delay adapts to the site's health automatically.
Back off further when a site says it is overloaded, with status codes like four-twenty-nine or five-oh-three, and if it keeps failing, pause that host for hours.
And identify ourselves with a clear user agent and a web page explaining who we are and how to contact us. Site owners who have a problem can then reach us rather than blocking us. Politeness is not just ethics; a crawler that is blocked by large parts of the web is a useless crawler.
What about very large sites, with millions of pages and powerful servers? One request every few seconds would take years to crawl them. So large hosts can be given higher rate limits, based on how fast they respond and on any limits their owners have set. Politeness is a per-host budget, not one fixed number.
Step 6: Fetching and DNS
- 01AsynchronousThousands of requests in flight per machine
- 02DNS cacheResolve each host once, not on every page
- 03Hard limitsTimeouts, maximum page size, redirect limits
- 04Conditional requestsOnly download if changed since last time
Fetchers spend almost all their time waiting on the network, so they must be asynchronous: one machine keeps thousands of requests in flight at once with an event loop, instead of one thread blocked per request.
A detail that interviewers like: DNS. Looking up a host name can take tens or hundreds of milliseconds, and public resolvers would not appreciate thousands of lookups a second from us. Since the same hosts are fetched again and again, run our own caching DNS resolvers, and cache results per host. It removes a surprisingly large share of fetch latency.
Set hard limits on everything, because the web is hostile. A connection timeout, a total download timeout, a maximum page size, say a few megabytes, after which we stop reading, and a maximum number of redirects, to escape redirect loops. A crawler without these limits will eventually be stuck on one server that sends data one byte a second forever.
And when recrawling, send conditional requests: ask the server to send the page only if it changed since our last fetch, using the last modified time or the entity tag we stored. Unchanged pages come back as a tiny not modified response, which saves bandwidth for both us and the site.
Fetchers also need to handle secure connections efficiently. Setting up an encrypted connection costs several round trips, so keep connections to a host open and reuse them for the next fetch from that host, as long as the politeness delay is short. And record every failure type per host: timeouts, refused connections, certificate errors. A host that fails repeatedly is probably gone, and should be retried with longer and longer gaps rather than every few seconds.
Step 7: Parsing and storing pages
| Field | Why |
|---|---|
| normalised URL, host | key and partition |
| fetch time, status, headers | recrawl decisions, conditional requests |
| content fingerprint | duplicate and change detection |
| compressed body | for the indexer; latest few versions |
| outgoing links | link graph for importance |
Parsing deserves its own step, because it is where pages become data. Parsers read raw pages from the store, and their first job is simply to survive. HTML on the web is frequently broken: unclosed tags, wrong character encodings, gigantic inline scripts. Use a forgiving parser, detect the encoding properly, and set a time limit per page, so one pathological document cannot stall a parser for minutes.
For each fetch we store a record: the normalised URL and host, the fetch time, the status code and headers, and the content fingerprint. The headers matter later: the last modified time and entity tag let us make conditional requests on the next visit, and the fingerprint tells us whether the page changed.
The body is compressed and kept in object storage, the latest few versions only. And the outgoing links are stored too, not just used. Together, they form the link graph of the web, which the prioritiser uses to estimate how important each page is. The crawler is not only feeding the index; it is feeding its own future decisions.
Parsers also extract things that guide the crawl itself: the canonical link tag, where a page declares its preferred URL, which helps deduplication; no-follow and no-index instructions, which we must respect; and alternate language versions. Paying attention to these small signals makes the crawler noticeably more efficient and more polite.
Step 8: Deduplicating URLs and content
HTTP://Example.com:80/a/./b/../c?utm_source=x&id=7#top lower-case scheme and host → http://example.com drop default port → :80 removed resolve dots in the path → /a/c drop fragment → #top removed drop tracking parameters → utm_source removed sort the remaining query → ?id=7 = http://example.com/a/c?id=7
Now loops and duplicates. The same page is reachable through many URLs, so before checking whether we have seen a URL, normalise it. Lower-case the scheme and host, remove default ports, resolve dots in the path, drop the fragment after the hash sign, which never changes what the server returns, remove known tracking parameters, and sort the remaining query parameters.
- 01URL seen?Hash of the normalised URL in a huge set
- 02Bloom filter in frontFast 'definitely new' answers in memory
- 03Content seen?Fingerprint of the page text
- 04Near duplicatesSimilarity hashes catch pages that differ by a date or an ad
Then check the normalised URL against the set of every URL we have ever seen. With tens of billions of URLs, store eight-byte hashes rather than full URLs, partitioned across machines in a key-value store.
To avoid a lookup over the network for every one of the hundreds of links on every page, put a Bloom filter in front. It is a compact bit array that can say this URL is definitely new, or probably seen. Most links on a page point to pages we have already seen, and the filter answers those in memory. Its small rate of false positives means we occasionally skip a new URL, which is an acceptable price.
URLs are only half the problem. Different URLs often serve identical content: mirrors, printer-friendly versions, the same article under two categories. So after fetching, compute a fingerprint of the page's main text and check it against the content we already have. If it is identical, store a pointer instead of a second copy, and do not extract its links again.
Exact fingerprints miss pages that are almost the same, like the same article with a different timestamp or ad. For those, use a similarity hash, a technique where similar documents produce fingerprints that differ in only a few bits. Comparing those catches near duplicates. Mention it by its purpose; the interviewer is unlikely to want the maths.
Step 9: Crawler traps
- 01CalendarsNext month, forever: cap depth per site
- 02Session ids in URLsEvery visit a new URL: strip known patterns
- 03Repeating paths/a/b/a/b/a/b: detect repeated segments
- 04Huge URLsReject URLs above about 2,000 characters
- 05Per-host budgetPages per host per crawl, by importance
The other half of without loops is traps: sites that generate infinitely many distinct URLs, so deduplication never helps, because every URL really is new. The classic is a calendar with a next month link: it goes on forever, each page unique and worthless.
Others include session ids embedded in every link, so each visit creates a new set of URLs, and broken relative links that keep appending the same path segments, creating ever longer URLs. Some traps are accidents, some are deliberate.
No single rule catches all of them, so layer simple defences. Reject very long URLs. Detect repeating path segments. Strip known session parameters. Limit how deep we follow links within one site from its entry points. And most importantly, give every host a budget: a maximum number of pages per crawl cycle, scaled by how important the site is. A trap can then waste only that site's budget, not the whole crawler's capacity. Say that the budget is the safety net that makes every other heuristic less critical.
Step 10: Recrawling and freshness
| Page | Changes | Recrawl |
|---|---|---|
| News front page | every few minutes | every few minutes |
| Popular article | rarely after day one | daily, then weekly |
| Product page | price changes weekly | every few days |
| Old forum thread | almost never | every few months |
A crawl is never finished. Pages change, and a search engine with week-old news is useless. But we cannot refetch five billion pages every hour. So each page gets its own recrawl schedule.
Estimate how often each page changes from its history: each time we refetch it, note whether the content fingerprint changed. Pages that change on every visit get visited more often; pages that never change get visited less, with the interval doubling each time we find no change. Combine that with importance: a popular page that changes daily deserves daily visits, an obscure page that changes daily maybe weekly.
The recrawl schedule feeds back into the frontier as priority: URLs whose next due time has passed are scored and placed into the priority queues alongside newly discovered URLs. So the same frontier handles both discovery and freshness, and the balance between them is just a matter of tuning the scores. Sitemaps and feeds published by sites also help: they tell us directly which pages changed and when.
Step 11: Scaling out
Finally, how does this run on hundreds of machines? The key choice is to partition everything by host. Hash the host name to pick a crawler node.
Each node owns the frontier queues, robots rules, DNS cache, politeness timers and URL-seen set for its hosts. Because one host lives on exactly one node, politeness needs no coordination between machines: only one node can ever fetch from a given site. That is a beautiful property, and you should point it out.
New URLs found by parsers are sent to the node that owns their host, usually in batches. Pages go to the shared page store. And to recover from a node failure, the frontier and the seen set are checkpointed to durable storage, so a replacement node can pick up its hosts from the last checkpoint, at worst refetching a few pages.
If crawling from several regions, keep the same rule, with each host assigned to one crawler, ideally one close to the host's servers. Crawling a site from nearby is faster and puts less strain on the long-distance network.
Step 12: The follow-up questions
Max asks
“How would you crawl pages that need JavaScript to show their content?”
Render them in a headless browser, which is many times more expensive than a plain fetch. So do it selectively: fetch plain HTML first, detect pages whose content is mostly built by scripts, and send only those to a separate rendering pool, with its own lower throughput and stricter per-host limits. Cache shared scripts, because many pages load the same ones.
Max asks
“A site owner complains that you are crawling them too hard. What do you do?”
Lower that host's rate limit immediately through a per-host override, which our design supports because every host has its own budget and delay. Check whether we violated their robots rules or ignored error signals, and fix the cause. And give owners a self-service way to request a slower crawl rate.
Max asks
“How do you decide which pages are important before you have crawled them?”
From the links pointing at them. A URL linked from many important pages is probably important, which is the idea behind link-based ranking algorithms. Before we have that data, use the site's importance, how close the page is to the site's home page, and signals like sitemaps. The scores improve with every crawl cycle as the link graph fills in.
Max asks
“How would you avoid crawling spam sites that link to each other?”
Spam farms create huge numbers of pages that link to each other to look important. Defences include computing importance with methods that discount links within tightly connected clusters, giving new domains a small budget until they earn trust, and feeding spam classifications from the indexer back into the prioritiser, so sites flagged as spam get a tiny crawl budget.
Max asks
“Your crawler is falling behind: the frontier keeps growing. What do you do?”
First, accept that the frontier will always be larger than what we can fetch; the web is effectively infinite. The real question is whether we are fetching the right things. So check that priorities are working: important pages being refreshed on time, and low-value URLs piling up at the back rather than the front. Then prune the frontier, dropping URLs below a priority threshold or older than some age. Only after that, add fetch capacity. Growing hardware to chase an infinite queue is a losing game.
Recap
- 010 to 5: requirementsSearch engine, HTML, polite, robust, prioritised
- 025 to 10: estimates2,000 pages a second, 500 TB a month, huge frontier
- 0310 to 15: the loopFrontier, fetch, store, parse, dedupe
- 0415 to 35: deep divesTwo-layer frontier, politeness, DNS, dedupe, traps
- 0535 to 45: freshness and scaleRecrawl by change rate; partition by host
On the clock: five minutes of requirements, ending with polite, robust and prioritised. Five minutes of numbers, ending with two thousand pages a second and a frontier too big for memory.
Five minutes drawing the crawl loop: frontier, fetchers, store, parsers, deduplication, and back to the frontier.
Twenty minutes on the deep dives: the frontier with priority queues in front and per-host queues behind, politeness rules, DNS caching and hard limits, URL normalisation and content fingerprints, and trap defences with per-host budgets. Then ten minutes on recrawling by change rate and partitioning everything by host. If you make politeness a property of the data structure, not an afterthought, you will stand out.
The frontier diagram is the moment this interview is won or lost, and it is much harder to explain clearly out loud than it looks on paper. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson eleven.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.