Throttling and Scheduling a Distributed Web Crawler

Medium · System Design · Software Engineer · Onsite

Prompt

Suppose you have a prototype graph crawler that discovers child URLs by issuing an outbound HTTP or REST API request for every visited page, and you now need to turn it into a reliable, multi-node production platform. Many target domains and third-party APIs enforce tight request quotas or degrade rapidly under bursts of concurrent traffic.

Design a distributed crawling system that satisfies the following requirements:

  • High aggregate throughput: Traverse millions or billions of pages and API resources efficiently across a fleet of worker machines.
  • No per-host head-of-line blocking: Slow responses, cooldown timers, or outages on individual domains must never stall workers from fetching ready hosts.
  • Strict upstream politeness: Pace outbound traffic per target host or API quota so the fleet never overwhelms target hosts or triggers an accidental denial-of-service.
  • Fault-tolerant execution: Handle socket timeouts, HTTP 429 / 5xx responses, retries, and mid-crawl worker crashes safely without dropping URLs or double-hammering struggling endpoints.

Scope & Expectations

  • Present the end-to-end cluster topology, worker partitioning scheme, async/multi-process concurrency model, and URL canonicalization and deduplication strategy.
  • Detail the request frontier and scheduler so per-host rate spacing, in-flight concurrency caps, and cross-domain fairness hold without blocking worker slots.
  • Specify adaptive rate control, robots.txt and Retry-After compliance, jittered exponential backoff, circuit breaking, and crash-safe worker leases.
  • Define production observability metrics, upstream distress alerts, and operator emergency shutoff controls.

