Distributed Web Crawler Across Heterogeneous Worker Nodes

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a distributed web-crawling platform that begins from seed links, downloads allowed web documents, persists raw page bodies alongside versioned fetch metadata, parses outbound hyperlinks, and schedules eligible discoveries as well as periodic refreshes. Network fetching runs across an uneven pool of roughly 1,000 worker nodes whose CPU cores, link speeds, and uptime stability vary dramatically.

Begin by pinning down crawl boundaries (broad public internet versus a curated domain allowlist such as a reference knowledge base), staleness tolerances for archived pages, and expected corpus scale, then back up your component choices with capacity arithmetic for throughput, ingress/egress bandwidth, and raw versus compressed storage across the 1,000-node pool.

Scope & Expectations

  • URL identity, scope & partitioned frontier: Specify versioned URL normalization, allowed protocols/MIME types/redirects, robots.txt and per-site rate politeness, frontier lifecycle states, and a sharding/prioritization model that deduplicates concurrent link discoveries atomically without head-of-line stalls behind slow domains.
  • Uneven-fleet coordination & delivery guarantees: Detail capability-aware task dispatch, lease timeouts and mid-fetch crash recovery across unreliable nodes, downstream write idempotency (contrasting network fetch attempts with storage side effects), and end-to-end backpressure from parsing and storage.
  • Fetch/parse pipeline & concrete storage schemas: Walk through safe HTTP downloading (timeouts, payload caps, relative link resolution against the post-redirect URL, identical-byte and fuzzy-text deduplication, crawl traps, transient vs. terminal error handling, and dead-lettering) plus concrete schemas for the frontier, body archives, multi-version metadata, and link graph.
  • Freshness, operations, legal guardrails & control APIs: Cover change-aware recrawls with conditional requests, health telemetry and rule/frontier recovery procedures, safety controls (identifying User-Agent, hard QPS/bandwidth caps, residency/takedowns, multi-level kill switches, off-limits auth/checkout/form paths), and idempotent external APIs for campaigns, status, results, and dead-letter replay.

