Design a Distributed Web Crawler at Scale
System DesignModel answerLast updated
Design a fault-tolerant, distributed web crawler that discovers, fetches, parses, and stores billions of pages while respecting site politeness rules.
Distributed Web Crawler
A web crawler is the foundation of any search engine or large-scale content analysis pipeline. Your task is to design one that can operate continuously at internet scale.
What the system must do
- Accept seed URLs, fetch each page, extract outbound links, and continue crawling discovered URLs.
- Re-visit pages periodically, prioritizing pages that change frequently or carry high importance.
- Respect each site's
robots.txtfile, honor crawl-delay directives, and never overwhelm any single host. - Persist crawled content and metadata for downstream consumers such as a search indexer.
What the system must handle well
- Scale: billions of pages, continuous operation over weeks or months.
- Politeness: no site should be hit faster than it allows.
- Fault tolerance: individual node failures or transient network errors must not require a full restart.
- Robustness: spider traps, malformed HTML, enormous responses, redirect chains, and near-duplicate or exactly-duplicate content.
- Observability: operators need visibility into crawl progress, error rates, and host-level health.
What to cover in your answer
- Back-of-envelope sizing — state your assumptions and derive the numbers that drive your design choices.
- High-level architecture — components, data flow, and how they connect.
- URL frontier design — how you balance priority with per-host politeness.
- URL deduplication — how you avoid re-crawling or re-storing the same URL.
- Fetching layer — async I/O, DNS,
robots.txthandling, timeouts, and conditional requests. - Parsing and content deduplication — link extraction, exact duplicates, near-duplicates.
- Storage — what you store, where, and in what format.
- Failure handling and retries.
- Monitoring and operational concerns.
A strong answer sizes the problem first, spends most of its depth on the URL frontier and politeness design (the parts candidates most often under-design), and clearly separates URL deduplication from content deduplication. Trade-offs and concrete numbers are expected throughout.
Hints
Hint 1
Start with numbers. Derive pages/second, bandwidth, and the size of the seen-URL set before drawing any boxes. Those numbers will justify every major architectural choice that follows.
Hint 2
The URL frontier is two distinct structures layered together: a priority layer that decides what to crawl next, and a per-host politeness layer that decides when it is safe to crawl it. Design both explicitly and explain how URLs move between them.
Hint 3
URL deduplication (have we seen this URL before?) and content deduplication (have we stored this page before?) are separate problems that require different data structures. A Bloom filter in front of a sharded key-value store handles URL dedup; SimHash handles near-duplicate content.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong answer moves in one direction: numbers first, then architecture, then deep dives on the hardest sub-problems. Avoid jumping straight to components. The scale estimates determine whether a simple design is viable or whether sharding, async I/O, and disk-spilling are non-negotiable.
1. Sizing the Problem
Assume the goal is 1 billion pages per week.
- Throughput: 1B / (7 × 86 400) ≈ 1,650 pages/s average; plan for ~5,000/s at peak.
- Bandwidth: average HTML page ~100 KB raw, ~20 KB compressed. At 1,650/s that is ~165 MB/s raw (~1.3 Gbps).
- Storage: ~100 TB raw per week, ~20–30 TB compressed. History across months reaches petabyte scale — use an object store with compression and batching (WARC format is standard).
- URL set: Assume each page yields ~50 outlinks. That is ~80,000 new URL candidates/s to deduplicate. With 10B known URLs, a 64-bit fingerprint per URL needs ~80 GB — must be sharded. A Bloom filter at 1% FPR needs ~12 GB and fits in memory on one node.
- Fetch latency: 0.5–2 s per page means thousands of concurrent requests per fetcher node. Synchronous I/O is completely infeasible; async I/O is required.
These four conclusions — sharded dedup, disk-spilling frontier, async fetchers, object store for content — all follow from the numbers. State this explicitly in an interview.
2. High-Level Architecture
Seeds
└─► URL Frontier ──► Fetcher Workers ──► Object Store (raw HTML)
▲ │ │
│ ▼ ▼
│ Kafka (page events) Parser Workers
│ │
└──── Link Pipeline ◄────────────────────┘
(normalize → filter → URL dedup → enqueue)
Every stage except the frontier and dedup stores is stateless. Stages communicate through Kafka topics, so each scales independently and a failure in one stage does not cascade.
3. URL Frontier: Priority + Politeness
This is the most important component and the one most candidates under-design.
Front queues (priority layer)
Assign each URL a numeric score based on host importance (e.g. estimated PageRank), observed change rate, crawl depth, and recrawl freshness requirements. Maintain ~10–20 priority buckets. A selector draws from buckets with weighted probability, giving high-priority URLs preference while ensuring low-priority URLs are never completely starved.
Back queues (politeness layer)
Each back queue holds URLs for exactly one host. A min-heap keyed by next_allowed_fetch_time selects which host's queue to drain next.
After each fetch:
next_allowed = now + max(robots_crawl_delay, k × last_response_time_ms)
The adaptive backoff automatically reduces pressure on slow servers without any manual tuning. Also limit concurrent connections per IP, since many hostnames share an IP on shared-hosting infrastructure.
Sharding: Partition frontier nodes by hash(host). One node owns all politeness state for a given host, eliminating the need for distributed locking on politeness enforcement.
Spilling to disk: Only queue heads stay in memory. The bulk of the frontier lives on disk or in Kafka partitions. Budget memory for ~a few million live URLs per node; the rest is durable but cold.
4. URL Deduplication
- Normalize each extracted URL: lowercase scheme and host, drop fragments and default ports, resolve relative paths, sort query parameters, strip known tracking parameters (
utm_*, session IDs, etc.). - Fingerprint with a 64-bit hash (e.g. MurmurHash3 or xxHash) of the normalized form.
- Bloom filter first: An in-memory Bloom filter (~12 GB at 1% FPR, zero false negatives) filters the vast majority of already-seen URLs in a single memory lookup without a network round trip.
- Authoritative KV store: Bloom filter positives are confirmed against a sharded key-value store (e.g. Redis cluster or Bigtable). Only new URLs proceed to the frontier.
- Batch lookups per shard to amortize network overhead and sustain 80k lookups/s.
Common mistake: using a single-node store for URL dedup at this scale. It will become the bottleneck immediately.
5. Fetching Layer
- Async I/O: each fetcher node runs thousands of concurrent requests (Python asyncio/aiohttp, Java Netty, Go goroutines all work).
- DNS: run a local caching resolver per fetcher node. DNS is a common hidden bottleneck that kills throughput.
- robots.txt: cache per host with a ~24h TTL. A 4xx response means allowed; a 5xx or timeout means treat as disallowed and retry later. Parse
User-agent,Disallow, andCrawl-delayfields. - Timeouts: connect ~5s, total response ~30s.
- Response caps: stop reading after ~5 MB; reject obviously non-HTML content types unless the job scope includes them.
- Redirects: follow at most 5 hops; record the final URL as canonical.
- Conditional requests: on recrawls, send
If-Modified-Since/If-None-Match. A 304 saves bandwidth and skips parsing entirely.
6. Parsing and Content Deduplication
- Parse leniently — real HTML is frequently malformed. Extract: outlinks,
<title>, meta-robots (noindex/nofollow), canonical link hints, and body text. - Exact deduplication: SHA-256 of normalized body. On a collision, store a reference to the canonical URL instead of a second copy.
- Near-deduplication: Compute a SimHash (64-bit locality-sensitive fingerprint). Pages within Hamming distance ≤ 3 are near-duplicates. Use permuted-index lookup (split bits into blocks, index each permutation) to find matches efficiently across billions of stored fingerprints.
- JavaScript rendering: ~10–100× more expensive than static parsing. Run a separate headless-browser tier, only for high-value hosts that require it.
7. Storage Layout
| What | Where | Notes |
|---|---|---|
| Raw pages | Object store (S3/GCS), WARC format | Compressed, batched, cheap at scale |
| URL state | Wide-column store (Cassandra/Bigtable) sharded by URL hash | status, last_fetch, next_fetch, priority, etag, fail_count |
| Host state | Same store + in-memory cache | robots rules, crawl_delay, error_rate |
| Content fingerprints | Sharded KV store | SHA-256 → canonical URL; SimHash index |
| Crawl events | Kafka topic | Downstream consumers subscribe; decouples indexing pipeline |
8. Failure Handling
- Transient errors (5xx, timeout): exponential backoff up to a max delay (~24h), with a fail count cap (~5) after which the URL is deprioritized or dropped.
- Spider traps: detect path-length explosions or parameter permutations during normalization; enforce a max URL length (~2 KB) and max depth per domain.
- Poison pages: cap response size and parse time; run parsers in isolated processes or containers.
- Crawler node failure: all durable state lives outside the fetcher (frontier on disk/Kafka, URL table in the KV store). Restart a failed node; it picks up from the frontier with no data loss.
- Checkpointing: frontier and dedup state are append-only or versioned. A full restart replays from the last durable checkpoint.
9. Monitoring
Key metrics to track per-host and globally:
- Pages fetched/s, bytes downloaded/s (throughput)
- Frontier depth per priority bucket (backlog health)
- robots.txt compliance violations (should be zero)
- HTTP status code distribution (4xx/5xx rates flag crawl problems early)
- Duplicate rates (URL and content) — a sudden spike often signals a spider trap
- P95/P99 fetch latency and timeout rates per host
Alerting on frontier depth drop (fetchers consuming faster than discovery) or a sudden spike in 5xx from a host (back off immediately) covers the most operationally critical scenarios.
Common Mistakes to Avoid
- Designing the frontier as a single global priority queue — this conflates priority with politeness and will hammer individual sites.
- Treating URL dedup and content dedup as the same problem — they require different data structures and catch different failure modes.
- Skipping the DNS cache — at 5,000 fetches/s, DNS lookups without caching saturate resolvers within minutes.
- Using synchronous fetchers — a single slow host stalls the entire crawl without async I/O.