Design a Web Crawler — System Design Interview Walkthrough
A web crawler looks like a networking problem and is really a scheduling problem. Fetching a page is a few milliseconds of work any HTTP client does for free; deciding which of the eleven billion URLs you have discovered to fetch next — without hammering one unlucky server, without fetching the same article a fourth time under a different query string, and without disappearing down an infinite calendar — is where the design lives. A candidate who opens with "a thread pool of fetchers behind a queue" has described the easy five percent.
This walkthrough takes the question as it is usually asked: build a crawler that feeds a search index. We will do the arithmetic that fixes the shape of the system, design the frontier that politeness forces on you, handle the two separate deduplication problems, defend against the traps the open web sets, and then be honest about what a crawler does not solve.
Scope it in the first two minutes
State the functional requirements narrowly, because "crawl the web" is unbounded:
- Start from a seed list, fetch HTML, extract links, repeat.
- Store each page's bytes plus metadata for a downstream indexer.
- Obey
robots.txtand stay polite to every origin. - Re-crawl pages at a rate related to how often they change.
- Survive crashes without losing or re-fetching the frontier.
Out of scope, said out loud so the interviewer knows you know: the inverted index, ranking, rendering JavaScript (we come back to it), anything behind a login, and media assets. A crawler decides what to fetch and when, and nothing about relevance. The targets that matter: 1 billion pages per month, and polite enough that no site operator ever has to email you.
The arithmetic that fixes the design
Estimate before you draw anything — here the numbers genuinely dictate the architecture rather than decorating it.
Throughput. 30 days is 2.59 million seconds, so a billion pages is 386 pages per second sustained, with no slack for retries. Call it 450 for headroom.
Bandwidth. HTML only, gzipped over the wire, is around 30 KB per page. 386 × 30 KB ≈ 11.6 MB/s ≈ 93 Mbps. That is one network interface. Bandwidth is not the problem.
Storage. Keep the compressed bytes: 1e9 × 30 KB = 30 TB per month, against roughly 100 TB uncompressed. Three months of history for change detection is 90 TB in a blob store — cheap and unremarkable.
Discovered URLs. At roughly 60 links per page, a billion pages yield 60 billion link instances. Most are repeats — every page of a site links to the same navigation — so expect on the order of 11 billion distinct URLs. That number, not the page count, sizes your dedupe layer.
Concurrency. This is the one that surprises people. If average fetch latency is 500 ms, Little's law says 386 pages/s needs 386 × 0.5 = 193 concurrent connections. Two hundred sockets. A single machine with async I/O does that comfortably. So why is this a distributed system at all?
Because of politeness. Hitting one host more than about once per second is unacceptable, so each host contributes at most 1 page/s. To sustain 386 pages/s you need at least 386 distinct hosts with work ready at every instant — and since pages per host are brutally skewed, keeping 400 ready means holding tens of thousands of hosts in the frontier. The binding constraint is host diversity, not CPU, bandwidth or sockets.
That reframing is the most valuable thing to say in this interview, and it explains the shape of the system: a modest fetching tier, and a frontier doing all the hard thinking.
The crawl loop
The frontier is the design
A single FIFO queue fails immediately: links arrive in bursts from one site, so a FIFO hands the fetchers five hundred URLs for one host and nothing else. You need two properties that pull in opposite directions — politeness, per-host and about when, and prioritisation, global and about which. The Mercator design (the frontier inside Heritrix) gets both by splitting them into two stages.
The whole thing is about thirty lines:
import heapq, time
from collections import deque
class Frontier:
"""One back queue per host; a heap orders hosts by when they may be hit."""
def __init__(self, default_delay: float = 1.0):
self.queues: dict[str, deque[str]] = {}
self.ready: list[tuple[float, str]] = [] # (next_allowed_at, host)
self.default_delay = default_delay
def add(self, url: str) -> None:
host = host_of(url)
q = self.queues.get(host)
if q is None: # first URL for this host
q = self.queues[host] = deque()
heapq.heappush(self.ready, (time.monotonic(), host))
q.append(url)
def lease(self) -> tuple[str, str] | None:
if not self.ready or self.ready[0][0] > time.monotonic():
return None # nothing is due yet
_, host = heapq.heappop(self.ready) # host is now checked out
return self.queues[host].popleft(), host
def release(self, host: str, delay: float | None = None) -> None:
if not self.queues[host]:
del self.queues[host] # host exhausted, drop it
return
at = time.monotonic() + (delay or self.default_delay)
heapq.heappush(self.ready, (at, host))
Three details carry the weight. The host is absent from the heap while a fetch is in flight, so no second thread can select it — mutual exclusion falls out of the data structure instead of a lock table. release takes a delay, which is where a Crawl-delay directive, an observed slow response, or a 429 backoff gets applied per host. And lease returning None is normal: a crawler with insufficient host diversity idles, and that idle time is the measurement that tells you the frontier is too narrow, not that the fetchers are too few.
What the sketch omits is durability: 11 billion URLs do not fit in memory and must survive a restart, so the real version keeps back queues on disk or in a log. "An in-memory heap over disk-backed per-host queues, checkpointed" is the right level of detail for an interview.
Deciding what to fetch next
With 11 billion candidate URLs and a budget of 1 billion fetches, your frontier grows faster than you can drain it, permanently. Prioritisation is not an optimisation; it is the only thing standing between you and a crawl that is 90% junk. Useful signals, roughly in order of value per unit of effort:
| Signal | Why it works | Cost |
|---|---|---|
| Host-level reputation (inlinks from distinct domains) | Spam farms have many internal links, few external domains pointing in | Cheap, batch-computed |
| URL depth / path length | Depth 1–2 pages are usually the real content; depth 9 is usually a faceted-search explosion | Free |
| Observed change rate | A page that changed on the last three visits will change again | Needs crawl history |
Sitemap priority and lastmod | Site owner telling you directly, often accurately | Free, one extra fetch |
Compute the link-graph scores offline in weekly batches and push them into the frontier as per-host and per-URL numbers. Maintaining a live global ranking inside the crawl loop is a classic over-design: the scores barely move week to week, and the batch version is one map-reduce.
The seen-set problem is bigger than it looks
Before a URL enters the frontier: is it the same URL as one I hold, and have I seen it already?
Normalisation answers the first, and it is unglamorous rule-following: lowercase the scheme and host, strip the default port, resolve . and .., drop the fragment, sort query parameters, and delete known-junk ones (utm_*, sessionid, fbclid). Then compare 8-byte hashes rather than strings. Be conservative: stripping a parameter that actually selects content silently merges two pages into one, and nobody notices until half a site is missing from the index.
The seen check answers the second, and the naive version does not work. 60 billion link instances over a month is 23,000 lookups per second against a table of 11 billion rows. As random point reads against a disk-backed store, that is roughly 23,000 IOPS of pure overhead before you have fetched anything.
Three fixes, in order of how much they buy:
- Shard by host, not by URL. Partition the seen set and the frontier by
hash(eTLD+1)so all of a site's URLs live on one worker. Links are overwhelmingly internal, so a link extracted on worker 7 is almost always answered by worker 7 — no network hop, good cache locality. Map shards to workers with consistent hashing: on a naive modulo map, adding a worker reassigns most hosts and two workers briefly believe they own the same one, which is a real politeness violation rather than mere churn. - Batch and merge. Accumulate URL hashes in memory, then every few minutes sort the batch and merge-join it against a sorted on-disk set. Random reads become one sequential scan. This is how IRLbot crawled 6.3 billion pages in 41 days on a single server — about 1,800 pages/second — and it is the best demonstration that this problem is about I/O patterns, not machine count.
- A Bloom filter in front, with a caveat. At 0.1% false positives a Bloom filter needs 14.4 bits per key, so 11 billion URLs cost 11e9 × 14.4 / 8 ≈ 20 GB — 2.5 GB per shard across eight shards. But be precise about what it saves: it cheaply proves absence, and in a mature crawl most lookups are repeats, so most still reach the real store. A false positive also silently drops a URL forever — 0.1% of 1.4 billion novel URLs is 1.4 million pages a month you never fetch and never hear about. Use it as a pre-filter to skip the disk read for definitely-new URLs; keep the sorted set authoritative.
Content deduplication is a second, different problem
Distinct URLs routinely serve identical or near-identical bytes: http and https, www and bare, print views, mirrors, syndicated articles. Roughly a quarter to a third of the web is a near-duplicate of something else.
Exact duplicates are easy: SHA-256 the normalised text, store one copy keyed by that hash, point both URLs at it, and take the storage saving for free.
Near-duplicates need a similarity-preserving fingerprint, which is what simhash gives you: hash each token, weight it by frequency, sum the weighted vectors bitwise, and take the sign of each component as one bit of a 64-bit fingerprint. Documents differing only by a timestamp and a sidebar land within a Hamming distance of 3. The non-obvious part is retrieval — you cannot index Hamming distance directly, so the standard trick (Manku et al., 2007, from Google's crawl) is to keep the fingerprints in ~20 permuted sorted tables and probe each by its high-order prefix, turning "anything within 3 bits" into twenty cheap range scans.
Store both near-duplicates and let the indexer pick a canonical. You cannot un-discard, and which of two copies is canonical is a ranking judgement the crawler has no business making.
Politeness, robots.txt, and not getting banned
robots.txt was finally standardised as RFC 9309 in 2022, and the details are where interviews probe:
- Fetch
/robots.txtbefore anything else on a host and cache it for 24 hours. Without the cache you have doubled your request count against every small site. - A 4xx on
robots.txtmeans no restrictions. A 5xx means treat the whole host as disallowed until it recovers — a failing server is not an invitation. Crawl-delayis not in the RFC and Google ignores it; Bing and others honour it. Honour it.- Back off exponentially on
429and503withRetry-After, per host, and keep a per-host error budget: ten consecutive failures should park a host for hours, not spin. - Identify yourself in the
User-Agentwith a URL explaining the crawler and how to block it. That converts angry emails into arobots.txtedit.
One number makes the ceiling concrete. A site with 50 million pages at 1 request per second takes 50 million seconds — 578 days. You cannot crawl a large site exhaustively on a polite budget; the real answers are per-host page budgets, sitemaps instead of link discovery, and for the few sites that matter, asking the operator for a higher rate or a bulk feed.
Politeness is also arguably per-IP, not per-host: thousands of small sites share one shared-hosting address, so one request per second to each of a hundred of them is a hundred requests per second to one machine. Rate-limiting on the resolved IP as well as the host is the thorough answer, and the mechanics are those of any distributed rate limiter — the only twist is that the key is a host you discovered a second ago.
The web is adversarial
Not always maliciously, but the effect is the same: unbounded URL spaces that will absorb your entire crawl budget.
| Trap | Defence |
|---|---|
Infinite calendar: a ?month= link for every month to 2187 | Max path depth, parameter-value caps, per-host budget |
| Session ids: the same page behind a new id on every link | Normalisation strips known session parameters |
| Faceted search: every colour by size by sort combination | Cap distinct query parameters at two or three; honour the canonical link |
Soft 404s: 200 OK with a "not found" body | Fingerprint the error page per host, then treat matches as 404 |
| Decompression bombs: 2 KB of gzip, 10 GB of output | Cap decompressed size and the compression ratio |
The one defence that covers traps you have not thought of is a budget per host: a fixed number of fetches and accepted new URLs per host per cycle, scaled by that host's reputation. A trap then costs one host's budget instead of your crawl. Saying that is worth more than enumerating trap types, because it is a general mechanism rather than a list.
Freshness
Re-crawling is a budget split, not a separate system: 386 pages/s buys discovery and freshness together, so you are choosing a ratio. 60/40 is a defensible starting answer, implemented as the P1-versus-P2 weighting in the front queues. Change rates then vary by four orders of magnitude, so a single interval is indefensible:
| Page type | Re-crawl interval | Why |
|---|---|---|
| News homepage | 2–5 minutes | Content turns over faster than that |
| Active forum thread | Hourly | New replies, stable URL |
| Product page | Daily to weekly | Price and stock |
| Documentation | Monthly | Changes on release |
Estimate each page's rate from its own history: model updates as a Poisson process, multiply the interval when a re-crawl finds nothing changed, divide it when something did. Use If-Modified-Since and ETag so an unchanged page costs a 304 and a few hundred bytes instead of 30 KB — on a re-crawl-heavy workload that alone cuts bandwidth by more than half. And note the limit: you only learn a page changed by fetching it, so freshness is an estimate, never a guarantee.
What a crawler does not solve
It does not give you search. The crawler produces documents. Index construction, ranking, snippets and query serving are separate systems, each at least as large.
It does not read JavaScript cheaply. A plain fetch is ~10 ms of work; a headless render is 1–2 seconds and 300–500 MB of RAM. At 386 pages/s and 1.5 s per render, Little's law demands 386 × 1.5 ≈ 580 concurrent browsers — roughly 230 GB of RAM plus a large CPU bill, two orders of magnitude more expensive than fetching. So go two-tier: fetch everything cheaply, detect the pages whose content is genuinely JS-dependent, and send only those to a small render pool with its own budget.
It does not reach the deep web. Anything behind authentication, a paywall or a form submission is invisible — which is most of the data in the world.
It does not beat sites that do not want it. If a site blocks you, the options are to respect that or negotiate access. Evasion buys an arms race you lose plus legal exposure, and interviewers notice which instinct you reach for.
It does not deliver exactly-once anything. Retries, redirects and re-crawls all produce duplicate deliveries downstream. The indexer has to be idempotent, keyed on URL hash plus content hash, so the same document arriving twice is a no-op.
Alternatives worth naming
Volunteering these is a strong signal, provided you can say when each is the right call.
Common Crawl. A few billion pages per monthly snapshot, WARC format, free on S3, going back to 2008. For a corpus rather than a live index, building a crawler to get one is a wasted quarter; the limits are freshness and coverage you do not control.
Existing crawlers. Scrapy for one site or a hundred; StormCrawler or Apache Nutch for a distributed crawl you do not want to write; Heritrix for archiving. All three already implement the frontier and politeness logic that is most of this post, better tested than your first version.
Ask instead of crawling. Sitemaps, feeds, public APIs and bulk dumps are cheaper, fresher, more accurate and welcomed. With a cooperative publisher a feed beats a crawl on every axis.
A focused crawler. If you want one topic, classify before you fetch and let the classifier drive priority — the useful part of the web for 1% of the budget.
For a real product: Common Crawl for breadth, feeds and APIs where publishers offer them, and a small purpose-built crawler for the few hundred sites that matter. Build the billion-page general crawler only when crawling is the product.
Running this in the interview
The ordering that lands best, each step motivating the next:
- Scope it. Fetch and store for an indexer, not rank. One billion pages a month.
- Do the arithmetic, then draw the conclusion from it. 386 pages/s, 93 Mbps, ~200 sockets — then the quiet part: bandwidth and CPU are not the constraint, host diversity is.
- Draw the cycle. Frontier, fetcher, parser, seen-check, back to the frontier — and note that the frontier is the only stateful component.
- Design the frontier properly. Front queues for priority, one back queue per host, a heap of next-allowed times. This is the part interviewers are waiting for.
- Split the two dedupe problems. URL normalisation and the seen set, then content fingerprints. Conflating them loses the thread.
- Volunteer politeness and traps unprompted, with the general defence — per-host budgets — rather than a list.
- Name one limit and one alternative. "This gets us documents, not search," and "for a corpus I would start with Common Crawl."
The follow-ups come in roughly this order: how do you dedupe URLs across 50 machines without a chatty broadcast; what happens when a worker dies holding a shard of the frontier; how do you tell that a 200 is really a soft 404; how do you stop one spam domain eating your budget; what do you re-crawl today; and how would you crawl a site that renders everything client-side. Each has an answer above, and they cluster around the frontier — so if you rehearse one part out loud, rehearse that.
If you want to hear how this sounds under time pressure, you can run the whole question as a voice mock interview on Whitepad and get scored on the parts you skipped.
Practice this out loud
Reading is the easy part. Sit across from a senior AI interviewer that talks, watches your whiteboard, and scores you like the real thing — your first mock is free.
Start a free mock →