Design a web crawler: a full worked answer
Fetch and store a few billion pages and keep them reasonably fresh, without overloading any site or fetching the same content twice. Most of the design is the scheduler: a strict per-domain delay, URL and content deduplication, and recrawl frequency that follows how often each page actually changes.
By devskills editorial team · Last updated
The question
Design a crawler that fetches a large portion of the web, stores the pages for later processing, and keeps them reasonably fresh. It must not overload the sites it visits and must not fetch the same content repeatedly.
“Design a web crawler” is a core-level problem in the crawling and ingestion family. The work is unbounded, the sources are hostile or fragile, and you are a guest on someone else's machine.
There is no fixed input size: the queue of work generates more work. So the interesting questions are what you refuse to fetch, how you avoid fetching the same thing twice, and how you avoid hurting the sites you depend on.
Before anything: where is the slack?
Nobody is waiting for any single page. This group has the most slack in the app, and most good decisions here come from spending it.
No human is watching a fetch. If one page takes thirty seconds, or fails and is retried in an hour, no user notices. So everything can be queued, batched, retried patiently and processed out of order: the opposite of a request path.
What has no slack is politeness. A site you are crawling has a request path, and their users are waiting. Hitting one domain a thousand times a second is an accidental denial-of-service attack. It gets you blocked, and possibly sued. So your own generous budget has to be converted into a strict per-domain delay.
Freshness has a range rather than a number, and that range is a design decision. A news homepage is stale in minutes. A 2011 blog post is unlikely to change again. Crawling both on the same schedule wastes most of your capacity re-fetching pages that have not changed.
So: Everything is a queue, nothing is synchronous, and the scheduler is built around per-domain politeness rather than global throughput. Recrawl frequency is adaptive, because a uniform schedule spends most of its budget on pages that never change.
Requirements
about 5 minAssumptions: this feeds a search index, we want a broad crawl of a few billion pages, HTML only for now with media referenced but not fetched, and we obey robots.txt. That last one is a constraint that shapes the design.
The question that changes a box: how fresh does this need to be? A one-off archive crawl is a much simpler system than one that keeps a few billion pages current. The second needs change detection, per-page recrawl scheduling, and a way to decide what is worth revisiting. I will assume continuous recrawling with adaptive frequency, because that is what a search product needs.
Second question: do we need JavaScript rendering? That changes the cost per page by an order of magnitude or more, because a headless browser uses far more CPU and memory than an HTTP fetch. I will assume a hybrid: plain fetch by default, rendering only for pages where the plain fetch returns almost no content, which is a small fraction.
Scope I propose: discovering URLs, scheduling politely, fetching, deduplicating content, storing raw pages, and extracting links to continue. Out of scope: the index itself, ranking, and interpreting the content. That is a separate system that consumes what this one produces.
Stage checklist
- Established the purpose, because it changes what "done" means
- Asked about freshness and tied it to recrawl scheduling
- Asked about JavaScript rendering and named the cost multiplier
- Committed to robots.txt as a design constraint, not an afterthought
- Proposed a scope that ends where the index begins
Actors and lifecycle
about 6 minActors: the seed source that gives you starting URLs; every website you visit (millions of actors, each with its own rules, capacity and tolerance for you); the DNS system, which you will hit very hard; and the crawler itself. The crawler makes constant decisions that nobody sees: is this URL worth fetching, is it the same page as one I already have, how long until I look again, and should I give up on this domain entirely.
The chain: discovered → normalised → deduplicated against what we know → checked against robots → scheduled by domain → fetched → content deduplicated → stored → links extracted, which feeds back to discovered → scheduled for recrawl.
The failure branches are most of this system. At normalised: the same page has five URLs with different tracking parameters and a trailing slash, so without normalisation you crawl it and store it five times. At robots: fetching robots.txt is itself a request, so it is cached per domain with a TTL, or you double your traffic to every site. At fetch: timeouts, 404s, 500s, redirect chains that loop, and pages that are 40 MB of nothing. Each needs a limit and a give-up rule. At content dedup: two different URLs return byte-identical or near-identical content, which is common with mirrors and printer-friendly pages, so you need a content fingerprint as well as a URL check.
The branches the system owns: a site that starts returning errors, where continuing to hammer it is both rude and pointless. A per-domain circuit breaker backs off entirely. And a crawler trap: a calendar page that generates an infinite sequence of links, or a site with a URL pattern that expands forever. Without a per-domain page cap and a depth limit, one such site can consume your crawler indefinitely.
Stage checklist
- URL normalisation before deduplication — the same page has many URLs
- robots.txt cached per domain, since fetching it is itself traffic
- Limits on redirect chains, response size and timeouts
- Content fingerprinting separate from URL deduplication
- A per-domain breaker for a site that starts failing
- Crawler traps named, with a depth limit and per-domain cap
The lifecycle, drawn
Numbers
about 6 minTarget: 4 billion pages, recrawled on average monthly. That is 4 billion fetches per month, divided by 2.6 million seconds, so about 1,500 pages per second sustained. Not extreme, but it has to run continuously for years.
Storage: an HTML page is about 100 KB raw, roughly 25 KB compressed. 4 billion pages compressed is about 100 TB for one copy of the web. That goes to object storage, not a database. At list prices that is roughly a few hundred dollars a month in an infrequent-access archive tier and about two thousand in standard storage. Worth saying, because candidates often assume storage is the expensive part.
The number that shapes the design: the seen-URL set. 4 billion URLs at 100 bytes each is 400 GB if stored as strings. That is too big to hold comfortably in memory on one machine, and link extraction means checking far more URLs than you fetch (perhaps 50,000 per second), which is a lot of random lookups for a disk-backed database. A bloom filter of 4 billion entries at a 1% error rate is about 5 GB, which fits in memory comfortably. The cost is that about 1% of new URLs are wrongly reported as already seen and never crawled, which is acceptable for a broad crawl.
DNS: 1,500 fetches a second across many domains means a lot of lookups, and resolution becomes a bottleneck if uncached. Aggressive DNS caching is a specific, named component here rather than an implementation detail.
So the hard part here is the seen-set at 4 billion entries and per-domain politeness, not fetch throughput. One is a membership problem and the other a scheduling problem; neither is about bandwidth.
Stage checklist
- Turned a target into a sustained pages-per-second number
- Estimated compressed storage and put it in object storage, not a database
- Calculated the seen-set size and showed why a plain set does not fit
- Chose a bloom filter and named the false-positive consequence
- Named DNS as a real bottleneck at this rate
- Finished the sentence: the seen-set and politeness, not throughput
The numbers, drawn
So the hard part is membership at 4 billion entries, plus per-domain politeness. Storage is 100 TB compressed in object storage, which costs less than candidates tend to expect and is not the constraint.
High-level design
about 12 minThe frontier is the core of the system, and it is not one queue. It is a set of per-domain queues, plus a scheduler that only releases a URL from a domain when that domain's politeness delay has elapsed. The unit of scheduling is the domain, not the URL. Workers ask the frontier for work and are handed URLs from domains that are ready, so no worker is ever waiting on a delay.
Partitioning by domain follows from that. All URLs for one domain are handled by one frontier partition, so the politeness state (last fetch time, current delay, breaker status) lives in one place with no coordination. This is the same "partition by the thing that needs ordering" move as chat, applied to rate rather than sequence.
The seen-set service holds the bloom filter, sharded by URL hash, and answers "have we seen this" for the tens of thousands of extracted links per second. New URLs are added and passed to the frontier. It is fronted by an exact store for the recently added, so the filter can be rebuilt periodically without losing the last hour.
Fetchers are stateless and numerous. Each has a timeout, a response size cap, a redirect limit, and a per-domain breaker. They resolve DNS through a heavily cached resolver, fetch, and hand the raw response on. They never decide what to fetch next; the frontier does.
Content processing computes a fingerprint of the normalised text, checks it against a content-seen store, and drops near-duplicates. The raw page goes to object storage keyed by content hash, which means identical content from ten URLs is stored once. Extracted links go back to the seen-set service. Metadata (URL, fetch time, status, content hash, change signal) goes into a database that the recrawl scheduler reads.
The recrawl scheduler is what makes freshness affordable. Each page carries a next-fetch time, adjusted by whether the content changed last time: pages that change get revisited sooner, and pages that do not decay toward a long interval. Most pages fall into the second group, which is why this box earns its place.
Stage checklist
- The frontier is per-domain queues plus a scheduler, not one global queue
- Partitioned by domain, so politeness state needs no coordination
- Seen-set as a sharded bloom filter service with an exact recent layer
- Fetchers stateless, with timeouts, size caps and per-domain breakers
- Raw pages in object storage keyed by content hash, so duplicates store once
- Adaptive recrawl scheduling driven by observed change
The architecture, drawn
Deep dive and tradeoffs
about 14 minHard part one: politeness against throughput. These are in direct conflict. My fleet can fetch 1,500 pages a second, but a single site might tolerate one request every two seconds. So a domain with 500 million pages would take 30 years at that rate. For large sites I need a middle position: honour crawl-delay where robots.txt specifies one, and otherwise adapt. Start conservative, watch response times and error rates, and speed up only while the site is answering quickly. If latency rises or errors appear, back off immediately. That is a control loop, not a constant. Cost: complexity in the scheduler, and I will never fully crawl the largest sites. So coverage is a decision, and I would prioritise by page importance rather than pretending completeness is possible.
Hard part two: what to recrawl. I cannot refetch 4 billion pages daily, so priority has to be computed. Signals: how often this page changed in the past, how important it is by inbound links, and how important its site is. A news homepage that changed every one of the last ten fetches goes on a minutes-to-hours cycle. A page unchanged for two years decays to quarterly. Cheap change detection helps a lot. A conditional request (If-Modified-Since or If-None-Match with the stored ETag) gets a small 304 "not modified" response instead of the page from servers that support it, so many recrawls cost almost nothing in bandwidth. Cost: per-URL state for billions of URLs, which needs a proper database, and a scoring model that can be wrong. It will miss a page that suddenly starts changing, so I would keep a floor on recrawl frequency rather than letting anything decay to never.
Traps and hostile sites. A calendar with infinite next-month links generates URLs forever. Defences: a maximum crawl depth, a per-domain page budget, and detection of URL patterns that keep producing near-identical content. Without these, one site can fill the frontier without any error being raised. Cost: legitimate deep sites get truncated, so the budget needs to scale with site importance rather than being fixed.
Operating it. This runs for years, so the metrics that matter are pages per second by status code, frontier depth per partition, seen-set false-positive rate, and the ratio of not-modified to full fetches. That last one tells me whether my recrawl scheduling is working. Cost: small, and skipping it means never knowing that a scheduling change made things worse.
Stage checklist
- Named politeness against throughput as a direct conflict, with a control loop as the answer
- Accepted that the largest sites will never be fully crawled, and prioritised instead
- Adaptive recrawl driven by observed change, with a floor so nothing decays to never
- Conditional requests so unchanged pages cost almost no bandwidth
- Depth limits and per-domain budgets for crawler traps
- Named the metric that tells you whether recrawl scheduling is working
And then they push back
Your per-domain page cap stops crawler traps. It also stops a retailer with tens of millions of real product pages. How do you tell them apart?
"Raise the cap for big sites." That needs a list of big sites, and it fails on the first big site with a trap inside it. A popular forum with a broken calendar plugin is both.
"A fixed cap asks the wrong question, so I would replace it with a budget each domain earns. Pages on a real site tend to get links from other domains, and they produce new content when fetched. Pages in a trap get few outside links, and they tend to come back as near-duplicates from the content-seen store, or sit on one URL pattern with a parameter that keeps counting up. So the budget grows with outside links and with the share of fetches that produced new content, and it shrinks when that yield falls. I would apply the throttle per URL pattern within the domain, so the calendar path stops while the product pages carry on. All of this state fits in the frontier partition that already owns the domain. Cost: more per-domain state, thresholds that need tuning, and some real pages in low-yield sections that never get crawled. I would log everything the budget rejected and sample it, so that loss is visible."
Could you build this with half the components? Which would you cut?
"Every component is necessary." Rarely true, and it signals that you added things by pattern rather than by requirement.
"Yes, and I would cut in this order. The queue on the write path goes first — at my write rate a synchronous call is simpler and gives the user a real answer. The separate search index goes next, because the built-in full-text search handles this data size and one system beats two. The in-process cache layer goes, keeping just the shared cache, because the extra hit rate is not worth servers disagreeing with each other. What I would not cut: the shared cache, because the database cannot take the read load, and the idempotency keys, because at-least-once delivery is not optional. If I were shipping this in a week, I would build the database, the cache and the stateless services, and add the rest when a measurement told me to. Most of what I drew is a response to scale I have estimated but not yet reached."
Now it must support scheduled actions — do this thing at 8am next Tuesday.
"We would use a cron job." Cron per user does not scale, does not survive a machine dying, and has no answer for what happens when a scheduled time is missed.
"I would store scheduled items in a table indexed by due time, and have workers poll for items due now. That gives durability, survives restarts, and lets me see and cancel what is pending, none of which cron gives me. The interesting parts are the failure branches. If the system is down at 8am, the item is late rather than lost, and I need a policy: run it late, or skip it, and that differs per action — a reminder is worth sending late, a market order is not. Duplicate execution must be harmless, so each scheduled item carries an id and execution is idempotent. Time zones and daylight saving cause bugs here: '8am next Tuesday' means 8am in someone's local zone, which is a different UTC instant depending on the date, so I store the intent rather than a resolved timestamp. And scheduled times cluster on round hours like 9am, so the due-time index gets hot and I would jitter execution by a small window where the exact second does not matter."
- One key gets 90% of the traffic. What breaks, and what do you do?
- A third-party API you depend on starts taking 30 seconds to respond. What happens?
- Your storage bill doubles every six months. What do you do?
- How do you know when you are about to run out of capacity?
- A worker dies halfway through processing a batch. What is the state of the world?
- You grow 10x every year for three years. What do you rebuild?
The topics this answer used
How companies ask this one
The same design comes up in company rounds with a different emphasis. These are practice framings written for this site, not inside information.
At Google: design a web crawler
Design a system that crawls the web: fetches pages, extracts links, and keeps going. Assume you want to crawl billions of pages and keep them reasonably fresh.
Politeness and deduplication, mostly. Plenty of candidates design a fast fetcher and forget that hammering one site is the fastest way to get blocked, and that the web is full of the same content at different URLs.
Their follow-up: "Two URLs return the same page. How do you avoid storing it twice?"
Two different problems, and they need different tools. Identical content is caught by hashing the normalised body and checking the hash, which is cheap and exact. Near-identical content is the harder and more common case: the same article with a different sidebar, or a page with a rotating advert. An exact hash is useless there because one changed byte gives a completely different hash. So I would use a similarity-preserving hash like SimHash or MinHash, where similar documents produce similar fingerprints and you can cheaply find pairs within a small Hamming distance. Before either of those, normalise the URL: lowercase the host, strip the default port and fragment, drop known tracking parameters, and follow redirects to the final URL. A large share of duplication is the same page reachable at cosmetically different addresses.