Architecting a Scalable, Politeness-Aware Web Crawler
System DesignModel answerLast updated
Design a high-throughput, distributed web crawling system that manages per-domain rate limits, prevents duplicate fetches, and handles network resilience at scale.
Design a large-scale distributed web crawler capable of continuously discovering, fetching, and persisting hundreds of millions of web pages per day across the public internet.
Requirements
- Host Politeness & Compliance: Strictly observe rules defined in
robots.txtfiles and enforce configurable per-domain request throttles (e.g., ensuring a mandatory delay between successive requests to the same hostname). - Horizontal Scalability & High Throughput: Efficiently scale out across a pool of stateless workers to crawl at least 100 million distinct documents per day.
- Multi-Stage Deduplication: Prevent redundant network requests and duplicate content storage by identifying seen URLs and duplicate document bodies.
- URL Normalization & Redirect Tracking: Consistently format discovered URLs, resolve relative hyperlinks, strip non-semantic query params, and follow HTTP redirect chains safely.
- System Fault Tolerance: Guard against worker crashes, non-responsive target servers, malformed HTML markup, and crawler traps.
Expected Output
- Provide a back-of-the-envelope capacity estimate (throughput, bandwidth, storage, and worker concurrency).
- Describe the high-level system architecture and data flow.
- Detail the design of the URL Frontier (priority vs. politeness management).
- Explain the multi-layer deduplication mechanism (URL filtering and content hashing).
- Outline failure handling strategies, including circuit breakers and parsing isolation.
Assume access to standard infrastructure components (message queues, distributed key-value databases, object storage, and distributed caches).
Hints
Hint 1
Decouple URL scheduling from network workers: use the Mercator model (priority queues feeding into host-specific politeness queues).
Hint 2
Partition host scheduling by consistent hashing on the domain name so that rate limits and robots.txt rules can be evaluated locally without distributed locks.
Hint 3
Implement deduplication in two stages: a light, probabilistic Bloom filter check before scheduling, and a content-hash check after downloading.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Scalable Web Crawler Architecture: Solution Walkthrough
Designing a concurrent web crawler requires balancing high-throughput parallel fetches with strict politeness policies. The core challenge lies in building a URL Frontier that ensures no single target web server is overloaded while maintaining saturated network links across thousands of target domains simultaneously.
1. Capacity Estimation & Core Metrics
Before designing the system, let's quantify the operational requirements for processing 100 million pages per day.
-
Fetch Throughput: $$\frac{100,000,000 \text{ pages}}{86,400 \text{ seconds}} \approx 1,157 \text{ pages/sec (average)}$$ Designing for a 3x peak load factor requires a system capable of handling ~3,500 requests/sec.
-
Network Bandwidth: Assuming an average HTML response size of 100 KB: $$\text{Average Inbound Bandwidth} = 1,157 \times 100 \text{ KB/s} \approx 115.7 \text{ MB/s} \quad (\sim 925 \text{ Mbps})$$ $$\text{Peak Inbound Bandwidth} = 3,500 \times 100 \text{ KB/s} \approx 350 \text{ MB/s} \quad (\sim 2.8 \text{ Gbps})$$
-
Storage Footprint:
- Raw compressed HTML storage (~30 KB compressed per page): $$100\text{M pages/day} \times 30\text{ KB} = 3\text{ TB/day} \implies \approx 1.1\text{ PB/year}$$
- Outlink discovery volume: Assuming an average of 50 links per page, the pipeline will encounter ~5 billion URL references per day, requiring fast inline deduplication.
-
Concurrency Requirements: Assuming an average HTTP response latency of 1.0 second (including DNS resolution and TLS handshake): $$\text{In-flight concurrent requests needed} = 3,500 \text{ workers/connections}$$
2. High-Level Architecture
The system decouples network fetching from link extraction and document parsing. This prevents slow target servers or compute-heavy HTML parsing from bottlenecking the network pipeline.
+----------------------------------+
| Seed Targets |
+----------------------------------+
|
v
+-------------------------------------------------+
| Discovered URL Broker (Kafka: partitioned by host)|
+-------------------------------------------------+
|
v
+-------------------------------------------------+
| Ingestion & URL Deduplication Service (Bloom) |
+-------------------------------------------------+
| (New URLs only)
v
+-----------------------------------------------------------------------+
| URL FRONTIER SHARDS |
| |
| +------------------------+ +-------------------------------+ |
| | Priority Queues (1..N) | -----> | Politeness Queues (per Host) | |
| +------------------------+ +-------------------------------+ |
| | |
| Ready Heap (Delay) |
+-----------------------------------------------------------------------+
|
| Leased Work Batch
v
+-------------------------------------------------+
| Stateless Fetcher Nodes (Async HTTP Client) |
+-------------------------------------------------+
/ \
(Raw Document HTML) (HTTP Response Metadata)
/ \
v v
+----------------------------------+ +--------------------------------+
| Parsing & Link Extractor Pool | | Metadata Store (Cassandra/DB) |
+----------------------------------+ +--------------------------------+
/ \
(Extracted Outlinks) (Content Hash)
/ \
v v
[Discovered URL Broker] [Content Dedup & Object Store (S3)]
3. Deep Dive: URL Frontier Design
The URL Frontier manages the queue of pending URLs. It uses the classic Mercator Frontier Architecture, divided into two tiers: Priority Queues and Politeness Queues.
Discovered URLs
│
▼
+-----------------------------------+
| Priority Selector Logic |
+-----------------------------------+
│
├───► [ Priority Queue 1 (High PageRank / News) ]
├───► [ Priority Queue 2 (Standard Content) ]
└───► [ Priority Queue 3 (Deep Links / Recrawl) ]
│
▼
+-----------------------------------+
| Politeness Router Logic | (Consistent Hash by registered domain)
+-----------------------------------+
│
├───► [ Host Queue: domainA.com ] ──► Next Available: T + 1000ms
├───► [ Host Queue: domainB.com ] ──► Next Available: T + 500ms
└───► [ Host Queue: domainC.com ] ──► Next Available: NOW
│
▼
+-----------------------------------+
| Min-Heap (Ready Queue) | (Ordered by Next Available Time)
+-----------------------------------+
│
▼
Stateless Fetchers (Lease Request)
Priority Queues (Front Queues)
URLs are scored by static and dynamic factors (PageRank estimate, host authority, freshness requirements, and link depth). High-scoring URLs enter higher-priority queues. A biased random scheduler selects work from these queues, favoring higher priorities to avoid starving lower-tier links.
Politeness Queues (Back Queues)
To avoid overwhelming a target host, requests must be throttled:
- Domain Partitioning: Each host domain (e.g.,
example.com) maps to exactly one back queue managed by a specific frontier shard using consistent hashing onregistered_domain. - State Tracking: Each host queue maintains state:
last_crawl_time: Timestamp of the last completed or dispatched request.crawl_delay: Delay specified byrobots.txt(defaulting to 1,000 ms if unspecified).in_flight_count: Number of active concurrent connections allowed for this host (typically capped at 1 to 2).
- Ready Min-Heap: Host queues are managed inside a priority heap indexed by
next_fetch_time = last_crawl_time + crawl_delay. The frontier worker continuously pops host queues whosenext_fetch_time <= current_time, dequeues a URL, updateslast_crawl_time, and re-inserts the queue back into the heap.
4. Concurrency & Fetcher Mechanics
Fetcher nodes are stateless and asynchronous (built using event loops such as Tokio or Netty):
- Lease Mechanism: Fetchers send a heartbeat request to frontier nodes:
GET /fetch-work?worker_id=W123&batch=50. - Work Leases: The frontier hands over URLs accompanied by a temporary lease (e.g., 30-second expiry). If the worker crashes before signaling completion, the lease expires and the URL is automatically re-queued.
robots.txtCompliance: Before performing a request, the worker checks its local LRU cache for the target host'srobots.txtdirectives. If missing, a high-priority job is issued to fetch and parsehttps://domain.com/robots.txt. Ifrobots.txtreturns a 4xx HTTP code, full access is assumed; if a 5xx error occurs, crawling for that domain is paused temporarily.- DNS Resolution: Fetchers maintain an in-memory DNS cache with short TTLs to prevent blocking on standard system resolver calls.
5. Multi-Layer Deduplication & Normalization
A. URL Normalization
Before evaluating duplicate states, every discovered link undergoes canonicalization:
- Convert scheme and host to lowercase (
HTTP://Example.COM/foo$\rightarrow$http://example.com/foo). - Remove standard ports (
:80,:443). - Strip URL fragments (
#section2). - Decode unreserved percent-encoded characters.
- Sort query parameters alphabetically and strip tracking tokens (
utm_source,gclid,fbclid). - Resolve relative paths (
/bar/../baz$\rightarrow$/baz).
B. Primary URL Deduplication (Pre-Fetch)
With billions of discovered outlinks daily, performing disk-based database lookups per URL is inefficient.
- Probabilistic Layer: A distributed Bloom Filter (or Cuckoo Filter) resides in cluster memory. For 10 billion items with a 0.1% false-positive rate, this requires: $$m = -\frac{N \ln p}{(\ln 2)^2} \approx 14.3 \text{ bits/element} \implies \sim 18 \text{ GB RAM}$$
- Durable Layer: If the Bloom filter yields a negative result, the URL is definitively new. If it yields a positive result, an exact lookup is run against a distributed key-value store (such as Cassandra) containing hashed canonical URLs (
SHA-256(url)).
C. Content Deduplication (Post-Fetch)
Target pages often contain duplicate content under different URLs (e.g., parameter variants or print views).
- Exact Matches: Calculate a cryptographic hash (
SHA-256) of the stripped response body. If the hash exists in the content store, skip parsing and point the metadata entry to the existing document. - Near-Duplicates: Compute a SimHash (or MinHash) over the document's word n-grams. Two pages are considered near-duplicates if their SimHash values differ by a Hamming distance of $\le 3$ bits.
6. Resilience, Error Handling, and Traps
| Failure Scenario | Mitigating Strategy |
|---|---|
Crawler Traps (Infinite paths like /calendar/next/next...) | Enforce a maximum path depth (e.g., 15 levels), limit the maximum URLs fetched per domain, and flag unusual path repetition patterns. |
| Slowloris / Hanging Servers | Set strict timeouts: 5s connection timeout, 15s total read timeout. Enforce maximum HTTP response body limits (e.g., 10 MB). |
| Malformed Markup / Memory Leak Spikes | Execute HTML parsing inside sandboxed, isolated worker pools running unprivileged processes. If a document crashes the parser, it routes directly to a Dead-Letter Queue (DLQ). |
| Domain Outages (Persistent 5xx / Timeouts) | Implement a per-host Circuit Breaker. If a domain produces 10 consecutive failures, open the breaker and suspend fetching for that host for 1 to 6 hours using exponential backoff. |
7. Common Implementation Pitfalls
- Global Domain Locks: Attempting to enforce per-host rate limits using a centralized Redis lock introduces severe network bottlenecking. Solution: Use consistent domain hashing to pin domain state locally within individual frontier nodes.
- Synchronous Fetching: Blocking a thread per HTTP connection limits a node's concurrency to its OS thread count. Solution: Use asynchronous, non-blocking I/O event loops capable of managing tens of thousands of concurrent sockets per machine.
- Ignoring DNS Infrastructure: Sending thousands of concurrent external DNS queries will trigger rate limiting by public resolvers or local ISPs. Solution: Deploy local caching DNS resolvers (such as Unbound) alongside fetcher nodes.