Step-by-step walkthrough

  1. Clarify crawl scope, freshness tiers, and scale

    Before drawing boxes, pin down three questions with the interviewer because every component depends on them:

    • Crawl scope: Is the system indexing the broad public internet or a curated domain allowlist (for example, a reference knowledge base)? We model both as campaigns—isolated crawl configurations carrying seed links, host allowlists/blocklists, maximum hop depth, and page budgets. Note: if a curated target is a single large reference wiki, always ask first whether it publishes bulk archives or a change stream; ingesting an official archive is vastly cheaper for both sides because polite rate limits make crawling a single multi-million-page domain slow.
    • Freshness targets: How stale can stored copies become? Assume three priority tiers: the top 1% most important pages refreshed within 1 day, the next 10% within 7 days, and the remaining 89% within 30 days.
    • Scale and worker fleet: Assume an active in-scope corpus starting at 300 million HTML pages, plus 10 million newly discovered in-scope pages per day (out of roughly 3 billion total discovered candidate URLs). Fetching runs across roughly 1,000 uneven worker nodes ranging from fast data-center hosts to flaky residential machines. Content is logged-out HTML (text/html, application/xhtml+xml) with no JavaScript execution in v1.

    Functional requirements

    • Start from seed URLs, fetch permitted pages, store an immutable body snapshot plus fetch metadata for every attempt, extract links, enqueue eligible discoveries, and recrawl stored pages on schedule.
    • Expose operator APIs to create campaigns, enqueue URLs, inspect status, stream results and outlinks, replay failed jobs, and trigger emergency stops.

    Non-functional requirements

    • Politeness as a hard rule: Strictly obey robots.txt directives and per-host rate limits without overloading target sites.
    • Correctness under retries and crashes: Maintain exactly one logical record per canonical URL, never lose discovered work, and never let retries overwrite historical fetch evidence.
    • Heterogeneous fault tolerance: Absorb workers with 25x throughput gaps or multi-hour disconnects without stalling hosts.
    • Fast stoppability: Enforce global, campaign, and per-domain kill switches within seconds.
  2. Estimate throughput, bandwidth, and storage

    Sizing the numbers first reveals where the real bottlenecks hide—and proves why a growing queue is not the same thing as useful progress.

    1. Crawl throughput demand
       Daily recrawls    3M/1d + 30M/7d + 267M/30d = 3.0M + 4.3M + 8.9M = ~16.2M/day (~190 pages/s)
       New pages         10M/day                                        = ~115 pages/s
       Protocol overhead +30% (robots.txt, redirects, transient retries)= ~400 pages/s average
       Provisioned peak  2.5x headroom for bursts and outage catch-up   = ~1,000 pages/s
    
    2. Worker fleet ceiling (Little's Law: throughput = concurrent_fetches / mean_fetch_time)
       Tier A: 100 data-center nodes  x 100 concurrent fetches           = 10,000 slots
       Tier B: 400 cloud/office nodes x  20 concurrent fetches           =  8,000 slots
       Tier C: 500 residential nodes  x   4 slots x 60% online           =  1,200 slots
       Total concurrency = ~19,200 slots; at ~2 s mean fetch time        = ~9,600 pages/s ceiling
       Peak 1,000 pages/s x 2 s = 2,000 active slots (~10% of fleet capacity)
    
    3. Host politeness constraint
       1 connection/host with ~1 s response + 1 s politeness delay       = ~0.5 pages/s per host
       400 pages/s average requires >= 800 distinct hosts ready at every instant
       One 6M-page encyclopedia host at 0.5 pages/s takes 6M / 43,200/d  = ~139 days alone!
    
    4. Network bandwidth (assume ~100 KB raw HTML; servers often send ~25-30 KB gzipped,
       but we budget 100 KB/fetch on the wire as a safe upper bound, and ~25 KB after zstd)
       Inbound download  400/s x 100 KB = 40 MB/s (~320 Mbps avg, ~800 Mbps peak; ~0.4 Mbps/worker)
       Worker egress     outbound HTTP GET headers (~1 KB x 400/s = ~3.2 Mbps)
                         + compressed snapshot uploads to central object storage
                           (<= 400/s x 25 KB = 10 MB/s = ~80 Mbps avg, ~200 Mbps peak)
    
    5. Daily and steady-state storage (raw vs. compressed, plus year-1 growth headroom)
       Total fetches     400/s x 86,400 s = ~34.6M fetches/day
       Changed snapshots ~60% change content (~20.7M/day; remaining 40% are HTTP 304 or same hash)
                         Daily snapshots: ~2.07 TB/day raw  | ~0.52 TB/day zstd (~190 TB/yr all versions)
       300M-page corpus  Latest snapshot: ~30 TB raw        | ~7.5 TB zstd (scales linearly as corpus grows)
       Fetch metadata    34.6M/day x ~500 B                 = ~17 GB/day (~6.2 TB/year)
       Link extraction   20.7M parsed/day x ~50 links/page  = ~1.04B link checks/day (~12,000 checks/s)
       Frontier state    ~3B known URLs x ~150 B = ~450 GB (+ 48 GB for 16-byte URL IDs) + index/graph
    

    What these numbers tell us: - Little's Law (a queueing formula stating that average concurrent work equals arrival rate multiplied by average duration) shows our 1,000 workers could fetch ~9,600 pages/s—nearly 10x our peak target. The worker fleet is not the bottleneck. - The real bottlenecks are per-host politeness, 12,000 link deduplication checks/s hitting the frontier, and small-object storage overhead (20.7 million 25 KB snapshots/day would rack up massive per-object metadata fees unless packed into larger archive segments).

  3. High-level architecture and end-to-end URL flow

    Before diving into individual components, trace how a URL moves through the system from discovery to storage.

      Operators / Campaign Owners
                   |
            [ Crawl API ]  (campaigns, seed enqueue, status, results, DLQ, kill switches)
                   |
                   v
      [ Canonicalizer + Scope Filter ] ---> [ Link Router: hash(politeness_key) mod 1024 ]
                   ^                                           |
                   |                       +-------------------+-------------------+
                   |                       v                   v                   v
                   |             [ Frontier Part. 0 ]  [ Frontier ... ]  [ Frontier Part. 1023 ]
                   |               single epoch-fenced writer, per-host queues,
                   |               ready-host min-heap, robots cache, lease reaper
                   |                       ^             |
                   |         ack/heartbeat |             | pull lease batches
                   |                       |             v
                   |               [ Stateless Lease Gateway ] <--- [ Backpressure Controller ]
                   |                       ^             |
                   |                       |             v
                   |        ~1,000 Workers (Tiers A / B / C): DNS guard, fetch, hash, zstd
                   |                       |             |
                   |                       |             +---> [ Regional Object Store ]
                   |                       v                   (staging blobs -> 1 GB WARC segments)
                   |               [ Fetch Log (Kafka) ] ---> [ Fetch Metadata Store ]
                   |                       |
                   |                       v
                   +--- outlinks --- [ Sandboxed Parse Tier ] ---> [ Near-Dup Index & Link Graph ]
    

    Life of one URL: 1. A seed or extracted link passes through the canonicalizer (which standardizes URL syntax) and scope filter, then routes by its domain's politeness key to one of 1,024 durable frontier partitions. 2. When the URL is due and its host's politeness timer has elapsed, the owning frontier partition issues a time-limited lease (a temporary work reservation) through the stateless lease gateway to a worker requesting work. 3. The worker verifies robots.txt rules shipped with the lease, resolves DNS safely, fetches the HTML, uploads the compressed body to staging object storage under its SHA-256 content hash, and sends a completion report. 4. The frontier partition verifies the lease is still active, logs the immutable fetch record, updates scheduling state, and advances the host's next-allowed timestamp. 5. A central sandboxed parse tier reads new snapshots, computes duplicate fingerprints, writes link-graph edges, and feeds newly extracted links back to Step 1.

  4. Define URL identity, canonicalization, and crawl scope

    URL canonicalization is the deterministic process of rewriting equivalent URL strings into one standard form so the crawler does not fetch the same page under ten cosmetic disguises. Normalization walks a sharp tightrope: overly broad rules irreversibly collapse separate documents into one key, whereas overly lax rules let cosmetic URL variants flood the queue.

    Conservative canonicalization rules (canon_version = v3, recorded on every record): 1. Parse with a browser-grade WHATWG URL parser rather than fragile regular expressions. 2. Scheme & port: Lowercase scheme (http or https only); strip default ports (:80 for HTTP, :443 for HTTPS). 3. Host: Lowercase, convert internationalized domain names to ASCII Punycode (the DNS encoding for non-ASCII domain characters), and strip any trailing dot. 4. Path: Resolve . and .. segments; normalize percent-encoding case (%2f -> %2F) and decode unreserved characters (A-Z a-z 0-9 - . _ ~); preserve path letter case and trailing slashes (/Wiki/Apple and /wiki/apple/ can be distinct pages on Linux servers); replace an empty path with /. 5. Fragment: Strip #section fragments completely (browsers never send them to servers). 6. Query string: Preserve parameter order (some backends treat ?a=1&b=2 differently from ?b=2&a=1), strip known tracking parameters on a versioned allow-to-drop list (utm_*, gclid, fbclid), and drop a bare trailing ?.

    Raw link:       HTTPS://Example.COM:443/docs/../Guide?a=1&utm_source=x#intro
    Canonical (v3): https://example.com/Guide?a=1
    

    Evidence-based aliasing instead of blind merging: - Never blindly merge http with https, or www.example.com with example.com. Instead, merge them only when crawl evidence proves equivalence—such as an HTTP 301/308 permanent redirect, a <link rel="canonical"> tag, or repeated identical body hashes—recording an explicit alias edge with its evidence source. Always save the raw discovered URL string on the link edge so future rule upgrades can re-evaluate history.

    128-bit stable url_id: - Set url_id = first_128_bits(SHA256(canonical_url)). Why 16 bytes instead of a 64-bit integer? By the birthday paradox, among n = 3 billion URLs, a b-bit hash produces roughly n^2 / 2^(b+1) expected collisions: for b = 64, that is (9 x 10^18) / (3.69 x 10^19) ≈ 0.24 (roughly a 22% chance of silently merging two unrelated web pages!). For b = 128, expected collisions drop to ~10^-20. Store canon_version alongside url_id rather than hashing it in, so unchanged URLs keep the same ID across rule versions.

    Scope, redirects, and robots.txt (RFC 9309): - Eligibility checks (in order): Allowed scheme -> host passes campaign allowlist and global blocklist -> URL length <= 2,048 chars, <= 16 path segments, no segment repeated > 3 times -> hop depth from seed <= max_depth -> host page budget remaining. - Redirects: Follow up to 5 hops inline only when scheme://host:port stays identical (so the lease's robots.txt rules and politeness slot still apply). Any cross-origin redirect (even http -> https) ends the current fetch as 3xx and enqueues the target URL through the normal scope, robots.txt, and politeness pipeline. - robots.txt and politeness: Cache one robots.txt per origin (scheme://host:port) for up to 24 hours, parsing at least 500 KiB per RFC 9309. HTTP 4xx means unrestricted crawl; 5xx or network timeout means full disallow until robots.txt can be fetched cleanly. Default politeness enforces 1 active connection per host and a >= 1 s adaptive gap between requests (honoring Crawl-delay and Retry-After, doubling delay on 429/503).

  5. Partition the durable frontier for politeness and atomic deduplication

    To enforce per-site cooldowns across 12,000 link discoveries/s with zero central locking, shard the frontier by the exact unit we rate-limit.

    • Politeness key (eTLD+1): Group hosts by their registrable domain (eTLD+1, such as example.com) using the Public Suffix List—a public catalog of domain suffixes including shared hosting platforms like github.io, ensuring alice.github.io and bob.github.io get separate politeness keys while www.example.com and shop.example.com share one budget.
    • Single-writer partitions: Route each URL to partition = hash(politeness_key) mod 1024, hosted across ~16 replicated frontier servers. Each partition has one active writer guarded by an epoch number (a monotonically increasing term counter that causes storage to reject stale writes from an old leader after failover). Because every URL for example.com lands on the same single writer, host.next_allowed_at is a fast local check in memory—zero distributed locks! (A loose per-IP cap of ~10 concurrent connections protects small shared-hosting servers without throttling CDNs like Cloudflare.)

    Frontier lifecycle states and two-level scheduling (no head-of-line blocking):

      DISCOVERED ---> SCHEDULED ---> LEASED ---> COMPLETED --(recrawl due)--> SCHEDULED
          |               ^            |
      (disallowed)        +--- RETRYABLE --(max retries / poison)--> DEAD (DLQ)
          v
       EXCLUDED
    
      Level 1 (Across hosts):  ready/{next_allowed_at_be64}/{politeness_key}
         -> Min-heap of hosts whose politeness cooldown has passed.
      Level 2 (Within a host): queue/{politeness_key}/{prio_u8}/{next_fetch_at_be64}/{url_id}
         -> Priority classes: 0 = seeds/operator, 1 = urgent recrawls, 2 = due retries,
                              3 = new discoveries, 4 = routine recrawls.
    
    • Avoiding head-of-line blocking (when one slow or massive host stalls unrelated hosts behind it): Level 1 pops the next ready host, pops one URL from Level 2 for that host, and removes that host from ready/ until the fetch finishes (or lease expires) plus delay_ms. Whether a host has 10 URLs or 50 million URLs queued, it gets at most ~0.5 fetches/s while thousands of other hosts flow unimpeded.

    Atomic deduplication under concurrent link discovery: When 500 pages link to https://example.com/about simultaneously, every worker's parser hashes "example.com" to the exact same partition writer, which executes atomically: 1. Check an in-memory Bloom filter (a compact bit array that answers "definitely never seen" or "maybe seen" with zero false negatives). 2. If "definitely never seen", write url/{url_id} via conditional put_if_absent and set the Bloom bits. If "maybe seen", check url/{url_id} on disk: if absent (a Bloom false positive), insert it; if already present, simply log the link-graph edge and drop the duplicate schedule!

  6. Coordinate 1,000 heterogeneous workers with pull leases

    How do we distribute work across 100 fast servers, 400 cloud/office machines, and 500 residential devices that randomly drop offline?

    • Pull leases, never push host assignments: Workers call POST /internal/leases (worker_id, free_slots, tier, max_bytes) through a stateless lease gateway whenever they have spare capacity. Hashing hosts directly onto workers ("push") fails here because a residential laptop going to sleep would stall its assigned websites, ignore the 25x capability gap between Tier A and Tier C, and put politeness enforcement on untrusted machines.
    • Capability-weighted small batches: The gateway tracks each worker's rolling throughput and failure rate, handing out batches sized to free_slots + ~5 seconds of work (1–5 URLs for Tier C). Why keep batches to seconds rather than minutes? Because a leased URL holds its host's only politeness slot—sitting in a worker's local queue for 60 seconds wastes 60 seconds of that website's crawl budget! Tier C workers are never assigned fragile hosts (strict Crawl-delay or recent 429s) or large downloads.

    Lease timing, monotonic clocks, and crash recovery: - Each lease carries (lease_id, fetch_id, url_id, partition_epoch, attempt, lease_ttl_ms) with lease_ttl_ms = clamp(3 * expected_fetch_ms, 90_000, 300_000)—always longer than the 60 s hard fetch timeout. Active workers renew leases via 15 s heartbeats. - Why relative TTLs instead of wall-clock timestamps: Residential devices often have skewed system clocks. Workers start a monotonic boot-clock timer when a lease arrives and refuse to start a fetch unless lease_ttl_ms - elapsed_ms > 60_000 (and drop all local leases after any network disconnect or sleep gap). - If a worker vanishes mid-fetch, the partition reaper marks the expired lease RETRYABLE (attempt + 1), keeping the host's politeness slot blocked until expires_at + delay_ms in case the zombie worker is still finishing its HTTP call. Three silent lease expirations quarantine the URL to the dead-letter queue as a suspected poison URL (an input that repeatedly hangs or crashes workers).

    Network fetch delivery vs. storage side effects: Exactly-once HTTP fetching is impossible: if a worker sends GET /page and loses power 1 ms before receiving the response, nobody can tell whether the remote server processed it. We therefore guarantee at-least-once fetch delivery (bounded by retry limits) paired with idempotent downstream writes (operations where repeating the same write produces the exact same stored state as running it once):

    Downstream write How duplicates become harmless
    Snapshot body Stored in object storage by SHA256(decompressed_bytes); identical bytes overwrite/share one key
    Fetch history row Keyed by (url_id, fetch_id) where fetch_id is assigned once per lease; resending writes identical data
    State transition Conditional on matching current (lease_id, partition_epoch); late completions from expired leases log fetch evidence without altering frontier state
    Extracted outlinks Routed to target partition for conditional put_if_absent(url_id)
    Campaign counters Aggregated from partition state tables rather than blind +1 increments
  7. Fetch, validate, parse, and deduplicate page content

    Safe worker execution path: 1. SSRF and DNS-rebinding defense: Server-Side Request Forgery (SSRF) occurs when a crafted link tricks a crawler into fetching private internal routers or cloud metadata endpoints (169.254.169.254, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10, ::1, fc00::/7, fe80::/10). Workers resolve DNS once via a local cache, verify every returned IP is public, and pin the TCP socket directly to that verified IP (repeating on every redirect hop) so DNS rebinding (swapping a public IP for 192.168.1.1 on a second lookup) cannot scan a corporate VPC or a residential volunteer's home Wi-Fi router. 2. Conditional HTTP & hard resource caps: Send GET only (no cookies), Accept: text/html,application/xhtml+xml, Accept-Encoding: gzip, br, an identifying User-Agent, and conditional request headers (If-None-Match with previous ETag, If-Modified-Since) so unchanged servers return tiny 304 Not Modified responses. Enforce timeouts (10 s connect, 10 s TLS, 30 s first byte, 60 s total, abort if < 1 KB/s for 20 s against tarpits) and abort non-HTML Content-Type headers or bodies exceeding 10 MB either on the wire or after decompression (blocking zip/gzip bombs; mark truncated = true if cut). 3. Upload & report: Compute SHA256(decompressed_body), compress with zstd, PUT to {region}/staging/sha256/{hash} via pre-signed URL (skipped only if blob_index already marks that hash verified), and report completion to the frontier.

    Central sandboxed parsing and relative link resolution: - Parsing runs centrally inside CPU/memory-capped containers (2 s CPU, 256 MB RAM, <= 10,000 links/page) so hostile HTML cannot exploit volunteer devices and parser updates apply uniformly. - Crucial link-resolution rule: Resolve relative <a href> links against <base href> if present, otherwise against the final URL after redirects—never the initially requested URL—before canonicalizing:

    Requested URL:  https://example.com/promo          --301-->  https://example.com/2026/spring/index.html
    Link in HTML:   <a href="terms.html">
    Wrong (vs req): https://example.com/terms.html              (404!)
    Right (vs fin): https://example.com/2026/spring/terms.html  (correct target)
    

    Exact vs. near-duplicate detection, retries, and crawl traps: - Exact duplicates share the same SHA-256 blob automatically. For near-duplicates (pages differing only by timestamps, ads, or session banners), compute a 64-bit SimHash—a locality-sensitive fingerprint over word 3-grams where nearly identical documents differ in <= 3 bits. Splitting 64 bits into four 16-bit lookup tables guarantees by the pigeonhole principle that any match within 3 bit flips shares at least one exact 16-bit block! Near-duplicates still have outlinks extracted, but join a duplicate cluster with lowered recrawl priority. - Retry rules & dead-letter queue (DLQ) (a holding table for permanently failing items awaiting operator inspection): - Transient (500/502/503/504, 429, timeouts, TCP reset): Exponential backoff per URL (1m, 10m, 1h, 6h, 24h + jitter); 429/503 also back off the host; move to DLQ after 5 failures. - Terminal URL (400, 401, 403, 404, 410, 451, disallowed Content-Type, > 5 redirects): Mark COMPLETED with status (401/403 never retried; 404/410 confirmed twice 24 h apart before marking removed). - Poison (>= 3 silent lease expiries or >= 3 parser crashes): Quarantine immediately to DLQ while retaining the raw snapshot for debugging. - Crawl-trap defenses (against infinite calendars /calendar/2099/12, facet permutations, and /a/b/a/b loops): Path length/depth/repeating-segment filters, max distinct query strings per path (e.g., 1,000), per-host campaign page budgets, and near-duplicate spike alerts.

  8. Design concrete storage schemas separating evidence from state

    Keep mutable scheduling state (which updates on every lease, heartbeat, and retry) physically separate from append-only fetch evidence so a retried job can never overwrite what was observed earlier.

    1. Frontier Store (embedded RocksDB per partition, replicated across 3 nodes)
       url/{url_id} -> { canonical_url, canon_version, politeness_key, state, prio_u8,
                         next_fetch_at_ms, attempts, lease_id, lease_expires_at_ms,
                         depth, campaign_ids[], discovered_from: (src_url_id, fetch_id), importance }
       queue/{politeness_key}/{prio_u8}/{next_fetch_at_be64}/{url_id} -> ""
       ready/{next_allowed_at_be64}/{politeness_key}                  -> ""
       host/{politeness_key} -> { delay_ms, next_allowed_at_ms, active_leases, error_streak, budget_left }
       robots/{scheme}://{host}:{port} -> { version, fetched_at, expires_at, status, rules, body_hash }
       * Note: prio_u8 (1 byte) and timestamps (*_be64, 8-byte big-endian unsigned ints) ensure
         RocksDB's byte-lexicographical range scans sort strictly in numerical time order!
    
    2. Fetch Log & Metadata Store (Kafka stream -> wide-column store like Cassandra/ScyllaDB)
       fetches PK: (url_id, fetch_id DESC)    -- fetch_id is time-ordered, bound 1:1 to lease_id
         { lease_id, worker_id, requested_url, final_url, redirect_chain[], http_status,
           error_class, content_type, byte_len, content_hash, simhash64, etag, last_modified,
           started_at, duration_ms, robots_version, canon_version, truncated }
    
    3. Snapshot Object Store (immutable S3/GCS, isolated per data-residency region)
       {region}/staging/sha256/{content_hash}        -- zstd body uploaded by worker
       {region}/segments/{yyyy-mm-dd}/{seg}.warc.zst -- ~1 GB WARC archive files packed hourly
       blob_index PK: (region, content_hash) -> { seg, offset, length, verified_at }
    
    4. Per-URL Metadata & Alias Table (wide-column, PK: url_id)
       { canonical_url, canon_version, raw_samples[], latest_fetch_id, latest_content_hash,
         change_stats: { visits, changes, lambda_per_day }, importance, simhash_cluster_id,
         aliases: [ { other_url_id, evidence: "301" | "rel=canonical" | "canon_v4", observed_at } ] }
    
    5. Link Graph & Dead-Letter Queue
       outlinks: Kafka stream + daily Parquet files keyed by (src_url_id, fetch_id) -> dst_url_ids[];
                 daily batch job inverts outlinks into inlinks + PageRank/importance scores.
       dlq PK: (campaign_id, error_class, url_id) -> { attempts, last_errors[], last_lease_ids[], since }
    

    Why each store fits—and why untrusted hashes are re-verified: - RocksDB excels at single-writer local transactions and ordered prefix scans (ready/ and queue/). Note that www.example.com and blog.example.com have separate robots/ keys but live inside the same example.com partition! - WARC (Web ARChive) packing solves the 20.7M-tiny-files/day problem by compacting 25 KB staging blobs into ~1 GB sequential archive files. Crucially, because Tier C devices are untrusted, the hourly compactor decompresses and re-computes SHA-256 before marking verified_at in blob_index—preventing a buggy or malicious device from poisoning a popular hash!

  9. Manage recrawls, backpressure, safety, and operations

    Adaptive recrawl scheduling: Each URL tracks observed changes (changes / visits) to estimate its daily change rate lambda, combined with an importance score (tier + inlinks). Modeling edits as random independent arrivals, the probability a page changed after T days is 1 - exp(-lambda * T). Setting that equal to target staleness tolerance p (tighter p for Tier 1 pages) yields the next interval:

    T = clamp( -ln(1 - p) / lambda,  T_min, T_max )
    Example: p = 0.5, lambda = 0.1 changes/day  ->  T = 0.693 / 0.1 = ~6.9 days
    
    • On 304 Not Modified or identical content_hash: advance metadata without storing a duplicate blob and lengthen T. On two consecutive 404/410s 24 h apart: mark removed, probe monthly x3, then retire. On 301/308: record alias evidence and shift recrawl budget to the target URL.

    End-to-end backpressure (slowing producers when consumers lag): A central token-bucket controller adjusts the lease gateway's global issuance rate every few seconds based on parse-queue age, object-store PUT error rate/latency, wide-column write latency, and frontier link-ingest lag. Crossing any threshold multiplies issuance by 0.7 (multiplicative decrease); healthy signals recover at +2%/min. If frontier storage hits capacity, low-priority discoveries are shed with explicit counters rather than stalling parsers.

    Metrics, alerts, and operational runbooks: - Useful progress vs. raw queue growth: Alert on fresh tier coverage (>= 95% of daily-tier pages refreshed within 24 h; p99 due-but-unfetched lateness < 6 h) and new unique content vs. discovery rate (if the frontier balloons while unique hashes flatten, a host hit a crawl trap!). Also alert on per-campaign 429 rate > 2%, Tier C lease-expiry rate > 30%, parse lag > 15 min, and storage error rate > 0.5%. - Rule migrations & frontier rebuilds: Shadow-test canon_v4 offline against saved raw links first; roll out partition by partition writing non-destructive alias pointers rather than mutating old history. Because the frontier is derived state, total loss is recoverable by replaying seeds + outlinks + fetches into fresh partitions and bumping the partition epoch.

    Safety and legal controls: - Transparent identity & dual ceilings: Send User-Agent: ExampleBot/1.0 (+https://example.com/bot; bot-ops@example.com). Enforce global, campaign, per-host, and per-IP QPS/bandwidth caps both at the authoritative frontier partition and via local worker limiters. - Data residency, takedowns, and off-limits pages: Pin EU/regional campaigns to regional workers and regional object-store buckets. Process takedowns by blocklisting the domain/URL, marking frontier state EXCLUDED, immediately deleting the blob_index pointer for any content_hash unreferenced by other URLs (checked via an exact (content_hash, url_id, fetch_id) index, never a drift-prone counter), and rewriting the immutable WARC segment on next compaction. Never send POST, cookies, credentials, or requests matching side-effect patterns (/logout, /checkout, /cart, /delete, /unsubscribe). - Kill switches (< 10 s stop): Backed by a strongly consistent config store; the lease gateway refreshes every 1 s (halting new leases immediately) and workers poll every 5 s to abort matching in-flight requests by global, campaign, or domain scope.

  10. Expose idempotent APIs and summarize key trade-offs

    Every mutating endpoint accepts an Idempotency-Key header—a client-generated unique request token cached server-side for 24 hours so network retries return the exact original response without duplicating campaigns, URL enqueues, or DLQ replays.

    POST /v1/campaigns                              Header: Idempotency-Key: <uuid>
      { name, seeds[], scope: { allow_hosts[], deny_hosts[], max_depth, max_pages },
        limits: { max_pages_per_s, per_host_pages_per_s }, recrawl_policy, region }
      -> 201 { campaign_id, status: "active" }
    
    POST /v1/campaigns/{cid}/urls                   Header: Idempotency-Key: <uuid>
      { urls: [ { url, priority: "high"|"normal", max_depth, not_before } ] }  (<= 10,000/call)
      -> 200 { results: [ { url, url_id, outcome: "added"|"already_known"|"out_of_scope"|"invalid" } ] }
    
    GET  /v1/urls/{url_id}       (or GET /v1/urls?url=<encoded>, canonicalized server-side)
      -> { url_id, canonical_url, canon_version, state, next_fetch_at, attempts,
           last_fetch: { fetch_id, http_status, fetched_at, content_hash, snapshot_url } }
    GET  /v1/urls/{url_id}/fetches?cursor=...       -> paginated fetch history, newest first
    GET  /v1/snapshots/{content_hash}               -> 302 redirect to short-lived signed blob URL
    GET  /v1/campaigns/{cid}/status                 -> { counts_by_state, pages_per_s, tier_lateness_p99 }
    GET  /v1/campaigns/{cid}/outlinks?after=<cur>   -> ordered stream of extracted (src, dst) links
    GET  /v1/dlq?campaign_id=...&error_class=...    -> inspect dead-lettered URLs + failure evidence
    POST /v1/dlq/replay                             Header: Idempotency-Key: <uuid>
      { campaign_id, error_class | url_ids[], reason } -> 200 { replay_id, moved_count }
    POST /v1/kill-switches
      { scope: "global" | "campaign" | "domain", target, reason } -> 200 { switch_id, active_at }
    

    Summary of architectural trade-offs: - Conservative canonicalization + evidence-based aliases: Accepts occasional extra fetches before a redirect/rel=canonical is seen, in exchange for zero irreversible merges of distinct pages. - Domain-partitioned single-writer frontier: Turns host politeness and link deduplication into fast local operations with no global lock, trading off epoch-fenced leader management and hot-partition isolation for giant domains. - Pull-based capability-weighted leases: Naturally adapts to slow or vanishing devices without stalling hosts, at the cost of running a lease gateway and expiry reaper. - At-least-once HTTP fetches + idempotent storage separated from workflow state: Respects network reality while ensuring retries never corrupt history or double-schedule links, trading storage compaction overhead for auditability and full frontier rebuildability.

Intuition & how it works

Imagine coordinating 1,000 volunteer researchers—some working on fast university workstations, others on flaky home Wi-Fi that drops every afternoon—to photocopy millions of articles across thousands of independent libraries, where every library enforces a strict rule: "at most one visitor from your team at our front desk per second." Instead of letting volunteers scramble over one giant checklist or call libraries uncoordinated, you assign each library's front-desk timer to one dedicated dispatcher desk (a frontier partition), hand out short time-stamped claim tickets called leases sized to each volunteer's speed whenever they ask for work, and file returned photocopies in a permanent archive indexed by content fingerprint.

Why do simpler designs fall apart? Putting all discovered URLs into a single shared first-in-first-out queue lets one massive or sluggish website stall thousands of fast websites waiting behind it, while sharding the queue by URL hash scatters example.com across every server so nobody can enforce its 1-request-per-second politeness limit (the maximum request rate a crawler imposes on itself per site) without a slow global lock. Worse, pushing fixed website assignments onto 1,000 unequal devices freezes entire domains whenever residential machines disconnect, and updating page rows in place lets late retries overwrite historical evidence.

Let's trace one discovered link through our architecture, including a worker crash mid-fetch:

Step  Event                                      System state & guarantee
----  -----------------------------------------  -------------------------------------------------------
1     Parser finds href="/docs/../Guide?utm_source=ads#top" on https://Example.com:443/home
2     Canonicalizer (v3) normalizes URL          -> "https://example.com/Guide"
                                                    url_id = 128-bit SHA-256 prefix = 0x8a3f...
3     Router hashes politeness key "example.com" -> Partition 412 checks Bloom filter + put_if_absent;
                                                    inserts url/0x8a3f as SCHEDULED (atomic dedupe!)
4     Host timer ready; Tier C worker pulls job  -> Lease L1 (fetch_id=F1, ttl=90s) issued;
                                                    "example.com" removed from ready heap
5     Tier C worker drops offline mid-fetch!     -> After 90s + 1s gap, reaper marks 0x8a3f RETRYABLE;
                                                    host politeness was never violated
6     Tier A worker pulls retry Lease L2 (F2)    -> Fetches 200 OK, uploads zstd body under SHA-256 H9,
                                                    logs immutable fetch F2, marks L2 COMPLETED.
                                                    (If L1 arrives late later, epoch/lease check ignores
                                                    its state change while preserving F1 as evidence!)

Key trade-offs

  • Canonicalization aggressiveness vs. identity preservation. Canonicalization (rewriting equivalent URLs into one standard string) shrinks the crawl queue, but aggressive rules like lowercasing paths or sorting query parameters irreversibly merge distinct pages on case- or order-sensitive servers. Keeping base rules conservative and merging http/https or www variants only via recorded alias evidence (301 redirects, rel="canonical", equal content hashes) costs a few extra initial fetches but never destroys page identity.
  • Politeness key: registrable domain (eTLD+1) vs. exact hostname vs. IP address. Grouping by registrable domain (the site-owner domain from the Public Suffix List, such as example.com, while keeping shared platforms like alice.github.io separate) matches how organizations share backend capacity and keeps subdomains under one polite budget. Per-IP caps catch tiny shared-hosting servers, but strict per-IP throttling would starve thousands of unrelated sites behind one CDN IP, so IP limits stay a loose safety ceiling.
  • Single-writer domain partitions vs. shared database locks. Routing all URLs of a domain to one partition owner guarded by an epoch number (a monotonically increasing leader term that fences off stale writers) turns host rate-limiting and URL deduplication into fast local operations with zero cross-node locks, at the cost of leader-election plumbing and splitting giant domains onto dedicated partitions.
  • Pull-based capability-weighted leases vs. consistent-hashing push. Having workers pull small ~5-second batches adapts automatically to 25x speed gaps and vanishing residential nodes while keeping politeness state on reliable servers. Pushing fixed domains to workers via consistent hashing (mapping keys onto a ring of nodes to minimize movement when nodes join or leave) would improve HTTP connection reuse, but any offline residential device would stall its assigned websites.
  • Short vs. long lease durations. Short leases (time-bounded task claims) recover faster when devices vanish, whereas overly short leases expire while slow fetches are still running and cause duplicate requests. Sizing leases to 3x expected latency (minimum 90 s, exceeding the 60 s fetch timeout) with 15 s heartbeats—and keeping batch sizes to a few seconds so queued URLs do not hold a host's single connection slot idle—balances fast recovery against wasted politeness budget.
  • At-least-once HTTP fetches vs. idempotent side effects. Over a real network, crashing right after sending GET makes "exactly-once HTTP fetching" impossible: skipping retries drops pages, while retrying can hit a server twice. Accepting at-least-once network fetches while making every storage write idempotent (safe to apply multiple times without changing the result beyond the first write) guarantees one logical URL record and clean history.
  • Central sandboxed parsing vs. on-device parsing. Parsing HTML centrally in resource-capped containers ensures one uniform parser version, protects untrusted devices from malicious markup, and allows re-parsing archived snapshots without re-crawling, trading off central CPU and ~80 Mbps of compressed snapshot uploads.
  • Immutable content-addressed WARC archives vs. overwrite-in-place rows. Storing every fetch record and packing unique compressed bodies by SHA-256 into ~1 GB WARC (Web ARChive) segments prevents retries from corrupting history, deduplicates identical pages, and avoids per-object cloud fees on 20M daily snapshots, at the cost of running an hourly background compactor.

Common mistakes

  • Over-normalizing or under-normalizing URLs: Lowercasing URL paths or alphabetizing query parameters merges distinct pages, while leaving #fragments and utm_* tracking tags creates endless duplicate URLs.
  • Using 64-bit URL hashes at multi-billion scale: At 3 billion URLs, 64-bit hashes have roughly a 22% collision probability by the birthday paradox, silently merging unrelated pages; use 128-bit IDs (16 bytes).
  • Partitioning the frontier by hash(url) or using a global rate-limiter lock: Hashing by full URL scatters one website across all partitions so enforcing per-host politeness requires hitting a central bottleneck on every single fetch.
  • Using a single FIFO queue across hosts: One slow server or 50-million-page domain causes head-of-line blocking, starving thousands of fast websites queued behind it.
  • Claiming "exactly-once fetching": Confusing network request delivery (at-least-once) with internal database state updates (idempotent / effectively-once per lease).
  • Treating robots.txt 5xx errors or timeouts as "crawl allowed": RFC 9309 requires treating unreachable/5xx robots.txt responses as temporary full disallow, and caching robots.txt per scheme://host:port rather than once per registrable domain.
  • Resolving relative links against the requested URL instead of the final redirected URL: When https://example.com/promo redirects to https://example.com/2026/promo/index.html, resolving href="faq.html" against /promo produces a broken 404 URL.
  • Following cross-host redirects inline inside the worker: Bypasses scope checks, robots.txt rules, and politeness limits on the destination host.
  • Relying on a Bloom filter alone for deduplication: Because a Bloom filter can produce false positives ("maybe seen" for a brand-new URL), skipping the backing key-value check permanently drops valid pages.
  • Leaving workers vulnerable to SSRF and DNS rebinding, or trusting worker SHA-256 hashes: Failing to block private/loopback IPs (127.0.0.0/8, 192.168.0.0/16, 169.254.169.254) or letting HTTP clients re-resolve DNS exposes corporate and home networks, while skipping compactor re-hashing lets one corrupted worker upload poison a popular content hash forever.

Follow-up questions

  • How do you keep a single massive website with millions of queued URLs from blocking smaller domains? Inside each frontier partition, every host has its own URL queue and its own cooldown timestamp next_allowed_at, and the scheduler pops the next ready host rather than the next raw URL—so a domain with 50 million queued links still gets only its polite ~0.5 pages/s while thousands of other domains run in parallel. Per-host campaign page budgets and frontier queue caps stop one giant site from exhausting disk space, and skewed mega-domains can be split onto dedicated partitions so they do not crowd neighbors. Finally, lease batches mix multiple hosts and steer slow servers to high-concurrency Tier A workers with strict timeouts so one sluggish giant never ties up worker slots.
  • How would your architecture adapt if target pages rely on client-side JavaScript to render content and links? Headless browser rendering consumes roughly 10–50x more CPU and memory than plain HTML parsing and fires dozens of sub-requests (scripts, stylesheets, API calls), so rendering must run only on dedicated Tier A or cloud render pools rather than flaky residential devices. Every sub-resource request triggered by the page must pass through the same SSRF guard and count against its target host's politeness budget, with ads, trackers, and media blocked and common JS frameworks cached across pages. Rather than rendering the whole web, compare raw-HTML text against rendered DOM text on a small sample per host to trigger rendering selectively, storing both raw HTML and rendered DOM snapshots tagged with the renderer version.
  • How can you roll out updated URL normalization rules while preserving historical crawl lineage? Because every URL record stores its canon_version and every link edge retains the raw discovered URL string, you can run v4 offline in shadow mode first—measuring how many v3 IDs merge or split and verifying that merged URLs actually share content hashes. During rollout, never overwrite or delete v3 records in place; instead, create or keep the winning v4 record partition by partition and write explicit alias rows (old_url_id -> new_url_id, evidence = "canon_v4", timestamp). Historical fetch logs remain intact under their original IDs and stay queryable across the alias link, making rollback as simple as ignoring canon_v4 aliases.
  • What structural invariants guarantee that concurrent link discoveries never insert duplicate logical URL entries? Workers never insert frontier records directly; they only emit raw discovered links. Every link is canonicalized deterministically under a single active rule version to a 128-bit url_id (where collision probability across 3 billion URLs is ~10^-20) and routed by hash(politeness_key) to one specific partition. That partition enforces single-writer ownership via a lease carrying a monotonically increasing epoch number, so the replicated storage engine rejects any stale writes from a deposed leader. Finally, inserting url/{url_id} uses an atomic conditional put_if_absent committed through the partition's consensus log, guaranteeing at most one record per (canon_version, canonical_url).
  • Suppose 500 of your 1,000 workers sit on flaky home broadband connections that drop offline for hours—what fails first, and how do you harden the design? Long disconnects strand active leases—delaying those URLs and blocking their hosts' politeness slots until expiry—while waking laptops with skewed wall clocks may fire off stale queued fetches simultaneously, causing duplicate hits and politeness violations. To fix this, restrict Tier C residential nodes to tiny batches (1–5 URLs) and short 90 s leases, measure remaining lease life against a local monotonic clock rather than wall-clock time, drop all queued leases immediately after any disconnect or sleep gap, and never assign fragile or tightly rate-limited hosts to Tier C. Because Tier C accounts for only ~6% of total fleet concurrency in our sizing (1,200 of 19,200 slots), provisioning Tiers A and B to carry 100% of target load keeps throughput steady even if every residential node goes dark.
  • If product requirements demand completing a 1-billion-page crawl within 30 days, which capacity bottlenecks and parameters must change? Crawling 1 billion pages in 2.592 million seconds requires ~386 pages/s for the pass alone—bringing total load with ongoing recrawls and 30% protocol overhead to ~1,000 pages/s average and ~2,000 pages/s peak (~4,000 concurrent fetches, still comfortably inside our 1,000-worker fleet's 19,200-slot ceiling, so worker count does not need to grow). Instead, four other numbers must move: (1) host breadth and politeness agreements, because at 0.5 pages/s no single host above ~1.3 million pages can finish in 30 days without official data dumps, APIs, or negotiated higher rates, and at least ~800+ distinct hosts must stay busy every second; (2) frontier capacity and link deduplication, growing to ~5 billion known URLs (~750 GB across more frontier nodes) and ~31,000 link checks/s; (3) storage and central parsing, adding ~25 TB of compressed snapshots (~100 TB raw) per pass and scaling parse workers ~2.6x (from ~240 to ~630 pages/s); and (4) tail scheduling, prioritizing the largest hosts from day 1 so slow domains do not blow the day-30 deadline.

Follow-up questions

Similar questions

More Lyft interview questions

All 52 Lyft questions →