Step-by-step walkthrough

  1. Clarify requirements and politeness goals

    A distributed crawler lives inside a fundamental tension: we want high global throughput across millions of pages, yet every individual upstream server wants us to go slowly. That means speed can never come from hammering one host harder — global throughput must come from crawling thousands of different hosts in parallel while strictly pacing each host so slowness, rate limits, or crashes on one domain never block others or cause an accidental denial-of-service (DoS).

    Functional requirements

    • Start from seed URLs, make outbound HTTP or API calls to fetch pages/resources, extract child links, and enqueue unseen links.
    • Fetch each normalized URL at most once per crawl job (unless explicitly scheduled for re-crawl).
    • Enforce per-host politeness: operator caps, robots.txt, upstream API rate-limit headers, 429 Too Many Requests, and Retry-After pauses.
    • Handle timeouts, transient network errors, and partial post-fetch crashes safely without losing URLs or flooding struggling hosts.
    • Scale horizontally across multiple worker machines with operator controls (pause, resume, per-host overrides, and an emergency kill switch).

    Non-functional requirements

    • Strict politeness invariant: Never exceed a host's allowed request rate or concurrency limit — even across retries, worker crashes, or cluster rebalances.
    • Zero head-of-line blocking: One slow, throttled, or dead upstream host must never stall workers from crawling healthy hosts.
    • Fairness across domains: Small websites with 20 pages finish promptly instead of starving behind giant 5-million-page domains.
    • Observability: Real-time visibility into per-host request rates, 429/5xx ratios, queue depth, and instant < 5 s emergency shutoff.

    Clarifying questions and assumed answers

    • What scale should we design for? 1 billion URLs across 2 million distinct hosts, targeting 2,000 fetches/s globally (~173 million pages/day).
    • Are upstreams public web servers, APIs, or both? Both: standard HTTP web servers (governed by robots.txt and IP/domain politeness) and third-party REST APIs (governed by per-API-key quotas such as 10 req/s).
    • What is our default politeness rule? Unless configured otherwise or slowed down by upstream feedback, at most 1 request/s and at most 2 concurrent in-flight requests per host.
  2. Back-of-the-envelope numbers and politeness math

    We use Little's Law (in_flight = arrival_rate * average_latency) to size network concurrency, memory, and disk:

    1. Network concurrency & bandwidth
       Global fetch target     2,000 fetches/s (~173M URLs/day -> ~5.8 days for 1B URLs overall)
       Upstream latency        p50 = 300 ms, mean = 500 ms, p99 = 5 s, hard total timeout = 30 s
       Concurrent sockets      2,000 req/s x 0.5 s mean = 1,000 active sockets on average
                               Provision 4,000 async slots (4x headroom so slow p99 tails never starve fast hosts)
       Inbound bandwidth       2,000/s x ~50 KB avg page = ~100 MB/s (~800 Mbit/s)
       HTML/JSON parse CPU     2,000/s x ~5 ms CPU/page = ~10 CPU cores total across the cluster
    
    2. Politeness math (why adding workers cannot speed up one host!)
       Default host limit      1 request/s per host
       Active breadth needed   Need >= 2,000 distinct hosts with queued URLs simultaneously to hit 2,000/s
       Single giant domain     A host with 5,000,000 URLs at 1 req/s takes 5,000,000 s = ~58 days,
                               no matter whether we run 10 workers or 10,000 workers!
       Single strict API       An API capped at 10 req/s per API key yields <= 10 fetches/s unless batched.
    
    3. State sizing (across 16 crawler nodes, 4 virtual shards per node = 64 virtual shards)
       URL frontier (queued)   up to 1B URLs x ~100 B = ~100 GB on disk (~6.25 GB per node in replicated KV store)
       Seen-URL set (RAM)      1B URLs x 8-byte (64-bit) hash = 8 GB raw (~1 GB hash-table RAM per node!)
                               (or 128-bit hashes = ~2 GB RAM per node for mathematically zero hash collisions)
       Per-host runtime state  2M hosts x ~120 B = ~240 MB total (~15 MB RAM per node)
    

    Three key takeaways shape the architecture: - Politeness — not CPU or sockets — is the bottleneck. Just 16 machines running 250 async I/O slots each easily hold 4,000 open connections. - Exact deduplication fits in RAM. At 1 billion URLs partitioned by host across 16 nodes, each node's seen-URL fingerprint set takes ~1–2 GB of RAM — zero disk reads per link check! - Giant domains finish last by design. Our job is ensuring a 5-million-page site paces smoothly in the background without ever delaying smaller domains.

  3. Interfaces and data model

    Operators need first-class controls to throttle or stop traffic immediately (for example, if a site administrator emails the contact address in our User-Agent header).

    Control Plane API
      POST /v1/crawls                 { seeds, allowed_hosts, max_depth: 5, max_pages_per_host: 1_000_000, priority }
      POST /v1/crawls/{id}/pause      (also /resume and /cancel)
      PUT  /v1/host-policies/{key}    { max_rate_rps, max_in_flight, blocked: bool }
      POST /v1/kill-switch            { scope: "ALL" | crawl_id | politeness_key }  -- halts dispatches in < 3 s
    

    Choosing the politeness_key: Rate limits must match what sits on the other end of the wire. For web pages, simply keying by hostname (sub1.shop.com, sub2.shop.com) can accidentally multiply load on one backend if a company uses 100 subdomains; conversely, keying naively by top-level suffix would lump independent users on alice.github.io and bob.github.io together. We extract the registered domain using the Public Suffix List (a community-maintained catalog of public domain suffixes like .co.uk and .github.io), so a.acme.com and b.acme.com share one budget (acme.com), while alice.github.io gets its own. For APIs, politeness_key is (api_provider, api_key_id).

    1. url_record (Partitioned by virtual_shard = hash(politeness_key) % 64 in transactional KV store, e.g. FoundationDB)
       Primary key: (virtual_shard, url_fingerprint_128bit)
         url, politeness_key, crawl_id, depth, priority
         state            "QUEUED" | "LEASED" | "DONE" | "DEAD_4XX" | "FAILED"
         attempts         int (0..5)
         lease_until_ms   timestamp when an in-flight worker lease expires on crash
         content_hash     SHA-256 of fetched body (enables crash-safe resume without re-fetching!)
    
    2. frontier_queue (Disk-backed per-host FIFO/priority queue in the same KV store)
       Key: (virtual_shard, politeness_key, priority, sequence_no) -> url, url_fingerprint
       (Only the next ~100 URLs of each active host are prefetched into node RAM!)
    
    3. host_policy (Replicated config from etcd / Postgres to all nodes)
       politeness_key -> { max_rate_rps, max_in_flight, blocked, robots_rules, robots_expires_at }
    
    4. host_runtime (In owning node's RAM; checkpointed every 60 s, and written IMMEDIATELY on 429 / Retry-After)
       politeness_key -> { current_rate_rps, next_allowed_ms, in_flight,
                           consecutive_failures, circuit_state, latency_ewma_ms }
    
  4. High-level architecture and concurrency model

    Routing every URL by hash(politeness_key) % 64 gives each host one exclusive owner node. That eliminates distributed rate-limiter network calls on every fetch!

                            Seed URLs / Control API
                                      |
                                      v
                      URL Normalizer + Scope Filter <------------------------+
                       | route batches by hash(politeness_key) % 64          |
                       v                                                     |
     +---------------- Crawler Node (16 nodes, 4 virtual shards each) -------|-------+
     |                                                                       |       |
     |  1. In-Memory Seen Set (128-bit URL fingerprints; durable in KV)      |       |
     |        | (unseen URLs only)                                           |       |
     |        v                                                              |       |
     |  2. Disk-Backed Frontier  --->  3. Single-Threaded Shard Scheduler    |       |
     |     (per-host queues,              - Ready Min-Heap (next_allowed_ms) |       |
     |      top ~100 cached in RAM)       - Per-host rate + in-flight cap    |       |
     |                                    - Circuit breakers & retry heap    |       |
     |                                           | lease URL                 |       |
     |                                           v                           |       |
     |                                 4. Async HTTP Fetcher Pool            |       |
     |                                    (event loop, 250 socket semaphore, |       |
     |                                     DNS cache, HTTP keep-alive pools) |       |
     +-------------------------------------------|---------------------------|-------+
                                                 v                           |
                                     Upstream Web Hosts & APIs               |
                                                 | response                  |
                                                 v                           |
                           Bounded Queue ---> CPU Parser Process Pool -------+
                                                 |             (extracted child links)
                                                 +--> Content Store (S3) + Kafka Crawl Log
    

    Why each stage uses a different concurrency model: 1. Fetching is I/O-bound -> Single-process Async Event Loop (asyncio / Tokio) capped by a semaphore of 250 slots per node (4,000 cluster-wide). Waiting 5 seconds on a slow server uses ~4 KB of coroutine state instead of blocking an OS thread, and per-host HTTP keep-alive pools reuse TLS connections so we do not hammer upstreams with repeated TLS handshakes. 2. HTML/JSON link extraction is CPU-bound -> Separate Process Pool connected by a bounded queue (say 1,000 responses). If CPU parsers fall behind, the bounded queue fills and fetchers automatically pause leasing new URLs (backpressure), keeping memory flat. 3. Host scheduling is fast in-memory bookkeeping -> Single-threaded per shard, requiring zero mutex locks and zero network round trips per request.

  5. Deep dive: Per-host frontier queues and ready-heap scheduling

    In a naive BFS crawler, all workers pull from one shared FIFO queue. In production, that fails immediately for two reasons: - Same-host burst (accidental DoS): Crawling acme.com/index discovers 500 links on acme.com and pushes them together. Fifty idle workers pop all 500 at once and blast acme.com! - Head-of-line blocking: When the front of the shared queue holds URLs for throttled hosts, workers either sleep while holding slots (starving healthy hosts behind them) or spin in a busy loop re-queueing blocked URLs.

    We use the classic Mercator frontier pattern: one FIFO queue per host paired with one min-heap of ready timestamps (ready_heap). Each active host has at most one entry (next_allowed_time, politeness_key) in the min-heap:

    Per-Host Queues (RAM head + Disk tail)          Ready Min-Heap (earliest allowed host on top)
      oak.dev   : [/guide, /pricing, /docs ...]  \
      maple.io  : [/v2/orgs, /v2/teams]           +-->  [ (t = 10.00s, "maple.io"),
      pine.org  : [/blog/1, /blog/2]             /        (t = 10.40s, "pine.org"),
                                                          (t = 45.00s, "oak.dev") ]  <-- paused by 429!
    

    Notice we enforce two independent limits on every host: 1. Rate spacing (1.0 / rate seconds between request starts) — acts like a 1-token bucket so requests are smoothly spaced and never burst. 2. Concurrency cap (max_in_flight = 2) — critical when an upstream slows down! If oak.dev suddenly takes 20 seconds to answer, 1 req/s spacing alone would pile up 20 simultaneous requests on a dying server. Capping in_flight < 2 automatically slows dispatch down to match what the server can finish.

    import heapq
    from collections import deque
    
    
    class HostState:
        def __init__(self, key: str, initial_rate: float = 1.0, max_rate: float = 1.0, max_in_flight: int = 2):
            self.key = key
            self.queue = deque()              # In-memory head (~100 URLs) of disk-backed host queue
            self.rate = initial_rate          # Current adaptive rate (requests/sec)
            self.max_rate = max_rate          # Hard ceiling from operator policy / robots.txt
            self.max_in_flight = max_in_flight
            self.in_flight = 0
            self.next_allowed = 0.0           # Earliest timestamp (sec) next request may start
            self.in_heap = False              # Ensures at most 1 heap entry per host
    
    
    class HostScheduler:
        def __init__(self):
            # hosts: politeness_key -> HostState
            self.hosts: dict[str, HostState] = {}
            # ready_heap: min-heap of (next_allowed_sec, politeness_key)
            self.ready_heap: list[tuple[float, str]] = []
    
        def get_or_create_host(self, key: str) -> HostState:
            if key not in self.hosts:
                self.hosts[key] = HostState(key)
            return self.hosts[key]
    
        def _maybe_push_heap(self, host: HostState) -> None:
            """Push host into ready_heap only if it has work, spare concurrency, and no existing entry."""
            if host.queue and not host.in_heap and host.in_flight < host.max_in_flight:
                heapq.heappush(self.ready_heap, (host.next_allowed, host.key))
                host.in_heap = True
    
        def enqueue_url(self, key: str, url: str) -> None:
            host = self.get_or_create_host(key)
            host.queue.append(url)
            self._maybe_push_heap(host)
    
        def next_ready_request(self, now: float):
            """Pop (host, url) ready to dispatch at `now` in O(log H) time, or None if none ready."""
            while self.ready_heap and self.ready_heap[0][0] <= now:
                _, key = heapq.heappop(self.ready_heap)
                host = self.hosts[key]
                host.in_heap = False
    
                # If a 429 Retry-After or circuit breaker pushed next_allowed later, re-push lazily.
                if host.next_allowed > now:
                    self._maybe_push_heap(host)
                    continue
    
                if not host.queue or host.in_flight >= host.max_in_flight:
                    continue
    
                url = host.queue.popleft()
                host.in_flight += 1
                # Enforce smooth spacing before the next request to this same host.
                host.next_allowed = now + (1.0 / host.rate)
                self._maybe_push_heap(host)
                return host, url
    
            return None
    
        def complete_request(self, host: HostState, status, retry_after_s, now: float) -> None:
            """Update adaptive rate/backoff first, then release in-flight slot and reschedule."""
            update_host_pace(host, status, retry_after_s, now)
            host.in_flight -= 1
            self._maybe_push_heap(host)
    

    With ~125,000 hosts per node (2M / 16), O(log H) is ~17 comparisons (< 2 microseconds), and when next_ready_request returns None, the event loop simply sets a timer for ready_heap[0][0] - now with zero CPU spin!

  6. Deep dive: Rate limiting, adaptive AIMD pacing, and circuit breakers

    Static rates are blind guesses — 1 req/s might still overload a tiny legacy server while under-utilizing a modern API. We combine strict hard ceilings with AIMD (Additive Increase, Multiplicative Decrease, the same congestion-control principle TCP uses): inch the rate up gently on fast 2xx responses (never passing max_rate), and cut the rate in half immediately on overload signals!

    MIN_RATE_RPS = 0.05       # Floor: 1 request every 20 seconds
    INCREASE_STEP_RPS = 0.05  # Gentle ramp: takes 10 healthy responses to climb +0.5 req/s
    
    
    def update_host_pace(host: HostState, status, retry_after_s, now: float) -> None:
        """Adjust host.rate and next_allowed based on upstream HTTP status or timeout (status=None)."""
        if status in (429, 502, 503, 504) or status is None:
            # Multiplicative decrease on explicit throttling, gateway overload, or timeout.
            host.rate = max(MIN_RATE_RPS, host.rate * 0.5)
            if retry_after_s is not None:
                host.next_allowed = max(host.next_allowed, now + retry_after_s)
        elif 200 <= status < 500:
            # Additive increase on healthy answers, strictly capped at host.max_rate.
            host.rate = min(host.max_rate, host.rate + INCREASE_STEP_RPS)
    

    Hierarchy of rate and safety guardrails: 1. Operator policy & Kill Switch: host_policy.max_rate and blocked = True override everything immediately. 2. Explicit upstream rate headers: Honor 429 / 503 Retry-After (persisted immediately to disk so a node restart never forgets a cooldown!), plus standard API quota headers (X-RateLimit-Remaining, RateLimit-Reset) to pace smoothly across the remainder of the quota window. 3. robots.txt compliance (RFC 9309): Before fetching any web page on a host, fetch /robots.txt and cache it up to 24 hours. Honor Crawl-delay if present as a lower max_rate. Crucial edge case: if /robots.txt returns 404 or 410, crawl normally; if /robots.txt returns 5xx OR 429 Too Many Requests, never treat 429 as "no restrictions" — pause all crawling on that host and retry /robots.txt with backoff! 4. Latency-based distress detection: Track an exponentially weighted moving average (EWMA) of response latency per host; if latency doubles above baseline, halve host.rate before the server starts throwing 503s. 5. Per-host circuit breaker: A circuit breaker stops calling a failing dependency so it can recover. If >= 50% of the last 20 requests fail (or 5 consecutive timeouts occur), trip the host circuit OPEN by setting host.next_allowed = now + 60s (doubling up to 1 hour on repeated trips), then allow 1 HALF_OPEN probe request to test recovery. 6. Shared-IP cap for cheap shared hosting: One thousand small domains hosted on the exact same IP address (203.0.113.10) would receive 1,000 req/s if paced only by domain! After DNS resolution, fetchers also acquire a token from a secondary per-IP bucket (e.g., 10 req/s per resolved IP, leased in batches of 20 tokens across nodes from Redis) so shared servers are protected too.

  7. Deep dive: Timeouts, jittered retries, crash leases, and deduplication

    1. Defensive socket timeouts on every outbound request: Set connect_timeout = 5 s, idle_read_timeout = 10 s, total_timeout = 30 s, and max_body_bytes = 10 MB. Without a total_timeout and size cap, a broken or malicious "tarpit" server sending 1 byte every 9 seconds holds a fetcher slot open forever!

    2. Outcome classification and full-jitter backoff: - 2xx: Store content, enqueue child links, mark DONE. - 301/302/307/308: Normalize redirect target and enqueue it through the normal dedup + target-host frontier (cap redirect chains at 5 hops) — never follow cross-host redirects inline without checking the destination host's rate budget! - 400/401/403/404/410: Permanent client outcomes -> mark DEAD_4XX, do not retry (if many URLs on one API return 401/403, pause that key and alert operators). - 429/500/502/503/504 & timeouts: Retry up to 5 attempts using full-jitter exponential backoff (picking a uniform random wait in [0, min(cap, base * 2^attempt)]), which spreads retries out over time instead of creating synchronized retry storms. Crucially, when a URL's retry timer matures, it re-enters its host queue and still obeys host.next_allowed — retries never bypass the host's rate limit!

    import random
    
    
    def compute_retry_delay_s(attempt: int, base_s: float = 1.0, max_cap_s: float = 600.0) -> float:
        """Full-jitter exponential backoff: random delay in [0, min(max_cap_s, base_s * 2**attempt)]."""
        exponential_ceiling = min(max_cap_s, base_s * (2 ** attempt))
        return random.uniform(0.0, exponential_ceiling)
    

    3. Crash-safe leases and idempotent partial-failure recovery: When leased to a fetcher, url_record sets state = "LEASED", lease_until = now + 60s. Processing one URL has three steps: (a) fetch bytes and write to object storage keyed by SHA256(body), saving content_hash on url_record; (b) parse links and enqueue through dedup; (c) mark state = "DONE". If a worker crashes mid-parse after fetching, the 60s lease expires, the next worker sees content_hash is already populated, and resumes directly from object storage without hitting the upstream server a second time! (For any non-GET API calls with side effects, attach a deterministic Idempotency-Key.)

    4. Three-stage deduplication: - URL canonicalization: Lowercase scheme/host, strip default ports (:80, :443) and #fragments, resolve ../, and strip known tracking params (utm_*, fbclid). - Exact seen-URL fingerprint set: Store 128-bit hashes (16 bytes x 1B URLs = 16 GB total -> 1 GB RAM per node) in memory, backed durably by url_record keys on disk. Why not just a Bloom filter (a compact bit-array that answers "definitely unseen" or "maybe seen" with ~1% false positives)? Because a standalone Bloom filter silently drops ~1% of valid pages, and even in front of disk, >80% of links on web pages point to already-visited navigation/header URLs ("maybe seen"), which would still trigger disk lookups! A Bloom filter only becomes useful at ~10B+ URLs when exact 128-bit hashes outgrow RAM. - Content deduplication: Exact SHA256(body) skips re-parsing identical mirrors; SimHash (a locality-sensitive fingerprint where nearly identical HTML pages differ in <= 3 bits) detects infinite calendar/session-ID crawler traps serving the same template under millions of URLs.

  8. Scaling across machines and fairness across domains

    Partitioning and split-brain protection: 64 virtual shards map across 16 crawler nodes (4 shards/node) via leases in etcd carrying a monotonically increasing fencing token (epoch = 42). Every write to the frontier KV store includes epoch and is rejected if another node has already claimed epoch = 43. Because upstream HTTP servers do not know about our internal epoch, a node also checks its lease against a local monotonic clock (time.monotonic(), immune to NTP clock jumps) and stops dispatching 3 seconds before its lease expires — guaranteeing two nodes never simultaneously crawl the same host at 2x its rate during a network partition or GC pause!

    When Node A extracts links belonging to hosts on Node B, it buffers and ships them in micro-batches every 100 ms (or 1,000 URLs). Scaling from 16 to 32 nodes simply reassigns 2 virtual shards per node.

    Three-tier fairness: 1. Fairness across domains: Because ready_heap orders hosts by next_allowed, a small blog with 15 pages interleaves cleanly at 1 req/s alongside a 5-million-page e-commerce giant and finishes in 15 seconds, never queued behind the giant's 5,000,000 URLs! max_pages_per_host and max_depth prevent spider traps from monopolizing disk. 2. Fairness across tenants / crawl jobs: When more than 4,000 hosts are ready simultaneously, Weighted Fair Queuing (WFQ) allocates fetcher slots proportionally across active crawl_ids (e.g., high-priority jobs get 3x weight over background jobs). 3. Priority within one host: Inside each host's frontier queue, shallow pages (depth = 1) and sitemaps sort ahead of deep pagination links.

  9. Observability, failure modes, and trade-offs

    Real-time observability and alerts: - Politeness compliance dashboard: Actual dispatched req/s and in_flight vs. max_rate for top hosts (alert immediately if any host ever exceeds max_rate — indicates a bug in domain canonicalization or lease safety). - Upstream health signals: Per-host and global 429 rate (alert if > 1% for 5 min), 5xx rate, timeout rate, and count of OPEN circuit breakers. - Bottleneck diagnosis: Compare queued_urls, hosts_ready_now, and active_fetcher_slots. Many queued URLs + 0 hosts ready means we are politeness-bound (healthy, waiting on timers); many hosts ready + saturated parser queue means we need more CPU parser workers! - Structured audit log: Every fetch attempt streams {timestamp, crawl_id, url, politeness_key, resolved_ip, status, latency_ms, node_id} to Kafka so we can investigate any site owner's inquiry in seconds.

    Failure handling summary: - Worker crash: Shard leases expire in ~10 s; surviving nodes adopt the virtual shards, rebuild the 128-bit seen set from url_record keys, load checkpointed host_runtime (starting cautiously at min(checkpoint_rate, default_rate) while honoring any persisted Retry-After cooldowns), and re-queue expired LEASED URLs. - Global DNS or outbound network blip: If > 50% of distinct hosts fail simultaneously, a cluster-wide circuit breaker pauses scheduling and alerts engineers instead of burning through every URL's 5-attempt retry budget!

    Summary of key trade-offs: - Per-host queues + ready min-heap vs. single shared queue: Eliminates head-of-line blocking and same-host bursts completely, at the cost of maintaining per-host queues in a partitioned KV store. - Host-sharded single-node ownership vs. centralized Redis rate limiter: Achieves exact, zero-RPC per-request pacing and concurrency tracking, requiring fenced shard leases for safe failover. - AIMD adaptive pacing under hard caps vs. static rates: Automatically backs off when a fragile server slows down while utilizing allowed capacity on fast servers.

Intuition & how it works

Imagine managing a research team making phone calls to 2 million local businesses, where every business gets angry if you call them more than once per second. If 100 callers all grab phone numbers from the top of one shared stack of index cards, disaster strikes the moment one call discovers 50 extension numbers for the same small clinic: all 50 cards go onto the stack together, and 50 callers dial that clinic in the same second! Even if callers check a rulebook first, 49 of them end up sitting on their hands waiting for that clinic's 1-second timer to clear while thousands of other businesses sit uncalled underneath.

The naive crawler design — a shared breadth-first queue polled by N worker threads with a global or Redis rate check — fails because it causes same-host bursts (accidental denial-of-service when one page yields hundreds of same-domain links) and head-of-line blocking (workers stalling or spinning on throttled domains instead of fetching ready domains).

Our production design solves both problems by organizing work by host rather than in one flat queue: 1. Assign one owner per host: Hashing each URL's politeness key (its registered domain from the Public Suffix List, or its API key) routes all URLs for a host to a single crawler shard, so one local scheduler enforces that host's rate and concurrency with zero cross-machine locks. 2. Per-host queues + a Ready Min-Heap: Each host keeps its own waiting line of URLs, and puts a single (next_allowed_time, host) ticket into a min-heap (a priority queue that keeps the earliest timestamp on top). Async I/O workers only ever pop hosts whose cooldown has already passed — zero sleeping workers, zero bursts. 3. Adaptive pacing (AIMD) + circuit breakers: Each host starts gently, inches up slowly on healthy responses up to a strict max_rate ceiling, immediately halves its rate on 429/503/timeouts or doubling latency, and opens a circuit breaker (a temporary pause switch) if a host goes down.

Tiny concrete walkthrough: Suppose default politeness is 1 req/s (max_in_flight = 2), and our shard holds URLs for oak.dev (/o1, /o2) and maple.io (/m1, /m2) at t = 0.0 s: - t = 0.0 s: Min-heap has [(0.0, oak.dev), (0.0, maple.io)]. Worker slot 1 pops oak.dev -> /o1, sets oak.next_allowed = 1.0 s, and pushes (1.0, oak.dev) back into the heap (even if /o1 discovers 500 more oak.dev links, oak.dev still cannot fire again until 1.0 s!). Worker slot 2 pops maple.io -> /m1 and sets maple.next_allowed = 1.0 s. - t = 0.3 s: oak.dev returns 429 Too Many Requests with header Retry-After: 30. Our adaptive controller halves oak.rate to 0.5 req/s, sets oak.next_allowed = 30.3 s, and puts /o1 back for retry. - t = 1.0 s: maple.io (1.0 s <= 1.0 s) pops and fetches /m2 right on schedule! When (1.0, oak.dev) pops, the scheduler sees oak.next_allowed == 30.3 s > 1.0 s, lazily re-pushes (30.3, oak.dev), and immediately moves on to other healthy hosts with zero blocked slots.

Key trade-offs

  • Per-host queues + ready min-heap vs. one shared FIFO queue. Maintaining a separate disk-backed queue per host plus an in-memory min-heap of ready times eliminates both same-host request bursts and head-of-line worker blocking in O(log H) time per fetch, trading off higher storage structure complexity than a single flat queue.
  • Host-sharded exclusive ownership vs. centralized distributed rate limiting. Routing hash(politeness_key) % 64 so one node owns a host's entire queue and rate state avoids 2,000 Redis network round trips per second and prevents distributed race conditions. The trade-off is managing shard ownership leases with fencing tokens (monotonically increasing lease numbers that block stale writers) and using batch token leasing only for cross-host shared-IP caps.
  • Both rate spacing AND max_in_flight vs. rate limiting alone. Enforcing 1 / rate spacing prevents micro-bursts within a 1-second window, while adding max_in_flight = 2 protects struggling servers whose response latency spikes to 15 seconds (where 1 req/s alone would pile up 15 concurrent requests), giving up burstiness that permissive APIs might tolerate in exchange for never tipping over a slow upstream.
  • AIMD adaptive pacing under hard caps vs. static configured rates. AIMD (Additive Increase, Multiplicative Decrease) automatically backs off on 429s, 502/503/504s, timeouts, and rising latency while recovering smoothly once the upstream stabilizes, bounded strictly below host_policy.max_rate so adaptation can never violate a configured ceiling.
  • Async event-loop I/O + separate CPU parser processes vs. thread-per-request. Coroutine-based async I/O holds 4,000 open sockets across 16 nodes in megabytes of RAM, while isolating HTML parsing in a separate process pool behind a bounded queue applies clean backpressure if CPU saturates instead of stalling event-loop timers.
  • Exact 128-bit in-memory URL fingerprints vs. a Bloom filter. At 1 billion URLs across 16 nodes, exact 128-bit hashes take just ~1 GB of RAM per node — giving zero false positives and zero disk reads on repeat links. A Bloom filter (a compact probabilistic bit array that can yield false positives) only pays off at ~10B+ URLs in front of an on-disk set, because standalone Bloom filters silently skip ~1% of valid URLs and still require disk checks whenever a page links to already-seen navigation URLs.
  • At-least-once leases with idempotent steps vs. distributed transactions. Expiring 60-second worker leases plus content-addressed storage (content_hash saved before parsing) recover cleanly from worker crashes with rare duplicate GETs and zero lost URLs.

Common mistakes

  • Enforcing only a global rate limit (e.g., 2,000 req/s cluster-wide), which still lets all 2,000 requests/s slam a single website when a seed page yields thousands of same-host links.
  • Having worker threads sleep() when they pop a rate-limited URL, tying up the entire worker pool on a handful of throttled domains while thousands of ready domains sit starved behind them.
  • Retrying failed requests immediately or on fixed intervals (1s, 2s, 4s without jitter), causing synchronized retry waves (thundering herds) that hammer an overloaded upstream right as it tries to recover, or letting retries bypass the host's normal rate queue.
  • Misinterpreting 429 Too Many Requests when fetching /robots.txt as "no robots.txt rules", because naive code checks if 400 <= status < 500: allow_all() and unleashes full-speed crawling onto a server actively begging us to stop!
  • Keying politeness by raw subdomain (a.site.com) or forgetting shared hosting IPs, either multiplying traffic across subdomains owned by one backend or hitting one cheap shared-hosting IP at 1,000 req/s across 1,000 tiny domains.
  • Omitting a hard total_timeout and max_body_bytes cap, allowing slow-trickling servers or multi-gigabyte media files to exhaust connection slots indefinitely.
  • Deduplicating raw URL strings without canonicalization, fetching http://Example.com:80/page?utm_source=x#top and http://example.com/page as separate pages, or placing no max_depth / max_pages_per_host guard against infinite calendar and session-ID spider traps.
  • Forgetting persistence on Retry-After and emergency shutoffs, so a crashed worker restarts at default speed and immediately violates a 1-hour Retry-After ban, or operators have no < 5 s kill switch when a site owner complains.

Follow-up questions

  • Suppose a third-party API enforces a shared quota of 1,000 requests per minute per API key across your entire worker fleet—how do you enforce that limit? Set politeness_key = (api_provider, api_key_id) so by default all requests using that API key route to a single owning shard, which paces them locally in memory at ~15 req/s (900/min, keeping a 10% safety buffer for clock skew). If response payloads or downstream work for that single key exceed what one node can handle, keep a centralized atomic token bucket in Redis (via a short Lua script) and have worker nodes lease small batches of tokens (say 15 tokens valid for 2 seconds) rather than calling Redis on every HTTP request, bounding both Redis load and crash waste. Finally, parse the provider's X-RateLimit-Remaining and X-RateLimit-Reset headers on every response to adjust pacing dynamically before ever hitting a 429.
  • How would you adapt the architecture to periodically revisit previously crawled URLs so a search index stays fresh? Add a next_crawl_at timestamp and refresh_interval_s to every url_record, adapting the interval via change frequency: if SHA256(body) changed since the previous fetch, halve refresh_interval_s down to a floor (e.g., 1 hour for breaking-news homepages); if unchanged, double it up to a ceiling (e.g., 30 days for static archives). A background scan on a time-ordered index feeds due URLs back into their host's frontier queue, reserving at most 50% of each host's politeness budget for re-crawls so newly discovered links never starve. On every re-crawl, send HTTP conditional headers (If-None-Match with the saved ETag and If-Modified-Since) so unchanged pages return lightweight 304 Not Modified headers with zero body bandwidth and zero HTML parsing cost.
  • What mechanisms detect and contain infinite spider traps, such as dynamically generated calendars or combinatorial filter URLs? Combine hard structural guardrails with live content-similarity feedback. Structurally, cap max_depth, max_pages_per_host, maximum URL length (e.g., 2,048 chars), query-parameter count, and repeated path segments (blocking URLs like /shop/item/shop/item/shop/item). Dynamically, compute a 64-bit SimHash fingerprint of every parsed page's text per host: if a host produces hundreds of distinct URLs whose SimHash values are identical or near-identical (within 3 bits), automatically quarantine that URL path/query pattern on the host and alert operators via the "new URLs discovered per unique content hash" metric.

Follow-up questions

Similar questions

More Nooks interview questions

All 2 Nooks questions →