Designing a Polite, Scalable Web Crawler at Production Scale
System DesignModel answerLast updated
Design a distributed crawler that fetches pages quickly across many hosts while never overloading any single upstream, with safe retries, deduplication, fairness and monitoring.
A simple graph traversal over web pages now has to run as a production service. Visiting a page means making an outbound HTTP or API request to discover its outgoing links, and the servers you call may enforce tight rate limits or fall over if hit too hard.
Design a crawler that:
- Covers a very large set of pages or resources efficiently
- Does not let any single host become a throughput bottleneck for the whole system
- Never overloads the services it calls, even by accident
- Deals with retries, timeouts and partial failures safely
- Scales out across many workers or machines
In your answer, cover:
- Requirements, scale assumptions and back-of-envelope numbers
- Overall architecture and the data model
- Concurrency model and request scheduling
- Deduplication of URLs and content
- Rate limiting and backoff
- Fairness across domains
- Failure handling
- Observability and operational controls
State your assumptions explicitly and explain the trade-offs behind your main choices.
Hints
Hint 1
Ask what the real bottleneck is. If a site accepts one request per second, what limits how fast you can finish crawling it, and where can parallelism actually help?
Hint 2
Consider partitioning the work queue by host so that exactly one scheduler owns each host. What does that do to the difficulty of enforcing per-host rate limits?
Hint 3
Use Little's law (concurrency = throughput x latency) to size the number of in-flight requests, and think about which signals (429, Retry-After, rising latency, consecutive errors) should slow a host down.
Hint 4
Retries must never bypass throttling. Think about routing them back through the same scheduler, with jittered exponential backoff, a retry budget, leases for crashed workers, and a dead-letter queue.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The tension is throughput versus politeness. You want thousands of fetches per second overall, but no single upstream should see more than it can tolerate. The central principle is to schedule by host, not by URL. Most of the design follows from it.
1. Requirements and numbers
Assumptions to state:
- About 1B URLs over about 1M hosts, with a heavily skewed distribution (a few hosts hold millions of pages).
- Target of about 5,000 fetches/s in aggregate.
- Average fetch latency of about 500 ms. By Little's law, in-flight requests = 5,000 x 0.5 = about 2,500. This fits in a few dozen async worker processes, so you do not need thousands of threads.
- Default politeness of 1 req/s and 1-2 concurrent connections per host. Honor
robots.txt,Crawl-delay,429andRetry-After. Respect published API quotas (for example 100 req/min per key). - Semantics: at-least-once fetching with idempotent processing. Safety matters more than freshness.
Key sanity check: at 1 req/s, a single host with 1M pages takes about 11.5 days. The per-host limit is the bottleneck, not your fleet, and parallelism only helps across hosts.
2. Data model and control plane
- URL record:
url_hash(PK), normalized URL, host, depth, priority, state (queued | leased | done | failed), attempts,next_attempt_at,lease_expiry. - Host record: rate limit, current rate, max concurrency, in-flight count,
next_allowed_at, consecutive failures, breaker state, parsed robots rules and fetch time. - Seen set: a Bloom filter in front of a durable key-value store keyed by
url_hash. - Content store: page metadata plus
content_hash, written idempotently byurl_hash. - Control API: create a crawl (seeds, scope, depth, default rate), query status, and set per-host policy (rate, concurrency, pause) as a manual override and kill switch.
3. Architecture
Pipeline: seeds, then URL normalizer, then dedup, then a frontier partitioned by host, then host-scheduler shards, then async fetchers, then the parser/link extractor, which feeds back into the normalizer. Results, metrics and a dead-letter queue sit alongside.
The most important decision is to partition by host (Kafka partitions or consistent hashing on the host key). Each host is owned by exactly one scheduler shard, so rate limiting is local and exact. There is no distributed token bucket and no Redis round trip per request. Scaling means rebalancing partitions, and a new owner rebuilds host state from the host table.
4. Scheduling and concurrency
Use a Mercator-style layout: priority front queues and per-host back queues. Each shard runs one event loop:
- Pop the host with the smallest
next_allowed_atfrom a min-heap, sleeping if it is in the future. - Check that the host's breaker is closed,
in_flight < max_concurrency, and a global semaphore slot is free. - Take the host's best URL, lease it, and dispatch an async fetch.
- Set
next_allowed_at = now + 1/rateand re-insert the host if it still has work.
Idle hosts cost nothing, and a slow host cannot block fast ones because only ready hosts surface from the heap. Fetchers use pooled connections, strict timeouts and body-size caps.
5. Deduplication
- Normalize first: lowercase the host, strip fragments, drop default ports, sort or filter query parameters, resolve relative paths, and remove known tracking parameters.
- URL dedup: check the Bloom filter (cheap negatives), then confirm against the KV store on a positive. Bloom false positives would otherwise silently drop pages, so confirm before discarding.
- Content dedup: hash the body (or use SimHash for near-duplicates) to avoid re-processing mirrors and session-ID variants.
- Crawler traps: cap depth, cap per-host frontier size (spilling to disk), and detect patterns such as endlessly growing paths or calendars.
6. Rate limiting and backoff
- Static ceiling: the minimum of the default rate,
Crawl-delayand any published quota. - Adaptive rate (AIMD): increase additively while latency is healthy, and halve on
429,503or sharply rising p99 latency. Latency-based adjustment protects hosts that degrade without ever returning 429. - Retry-After applies to the whole host, not only the failing URL.
- Circuit breaker per host: after N consecutive failures, open for a cool-down, then half-open and probe with one request.
- Politeness key: throttle by registered domain or resolved IP when that is more conservative than the hostname, since several subdomains and a CDN may share one origin.
7. Fairness
- Weighted round-robin across hosts via the heap, so a giant site gets its fair rate rather than the whole fleet.
- Per-tenant or per-crawl quotas so one large job cannot starve others.
- Bounded per-host frontier to cap memory.
8. Retries and partial failure
- Timeouts: connect about 3 s, total about 10-15 s, max body about 10 MB, redirect limit of about 5.
- Classify errors: retry timeouts, 5xx, 429 and resets. Do not retry most 4xx or robots-disallowed URLs.
- Exponential backoff with full jitter:
delay = random(0, min(cap, base * 2^attempt)). Retries re-enter the host scheduler, so they obey the same limits. - Retry budget: at most about 5 attempts per URL, and retries capped near 10% of a host's traffic so they cannot amplify an outage. Exhausted URLs go to a dead-letter queue for inspection.
- Leases: a leased URL carries an expiry. If a worker dies, the lease lapses and the URL is requeued. Because delivery is at-least-once, writes must be idempotent by
url_hash. - Shard failure: another node takes the partition and reconstructs host state. The worst case is a brief burst of duplicate or early requests, so persist
next_allowed_atperiodically and add a short warm-up delay after rebalance.
9. Observability
- Per host: request rate, in-flight count, error mix (2xx/4xx/5xx/timeouts), p50/p99 latency, current AIMD rate, breaker state.
- Global: frontier depth, lease-expiry rate, dedup hit rate, DLQ size, fetch throughput, and crawl-completion estimate.
- Alerts: a host's 429 rate climbing, breakers opening en masse (possibly your own network), or growing lag on a partition.
- Controls: per-host pause, rate override and blocklist, plus a global kill switch.
- Use structured logs with crawl ID, host and URL hash, and a clear User-Agent with a contact address so site owners can reach you.
Trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Host-partitioned scheduling | Exact local limits, no shared state | Hot hosts cannot spread across shards |
| Bloom + KV dedup | Low memory, fast | Extra lookup on positives |
| AIMD adaptive rate | Self-protects upstreams | Slower ramp-up |
| At-least-once with leases | Simple recovery | Requires idempotent writes |
Common mistakes
- Using a global rate limiter or a global queue, so a single slow host stalls everyone.
- Letting retries bypass the throttle and create retry storms.
- Backing off only the failing URL rather than the whole host after a
429. - Retrying without jitter, causing synchronized spikes.
- Ignoring
robots.txt, subdomain-to-origin sharing, and crawler traps. - Using a Bloom filter alone for dedup and silently losing pages to false positives.
- Having no kill switch or per-host metrics when something goes wrong.