Building a Large-Scale Internet Page Fetcher
System DesignModel answerLast updated
Design an architecture to retrieve and store billions of web pages while respecting site policies and handling failures gracefully.
You need to architect a system that downloads web pages at internet scale. The system should handle billions of pages, coordinate work across many machines, and behave responsibly toward the sites it visits.
What the System Must Do
Your design should address:
- Managing the work queue: How do you decide which pages to fetch next and in what order?
- Retrieving content: How do workers actually download pages?
- Respecting websites: How do you avoid overwhelming any single site with too many requests?
- Avoiding redundant work: How do you prevent fetching the same page or content multiple times?
Constraints and Goals
- Scale: The system should support thousands of worker machines operating concurrently
- Resilience: If a worker fails mid-download, that work should not be lost forever
- Refresh strategy: Important or frequently-changing pages should be revisited more often than static ones
What to Provide
- An architecture showing the major components and how they interact
- Your approach to preventing multiple workers from hitting the same domain simultaneously
- A data schema showing how you track which pages are pending, in-progress, or complete
- Your strategy for detecting duplicate URLs and content across billions of entries
Hints
Hint 1
Think about how to partition work so politeness becomes a local problem rather than requiring global coordination
Hint 2
Consider what happens when a worker crashes halfway through downloading a page - how does the system know to retry?
Hint 3
Bloom filters can help with deduplication, but remember they have false positives
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Building a Large-Scale Internet Page Fetcher: Model Answer
1. Establish Scale and Constraints
Before diving into architecture, quantify the problem:
- Volume: Targeting roughly 1 billion pages per day, with a known universe of 10–20 billion URLs
- Rate: 1B pages / 86,400 seconds ≈ 11,500 pages/second average, with peaks around 20–25k/s
- Network: Assuming 100 KB average page size, that's approximately 100 TB/day of raw content, or around 10 Gbps sustained bandwidth
- Worker capacity: A single async worker handling 500 concurrent connections at ~1s average latency can fetch 300–500 pages/s, suggesting 50–100 workers for baseline load
- Metadata storage: 10B URLs with ~500 bytes of metadata each ≈ 5 TB, requiring sharded storage
2. Overall Architecture
The system breaks down into several key stages:
Seed URLs & Recrawl Scheduler
↓
Work Queue (partitioned by domain)
• Priority tiers for important pages
• Per-host rate limiting
• Robots.txt cache
↓
Worker Pool (stateless fetchers)
• Lease-based work assignment
• DNS caching
• Connection pooling
↓
Content Storage (blob store like S3)
↓
Event Stream (e.g., Kafka)
↓
Link Extraction & Parsing
↓
Deduplication Layer
• URL normalization
• Content fingerprinting
↓
New URLs → back to Work Queue
Supporting Data Stores:
• URL State Database (sharded KV store)
• Host Metadata Store (rate limits, robots policies)
An event stream decouples stages, allowing each to scale independently and absorbing burst traffic.
3. Work Queue and Politeness (Critical Design Decision)
The core challenge is coordinating thousands of workers while ensuring no single website gets hammered.
Partitioning strategy: Shard the queue by hash(domain) using consistent hashing. Each queue shard owns a set of domains, making politeness enforcement purely local—no cross-shard coordination needed.
Two-level queue structure within each shard:
- Priority tier: Multiple queues (P0, P1, P2...) based on page importance. High-priority pages (from popular sites or frequently-changing content) get selected more often via weighted sampling
- Host-level queues: Each active domain gets its own FIFO queue
Politeness enforcement:
Maintain a min-heap keyed by next_available_time for each host. When dispatching work:
- Extract the host that's been waiting longest and is now ready
- Take one URL from its queue
- Reinsert the host with
next_available_time = now + crawl_delay
The crawl_delay comes from the site's robots.txt (or defaults to ~1 second). This ensures each domain sees at most one request per delay period.
Worker coordination:
Workers don't pick URLs directly. They call lease_batch(count) on a queue shard, receiving URLs from different ready hosts. Since each host has at most one URL in-flight, workers inherently avoid collisions.
Memory management:
Keep only active URLs in memory (perhaps the next few hundred per host). The full backlog stays in the URL State Database. Refill from storage as queues drain.
Rebalancing:
When adding/removing queue shards, consistent hashing relocates only ~1/N of domains. The new owner rebuilds its internal state from the Host Metadata Store.
4. Data Models
URL State Table (partition key: hash(url) for distribution; cluster by domain for locality):
url_id (hash) | Primary key
url (normalized) | Full URL after canonicalization
domain | Extracted registered domain
state | PENDING | FETCHING | DONE | FAILED | BLOCKED
priority_score | Float derived from page importance
worker_id | ID of worker that leased this URL
lease_expires | Timestamp when lease becomes invalid
retry_count | Number of fetch attempts
last_http_status | Response code from previous attempt
last_fetched | Previous successful fetch time
next_fetch_after | When to recrawl (for freshness)
content_fingerprint | SHA-256 for duplicate detection
blob_location | Pointer to stored content
Host Metadata Table:
domain | Primary key
robots_content | Cached robots.txt
robots_fetched_at | When robots.txt was last retrieved
crawl_delay_ms | Delay between requests (from robots or default)
max_parallel | Concurrent connections allowed (usually 1)
consecutive_errors | Counter for exponential backoff
backoff_until | Don't attempt this host until this time
average_latency_ms | Used to adjust delays dynamically
State transitions:
PENDING --[lease]--> FETCHING --[success]--> DONE --[schedule refresh]--> PENDING
|
+--[lease timeout/crash]--> PENDING (retry_count++)
|
+--[4xx/5xx error]--> FAILED --[backoff]--> PENDING or BLOCKED
5. Fault Tolerance Through Leases
When a worker takes URLs, it acquires a time-bound lease (typically 60–120 seconds):
- Worker calls
lease_batch(), receiving URLs with state changed toFETCHINGandlease_expiresset - If the worker completes successfully, it updates state to
DONE - If the worker crashes, it simply stops sending heartbeats
- A background reaper process periodically scans for expired leases and resets them to
PENDINGwith incrementedretry_count
This provides at-least-once execution: some pages might be fetched twice if a worker dies right after downloading but before confirming, but this is acceptable since completion is idempotent (content-addressed storage).
After excessive failures, mark the URL as BLOCKED and surface for manual review.
6. Distributed Deduplication
URL-level deduplication:
-
Normalize first: Lowercase hostnames, remove default ports and fragments, sort query parameters (or strip known tracking parameters like
utm_*), resolve relative paths. This step is essential—without it,example.com/pageandexample.com:80/pagewould be treated as different. -
Sharded Bloom filter: For 10B URLs with 1% false positive rate, you need ~10 bits/URL ≈ 12.5 GB total. Partition this by
hash(url)across shards, keeping each partition in memory.- Negative result → definitely new, insert into URL database
- Positive result → might be seen, query the database to confirm
- Never trust Bloom positives alone, or you'll silently drop valid URLs
-
Batch checks: Process link extraction output in batches per shard to amortize round-trip costs.
Content-level deduplication:
-
Exact duplicates: Compute SHA-256 of normalized HTML (strip whitespace, normalize encoding). Store in a
content_hash → canonical_urlmapping. On collision, mark as a mirror and skip parsing. -
Near-duplicates: Use SimHash (64-bit fingerprint). Store fingerprints and query for Hamming distance ≤ 3. This catches minor variations like different ad placements or timestamps. Use locality-sensitive hashing (split fingerprint into bands) to make similarity search efficient.
-
Crawler traps: Limit URLs per domain and enforce maximum path depth to avoid infinite calendar pages or session-ID variations.
7. Freshness and Priority
Not all pages should be refetched at the same rate:
- High-value pages (news sites, social media) may need hourly updates
- Static content (archived documentation) might refresh monthly
Compute next_fetch_after = last_fetched + adaptive_interval where the interval depends on:
- Observed change frequency (if content hash changed last time, shorten interval)
- Page importance score (derived from inlink count, traffic estimates)
- HTTP caching headers (Last-Modified, ETag) for conditional requests
A separate scheduler process scans the URL table for next_fetch_after < now and pushes those URLs back into the work queue with appropriate priority.
Common Mistakes
- Using a single global queue: Creates a bottleneck and makes politeness require distributed coordination
- Not normalizing URLs: Results in massive duplication—same page fetched under multiple equivalent URLs
- Trusting Bloom filters without confirmation: False positives silently drop real URLs
- Synchronous fetching: Blocks workers during network I/O; async I/O with connection pooling is essential
- Ignoring robots.txt: Gets your crawler banned
- No lease timeout mechanism: Worker crashes cause URLs to be stuck in FETCHING state forever
- Fetching robots.txt on every request: Should be cached per domain with TTL
Trade-offs and Extensions
- Rendering JavaScript: Some sites require a headless browser. Maintain a separate pool of render workers for URLs that need it (detected via response headers or failure patterns). This is expensive—reserve for high-value pages.
- Distributed vs centralized queue: The partitioned approach described here scales better than a centralized coordinator, but you could also use a message queue like Kafka as the work queue itself, with domain-keyed partitions providing natural ordering.
- Content extraction: This design focuses on fetching and storing raw content. Downstream parsing, indexing, and search serving are separate systems.