Build a Distributed Crawler for Billions of Pages
System DesignModel answerLast updated
Design a distributed system that discovers, fetches and stores web pages at scale while avoiding repeats, honoring site rules, throttling per host, and surviving failures.
You are asked to design a crawler that keeps finding and downloading web pages without stopping, starting from a small set of known URLs and growing outward through the links it discovers.
The system must:
- Start from seed URLs and scale to a very large number of pages.
- Not fetch the same thing twice, and respect each site's
robots.txtand a per-domain request rate limit. - Favor pages that are important or likely to have changed.
- Persist downloaded content together with its metadata.
- Tolerate machine failures and be able to pick up where it left off.
Out of scope: search ranking and executing heavy client-side JavaScript.
What to cover in your answer:
- Assumptions and a rough capacity estimate.
- The main components and how data moves between them.
- How you schedule URLs (priority and politeness).
- How you detect duplicate URLs and duplicate content.
- How you handle recrawling, failures and hostile or pathological sites.
- Key trade-offs.
Hints
Hint 1
Start with numbers: pages per month, average page size, and what that implies for fetch rate, bandwidth, storage and the size of the set of known URLs.
Hint 2
Partition work by host. If one node owns a host, throttling, robots and DNS caching become local decisions instead of distributed coordination.
Hint 3
Split the URL scheduler into two layers: one that orders URLs by importance, and one that enforces a minimum gap between requests to the same host.
Hint 4
Treat duplicates at two levels (normalized URL, and page body), and plan for traps such as infinite calendars or session-ID URLs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
Functional: seeds in; fetch, extract links, enqueue new URLs; dedupe URLs and content; obey robots.txt and per-host limits; prioritize and recrawl by importance and change rate; store raw content and metadata for downstream consumers. HTML only.
Non-functional: horizontally scalable, fault tolerant, resumable without losing the frontier, polite to sites.
Capacity estimate (state it, then let it drive the design):
| Item | Estimate |
|---|---|
| Volume | ~10B pages/month |
| Fetch rate | ~4k pages/s average, plan ~10k/s peak |
| Page size | ~100 KB raw, ~25 KB compressed |
| Bandwidth | 4k x 100 KB = ~400 MB/s, about 3.2 Gbps sustained |
| Storage | ~250 TB/month compressed |
| Known URLs | ~100B; 8-byte fingerprints is ~800 GB, so it must be sharded |
Fetching is I/O-bound, so use heavily async clients. The frontier and seen-set cannot fit on one machine. In practice politeness, not raw bandwidth, is the binding constraint.
2. Architecture
Seeds -> Frontier (priority + politeness)
-> Fetchers (async HTTP, DNS + robots caches)
-> Blob store + "fetched" queue
-> Parsers -> URL normalize/filter/dedup -> Frontier
-> Content dedup, metadata update, recrawl scheduler
Partition by host hash using consistent hashing. One node owns each host, so rate limiting is a local in-memory decision with no distributed locks, and its robots and DNS caches stay warm. Links pointing to hosts owned by other nodes are routed through a message queue (e.g. Kafka). Parsers are stateless consumers of that queue, scaled separately from fetchers because parsing is CPU-bound.
3. Data model
- URL record (key: URL hash, sharded by host) in a wide-column store such as Cassandra/HBase: status, last and next fetch time, priority, ETag/Last-Modified, content hash, estimated change rate, failure count.
- Host record: parsed robots rules, fetch time of robots, crawl delay, resolved IP, error rate, next allowed fetch time.
- Content: compressed WARC-style files in object storage; URL record keeps
(file, offset, length). - Fingerprints: SHA-256 for exact content match; SimHash for near duplicates.
4. Frontier: priority plus politeness
Use a two-tier design.
- Priority queues. Score each URL from in-link count or PageRank-like signals, domain authority, depth from seed, predicted change rate, and whether it is new. Map the score to one of several buckets and sample buckets with a bias toward high priority, while still serving low buckets so they do not starve.
- Per-host queues. Each queue holds one host's URLs. A min-heap keyed by
next_allowed_timetells a fetcher which host is ready. After fetching, reschedule the host atnow + max(crawl_delay, k x last_response_time). This adapts automatically: slow servers, 429s and 503s increase the delay. - Persistence. Keep queue heads in memory and spill the rest to disk (RocksDB or log segments). Also cap rate per IP, since many virtual hosts share a server.
5. Deduplication
URLs: normalize first (lowercase scheme/host, drop default ports and fragments, sort query params, strip tracking and session params, resolve relative paths). Hash to 64 bits and check on the owning shard: an in-memory Bloom filter first (~10 bits/URL for 1% false positives), then the URL store to confirm "maybe seen" answers when accuracy matters. A false positive only skips a new URL, which is usually acceptable.
Content: exact SHA-256 of the normalized body catches mirrors; 64-bit SimHash with Hamming distance of about 3 or less catches near-duplicates. Duplicates store a pointer to the canonical copy. A host producing many duplicates gets lower priority, which also helps spot traps.
6. robots.txt and DNS
- Cache robots per host (~24 h) and honor
Crawl-delay. Treat 404 as allow-all and 5xx as temporarily disallowed. Check rules before enqueueing so queue slots are not wasted. - DNS is a hidden bottleneck (10 to 200 ms per lookup). Use a local caching async resolver and prefetch for hosts near the front of the queue.
7. Freshness and recrawl
Estimate each URL's change rate by comparing content hashes across fetches (a Poisson model works). Set next_fetch proportional to the expected change interval and weight it by importance: minutes for news front pages, months for static docs. Use conditional GETs (ETag, If-Modified-Since) so unchanged pages return a cheap 304. Sitemaps and RSS provide change hints. A scheduler scans records with next_fetch <= now and feeds them back into the priority queues.
8. Traps and fault tolerance
- Spider traps: cap URL length, path depth and the number of URLs per host; detect repeating path patterns and parameter explosions; demote hosts with high duplicate ratios.
- Failures: the frontier and URL records are durable (replicated store plus write-ahead log), so a crashed node's hosts are reassigned by the hash ring and resume from persisted state. Fetches are idempotent, so an at-least-once queue is fine. Retry with exponential backoff and give up after a failure threshold.
- Backpressure: bounded queues between stages so a slow parser does not exhaust memory.
- Monitoring: pages/s, error rates per host, queue depth, freshness lag, duplicate ratio.
9. Trade-offs
- Bloom filter vs exact set: the filter saves memory but loses a small fraction of new URLs; an exact sharded store costs far more RAM or adds latency.
- Host ownership vs load balance: simple, local politeness, but huge hosts can be hot. Mitigate by splitting very large hosts into sub-shards, each with a shared token budget.
- Breadth vs freshness: recrawling competes with discovering new pages; allocate a quota to each.
- Consistency: the seen-set may be slightly stale; occasional duplicate fetches are cheaper than global coordination.
Common mistakes
- Ignoring politeness and designing only for throughput.
- A single global queue or global lock for rate limiting.
- Skipping URL normalization, which makes dedup ineffective.
- Forgetting traps, DNS cost, or what happens on node failure.
- Treating robots.txt errors uniformly rather than by status code.