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.txtand 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
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.txtdirectives 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.
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/graphWhat 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).
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.txtrules 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.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 (httporhttpsonly); strip default ports (:80for HTTP,:443for 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/Appleand/wiki/apple/can be distinct pages on Linux servers); replace an empty path with/. 5. Fragment: Strip#sectionfragments completely (browsers never send them to servers). 6. Query string: Preserve parameter order (some backends treat?a=1&b=2differently 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=1Evidence-based aliasing instead of blind merging: - Never blindly merge
httpwithhttps, orwww.example.comwithexample.com. Instead, merge them only when crawl evidence proves equivalence—such as an HTTP301/308permanent redirect, a<link rel="canonical">tag, or repeated identical body hashes—recording an explicitaliasedge 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: - Seturl_id = first_128_bits(SHA256(canonical_url)). Why 16 bytes instead of a 64-bit integer? By the birthday paradox, amongn = 3 billionURLs, ab-bit hash produces roughlyn^2 / 2^(b+1)expected collisions: forb = 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!). Forb = 128, expected collisions drop to~10^-20. Storecanon_versionalongsideurl_idrather 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,048chars,<= 16path segments, no segment repeated> 3times -> hop depth from seed<= max_depth-> host page budget remaining. - Redirects: Follow up to 5 hops inline only whenscheme://host:portstays identical (so the lease'srobots.txtrules and politeness slot still apply). Any cross-origin redirect (evenhttp->https) ends the current fetch as3xxand enqueues the target URL through the normal scope,robots.txt, and politeness pipeline. -robots.txtand politeness: Cache onerobots.txtper origin (scheme://host:port) for up to 24 hours, parsing at least 500 KiB per RFC 9309. HTTP4xxmeans unrestricted crawl;5xxor network timeout means full disallow untilrobots.txtcan be fetched cleanly. Default politeness enforces 1 active connection per host and a >= 1 s adaptive gap between requests (honoringCrawl-delayandRetry-After, doubling delay on429/503).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 asexample.com) using the Public Suffix List—a public catalog of domain suffixes including shared hosting platforms likegithub.io, ensuringalice.github.ioandbob.github.ioget separate politeness keys whilewww.example.comandshop.example.comshare 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 forexample.comlands on the same single writer,host.next_allowed_atis 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) plusdelay_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/aboutsimultaneously, 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", writeurl/{url_id}via conditionalput_if_absentand set the Bloom bits. If "maybe seen", checkurl/{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!- Politeness key (
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 (strictCrawl-delayor recent429s) 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)withlease_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 unlesslease_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 leaseRETRYABLE(attempt + 1), keeping the host's politeness slot blocked untilexpires_at + delay_msin 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 /pageand 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 keyFetch history row Keyed by (url_id, fetch_id)wherefetch_idis assigned once per lease; resending writes identical dataState transition Conditional on matching current (lease_id, partition_epoch); late completions from expired leases log fetch evidence without altering frontier stateExtracted outlinks Routed to target partition for conditional put_if_absent(url_id)Campaign counters Aggregated from partition state tables rather than blind +1increments- Pull leases, never push host assignments: Workers call
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 for192.168.1.1on a second lookup) cannot scan a corporate VPC or a residential volunteer's home Wi-Fi router. 2. Conditional HTTP & hard resource caps: SendGETonly (no cookies),Accept: text/html,application/xhtml+xml,Accept-Encoding: gzip, br, an identifyingUser-Agent, and conditional request headers (If-None-Matchwith previousETag,If-Modified-Since) so unchanged servers return tiny304 Not Modifiedresponses. Enforce timeouts (10 s connect, 10 s TLS, 30 s first byte, 60 s total, abort if< 1 KB/sfor 20 s against tarpits) and abort non-HTMLContent-Typeheaders or bodies exceeding 10 MB either on the wire or after decompression (blocking zip/gzip bombs; marktruncated = trueif cut). 3. Upload & report: ComputeSHA256(decompressed_body), compress withzstd,PUTto{region}/staging/sha256/{hash}via pre-signed URL (skipped only ifblob_indexalready 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,000links/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
<= 3bits. 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/503also back off the host; move to DLQ after 5 failures. - Terminal URL (400, 401, 403, 404, 410, 451, disallowedContent-Type,> 5redirects): MarkCOMPLETEDwith status (401/403never retried;404/410confirmed twice 24 h apart before marking removed). - Poison (>= 3silent lease expiries or>= 3parser 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/bloops): 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.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/andqueue/). Note thatwww.example.comandblog.example.comhave separaterobots/keys but live inside the sameexample.compartition! - 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-computesSHA-256before markingverified_atinblob_index—preventing a buggy or malicious device from poisoning a popular hash!Manage recrawls, backpressure, safety, and operations
Adaptive recrawl scheduling: Each URL tracks observed changes (
changes / visits) to estimate its daily change ratelambda, combined with an importance score (tier + inlinks). Modeling edits as random independent arrivals, the probability a page changed afterTdays is1 - exp(-lambda * T). Setting that equal to target staleness tolerancep(tighterpfor 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 Modifiedor identicalcontent_hash: advance metadata without storing a duplicate blob and lengthenT. On two consecutive404/410s 24 h apart: mark removed, probe monthly x3, then retire. On301/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;p99due-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-campaign429rate> 2%, Tier C lease-expiry rate> 30%, parse lag> 15 min, and storage error rate> 0.5%. - Rule migrations & frontier rebuilds: Shadow-testcanon_v4offline against saved raw links first; roll out partition by partition writing non-destructivealiaspointers rather than mutating old history. Because the frontier is derived state, total loss is recoverable by replaying seeds +outlinks+fetchesinto 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 stateEXCLUDED, immediately deleting theblob_indexpointer for anycontent_hashunreferenced 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 sendPOST, cookies, credentials, or requests matching side-effect patterns (/logout,/checkout,/cart,/delete,/unsubscribe). - Kill switches (< 10 sstop): Backed by a strongly consistent config store; the lease gateway refreshes every1 s(halting new leases immediately) and workers poll every5 sto abort matching in-flight requests by global, campaign, or domain scope.- On
Expose idempotent APIs and summarize key trade-offs
Every mutating endpoint accepts an
Idempotency-Keyheader—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=canonicalis 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/httpsorwwwvariants only via recorded alias evidence (301redirects,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 asexample.com, while keeping shared platforms likealice.github.ioseparate) 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
3xexpected 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
GETmakes "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
#fragmentsandutm_*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.txt5xxerrors or timeouts as "crawl allowed": RFC 9309 requires treating unreachable/5xxrobots.txtresponses as temporary full disallow, and cachingrobots.txtperscheme://host:portrather than once per registrable domain. - Resolving relative links against the requested URL instead of the final redirected URL: When
https://example.com/promoredirects tohttps://example.com/2026/promo/index.html, resolvinghref="faq.html"against/promoproduces a broken404URL. - Following cross-host redirects inline inside the worker: Bypasses scope checks,
robots.txtrules, 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_versionand every link edge retains the raw discovered URL string, you can runv4offline in shadow mode first—measuring how manyv3IDs merge or split and verifying that merged URLs actually share content hashes. During rollout, never overwrite or deletev3records in place; instead, create or keep the winningv4record partition by partition and write explicitaliasrows (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 ignoringcanon_v4aliases. - 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 byhash(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, insertingurl/{url_id}uses an atomic conditionalput_if_absentcommitted 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
- How do you keep a single massive website with millions of queued URLs from blocking smaller domains?
- How would your architecture adapt if target pages rely on client-side JavaScript to render content and links?
- How can you roll out updated URL normalization rules while preserving historical crawl lineage?
- What structural invariants guarantee that concurrent link discoveries never insert duplicate logical URL entries?
- 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?
- If product requirements demand completing a 1-billion-page crawl within 30 days, which capacity bottlenecks and parameters must change?
Similar questions
- Design an Online Charity Fundraising Platform
- Resilient Wikipedia Archiving System Over Untrusted Workers
- Direct Messaging Service Architecture
- Real-Time Direct and Group Messaging Platform
- Wiki Archiver with a Five-Day Freshness SLA
- Multi-Device Direct Chat and Real-Time Sync Architecture
More Lyft interview questions
- In-Memory Transactional Key-Value Store Easy
- Stateful Batch Reader for Paginated APIs Medium
- Shortest Substring Covering Character Multiplicities Medium Pro
- Minimum-Worker Interval Task Scheduling Medium Pro
- Chunked Word Reader Over a Variable-Size Page API Medium Pro
- Poisson Supply-and-Demand Coverage and Fill Rate Medium Pro
- Leading Through Ambiguity and Compensation Negotiation Medium Pro
- Multi-Device Direct Chat and Real-Time Sync Architecture Medium Pro
- Key-Value Store with Shared Monotonic Snapshot Versions Medium Pro
- Direct Messaging Service Architecture Medium Pro