SkillSprout
Chapter 5 · Lesson 4
Intermediate
26 min read

Design a Web Crawler

Overview

A web crawler (also called a spider) is a program that starts from a few known web pages, downloads them, extracts the links inside, and follows those links to discover more pages, again and again. Search engines use crawlers to build their index, and many other products use them too: price trackers, archive services, and machine-learning teams collecting training text. The idea fits in one sentence, which is why the interview is really about scale and manners. We must fetch about a billion pages a month without hammering any single website, without wasting work on pages we already have, and without getting lost in endless loops. This lesson walks the full eight-step framework with the reasoning to say out loud at each step.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about any real search engine. The interviewer will not check whether one billion pages a month is realistic; they will check that your estimates drive your design. The heart of this problem is one component, the URL frontier (the data structure that decides which URL to fetch next), so expect to spend half the time on it.

Step 1: Clarify Requirements

Open with: "Before designing, I'd like to agree on what we crawl, why, and how big it is." The answer changes the design. A crawler for a search engine needs breadth and freshness. A crawler for one company's price tracking needs depth on a few sites.

Functional requirements

  • Start from a set of seed URLs (the hand-picked starting pages) and discover new pages by following links.
  • Download each page's HTML and store it for downstream systems (indexing, ranking, analytics).
  • Extract links from each page and add the new ones to the crawl.
  • Re-crawl pages over time so stored copies stay fresh.

Extended requirements

Mention these, then ask whether to include them.

  • Crawl non-HTML content: images, PDFs, video.
  • Render JavaScript-heavy pages in a headless browser (a browser without a visible window).
  • Prioritize important pages (for example by link popularity).
  • Detect near-duplicate pages, not just identical ones.

Non-functional requirements

Put a number on each one.

  • Scale: about 1 billion page fetches per month, from a known set of about 5 billion distinct pages.
  • Politeness: never overload a website. At most one request per second per host, and obey the site's robots.txt file (a text file at /robots.txt where a site lists which paths crawlers may not visit, and sometimes a Crawl-delay).
  • Robustness: the web is full of broken HTML, slow servers, infinite loops and malicious pages. The crawler must survive all of them without crashing.
  • Freshness: news pages re-crawled within hours, ordinary pages within weeks, rarely changing pages within months.
  • Extensibility: adding a new content type (say images) should mean adding a module, not redesigning.
  • Fault tolerance: a machine dying must not lose the crawl state or cause the same site to be crawled twice at once.
  • Low duplicate work: do not store or re-process the same URL or the same content twice.

Latency is not the goal. Unlike a URL shortener, no user is waiting for one request. We optimize throughput (pages per second) and good behavior, not p99 latency. Saying this early shows you understand the workload.

Out of scope

Ranking, indexing and search (the crawler hands pages to them), JavaScript rendering, crawling content behind a login, and legal questions about copyright. We will mention each only briefly.

Interview tip. Many candidates draw "fetch, parse, repeat" and never mention politeness or duplicates. Those two topics are what interviewers listen for. Raise them yourself in Step 1.

Step 2: Estimate Scale

Assumptions to state

  • 1 billion pages fetched per month (new pages and re-crawls together).
  • 5 billion distinct pages in our collection; 10 billion distinct URLs ever seen (many discovered URLs are never fetched: duplicates, low value, blocked).
  • Average HTML page: 100 KB.
  • Each page contains about 50 links.
  • A day has about 100,000 seconds.
  • We keep only the latest version of each page. Old versions are not needed.

Request load

text
1B pages / 30 days             = about 33M pages per day
33M / 100,000 seconds          = about 330 pages per second
Add 20% for retries and re-crawls, round up = 400 pages per second
Peak (2x average)              = about 800 pages per second
Links to check = 400 pages/s x 50 links     = 20,000 URLs per second

The second number matters more than the first. Every fetched page produces 50 candidate URLs, so the "have I seen this URL?" check runs 20,000 times per second, about 50 times more often than the fetch itself. That check cannot be a disk database query. It must be answered from memory.

Web Crawler: Estimate the Scale
Estimation

Request load

1Bpages / month
given
33Mper day
÷ 30 days
~400/sfetches (from 330)
÷ 100,000 s, +20%
800/sat peak
× 2 peak factor
20K/sURLs to check
× 50 links/page

Page storage

~170 TB

5B pages × 100 KB = 500 TB, 3:1 compression

Object storage; keep only metadata in a database

Bandwidth

~320 Mbps

400 pages/s × 100 KB (640 Mbps at peak)

Fits ~20 fetchers; use 304s to save cost

Dedup memory

12.5 GB

10B URLs × 10 bits (Bloom) vs 80 GB exact

Bloom filter in RAM; frontier of ~100 GB on disk
Key point. Throughput is modest, storage is huge, and the seen-check runs 50 times more often than the fetch.

A billion fetches a month is only 400 pages per second. The scale problem is hidden in the 50 links on each page.

Storage

text
5B pages x 100 KB           = 500 TB raw
Compression (about 3:1)     = about 170 TB stored
URL metadata: 5B x 200 bytes = 1 TB
Content fingerprints: 5B x 8 bytes (64-bit) = 40 GB

500 TB of page content is far too big for a database row store, so pages go into object storage (cheap, huge, key-addressed storage for large files, from the blob storage lesson). Only small metadata goes in a database.

Bandwidth

text
400 pages/s x 100 KB        = 40 MB/s = 320 Mbps
Peak: 800 pages/s x 100 KB  = 80 MB/s = 640 Mbps
Per month downloaded        = 1B x 100 KB = 100 TB

About 640 Mbps at peak is less than one 1 Gbps network card, so bandwidth does not force a design change. It is a cost line item (100 TB a month) and a reason to use conditional requests (Step 6) so unchanged pages are not downloaded again.

Duplicate-detection memory

text
Exact set of 64-bit URL fingerprints: 10B x 8 bytes = 80 GB
Bloom filter, 1% false positives:     10B x 10 bits = 100 Gbit = 12.5 GB

A Bloom filter (from the probabilistic data structures lesson) is a compact bit array that answers "definitely not seen" or "probably seen". Ten bits per item gives about a 1% false-positive rate. 12.5 GB fits in one machine's memory with room to spare. 80 GB fits across a few machines. Either is feasible; we compare them in Step 6.

URL frontier size

text
Pending URLs waiting to be fetched: about 1B
1B x 100 bytes per URL entry        = 100 GB
Drain time at 400 pages/s: 1B / 400 = 2.5M seconds = about 29 days

The pending queue is about 100 GB, too big to keep wholly in RAM on one node, so the frontier is disk-backed with in-memory heads (the front of each queue is in memory, the tail on disk). The drain time of about a month matches our monthly crawl cycle, which is a good sanity check.

Fleet size

text
One fetcher machine (network and parsing limits)  = about 50 pages/s
400 / 50 = 8 machines average, 800 / 50 = 16 at peak
Round up with headroom                            = about 20 fetcher machines
In-flight requests: 50 pages/s x 1 s latency      = about 50 open connections each

Most of a fetcher's time is spent waiting for remote servers, not computing, so it runs many fetches at once (concurrency) using asynchronous I/O.

The politeness ceiling

One host at 1 request per second yields 86,400 pages a day. A site with 100 million pages would take about 3 years to crawl politely. So per-host speed is capped by manners, not by hardware, and to reach 400 pages/s we must crawl at least 400 different hosts at the same time. The frontier's job is to keep hundreds of hosts in flight, each at a gentle pace.

Interview tip. End each estimate with a "so what": "20,000 URL checks a second means in-memory dedup", "100 GB frontier means disk-backed queues", "per-host limits mean I need many hosts in parallel".

Step 3: Define the APIs

A crawler has few user-facing APIs; most interfaces are internal between components. Still define them, because they reveal the data you need to track.

Submit seeds and control a crawl

http
POST /v1/seeds
Authorization: Bearer <token>
Content-Type: application/json

{
  "urls": ["https://example.com/", "https://news.example.org/"],
  "priority": "high",
  "max_depth": 10
}
json
{
  "accepted": 2,
  "rejected": 0,
  "job_id": "job_8f21"
}
  • 202 Accepted: seeds are queued, crawling happens later.
  • 400 Bad Request: a URL is malformed or not http/https.
  • 401 Unauthorized and 429 Too Many Requests as usual.
http
GET  /v1/jobs/{job_id}              # pages fetched, queue size, error counts
POST /v1/blocklist                  # never crawl this host or pattern
GET  /v1/pages?url=https://example.com/   # latest stored copy plus fetch metadata

Internal API: fetchers lease URLs from the frontier

http
POST /internal/frontier/lease
{ "worker_id": "fetcher-17", "max": 100 }
json
{
  "lease_id": "l_55a0",
  "lease_expires_in_s": 300,
  "urls": [{ "url": "https://example.com/a", "host": "example.com" }]
}
http
POST /internal/frontier/ack
{ "lease_id": "l_55a0", "results": [{ "url": "https://example.com/a", "status": "done" }] }

A lease is a temporary claim: the fetcher owns those URLs for 5 minutes. If it never acknowledges (it crashed), the lease expires and the URLs return to the queue. This gives at-least-once processing, which is safe because duplicate fetches are harmless (Step 6 removes duplicate content).

How the API shapes the architecture

Fetchers pull work instead of the frontier pushing it. A pulling worker asks only when it has free capacity, so a slow worker never gets buried (this is natural backpressure, from the queues lesson).

Step 4: Define the Data Model

Access patterns first:

  1. Seen check by URL: "have we already queued or crawled this?" (20,000 per second, from memory).
  2. Read and write the state of one URL: last crawl time, next crawl time, content fingerprint (400 per second).
  3. Find URLs due for re-crawl: "next_crawl_at is before now" (background scan).
  4. Per-host rules: robots.txt rules, crawl delay, cached IP address, looked up on every fetch.
  5. Store a page body and find it by content hash.

Fields and why each exists

  • url_hash: a 64-bit hash of the normalized URL (Step 6). It is the primary key; storing a fixed 8-byte key instead of the full URL keeps indexes small.
  • host: groups URLs for politeness and for partitioning.
  • next_crawl_at: when the URL should be fetched next. This drives re-crawl scheduling.
  • etag and last_modified: values the server sent last time. We send them back so the server can answer "not modified" (304) without a body.
  • content_fingerprint: a hash of the content, to detect that a page did not change or is a duplicate of another URL.
  • crawl_interval_s: how often this page seems to change.
  • fail_count: consecutive failures, used for retry limits and for giving up on dead pages.
  • Host table: robots_txt, crawl_delay_ms, ip and expiry times, so one robots.txt fetch serves thousands of pages.
The Data Model
Data model
url_stateWide-column store
  • PKurl_hashbigint

    64-bit hash of the normalized URL

  • urlvarchar(2048)

    normalized URL

  • FKhostvarchar(255)

    partition key; groups a host's URLs

  • IDXnext_crawl_attimestamp

    re-crawl scheduler scans this

  • crawl_interval_sint

    halves on change, doubles if stable

  • etagvarchar

    sent back as If-None-Match

  • FKcontent_fingerprintbigint

    detects unchanged or duplicate content

  • fail_counttinyint

    gives up after 3-5 failures

About 200 bytes per row, 5 billion rows, 1 TB total.

hostsKey-value store
  • PKhostvarchar(255)
  • robots_rulestext

    parsed, cached about 24 hours

  • crawl_delay_msint

    1,000 default, or from robots.txt

  • ipvarchar(45)

    cached DNS answer

  • ip_expires_attimestamp

    honors DNS TTL

One robots.txt fetch serves thousands of pages.

pagesObject storage + index
  • PKcontent_hashbigint

    same content stored once

  • blob_pathvarchar

    compressed HTML in the bucket

  • IDXsimhashbigint

    near-duplicate lookup by bit blocks

  • fetched_attimestamp

Bodies are written once and read in bulk by indexing jobs.

frontier_entryDisk queues + log
  • PKhostvarchar(255)

    one back queue per host

  • SKurlvarchar(2048)
  • prioritytinyint

    front queue 1-3

Head in memory, tail on disk; rebuilt from log after a crash.

  • url_state.hosthosts.host· many to one
  • url_state.content_fingerprintpages.content_hash· many to one
Key point. Partition URL state by host so politeness and per-host data live on one node.

URL state is small and keyed by hash. Page bodies live in object storage, keyed by content hash.

Which database?

  • URL state is a huge key-value table (5 billion rows, 1 TB) accessed by key, with a secondary index on next_crawl_at. A wide-column or key-value store partitioned by host fits, because it scales out and handles the write volume. A sharded relational database also works; justify it either way.
  • Page bodies are big, written once, read in bulk by indexing jobs: object storage, keyed by content hash.
  • Frontier queues have their own purpose-built structure (Step 6), not a general database table. A database used as a queue struggles with constant pops and deletes.
  • Bloom filter and fingerprints live in memory, with periodic snapshots to disk.

Trade-off thinking. A single database for everything is simple but cannot serve 20,000 seen-checks a second at low cost. Splitting by access pattern (memory for dedup, key-value for state, object storage for bodies) adds components but matches each workload.

Step 5: High-Level Design

The crawl is a loop: take a URL, fetch it, parse it, find new URLs, filter them, and add them back to the frontier. We build it as a pipeline of stages that scale independently. Fetching waits on the network, parsing burns CPU, so they run on different machines in different numbers.

The Crawl Pipeline
Architecture
Seed URLsstart + re-crawlURL frontierpriority + politeFetchersasync HTTPDNS + robotscached per hostParserHTML, linksPage storeobject storageURL filternormalize + seenContent seenchecksum, simhashlease URL1ip, rulesHTML2savelinksfingerprintnew URLs3
Key point. Each stage scales on its own: fetchers wait on the network, parsers burn CPU.

A loop: fetch, parse, extract, filter, and feed new URLs back to the frontier.

Components and why each exists

  • Seed URLs and re-crawl scheduler: inject starting URLs and re-enqueue old pages when they are due.
  • URL frontier: holds URLs waiting to be fetched and decides the order, enforcing priority (important first) and politeness (gentle per host). The deep dive covers it.
  • Fetchers: download pages over HTTP. Many run in parallel with asynchronous I/O.
  • DNS and robots cache: before fetching, we must turn example.com into an IP address (DNS lookup) and check robots.txt. Both are cached, because a DNS lookup can take 10-100 ms and robots.txt rarely changes.
  • Parser and link extractor: parses HTML, handles broken markup, extracts text and links.
  • Content-seen check: computes a fingerprint of the page and drops duplicates before storing them.
  • Page store: object storage holding the downloaded content.
  • URL filter and URL-seen check: normalizes URLs, removes disallowed ones, and drops those already seen, so only genuinely new URLs reach the frontier.

Keeping stages separate lets each scale on its own: perhaps 20 fetchers feed only 8 parser machines.

Fetching One URL
Request flow
FetcherDNS + robotscacheWebsitePage store1resolve host, rulescache hit for most URLs2IP + alloweddisallowed: skip URL3GET /a (If-None-Match)4200 HTML or 304timeout 10 s, max 10 MB5save compressed bodykeyed by content hash6ok, then parse queue

On a 304 the flow ends after step 4: no body is downloaded or stored.

Request flow

  1. The frontier hands a fetcher a URL whose host is allowed to be contacted now.
  2. The fetcher resolves the host through the DNS cache and checks the cached robots.txt rules.
  3. It sends GET with If-None-Match and If-Modified-Since headers.
  4. On 200 it receives the HTML; on 304 it learns nothing changed and stops.
  5. It saves the body to the page store and passes the page to the parser.
  6. The parser extracts links; the URL filter normalizes and dedups them; new ones go to the frontier.
  7. The fetcher records the result and schedules the next crawl time.

Step 6: Deep Dive

Interviewers pick the hardest area. Here that is the frontier, duplicate detection and partitioning. Be ready for all of them.

6.1 The URL frontier: priority plus politeness

The frontier has two competing jobs. Priority: crawl important or fast-changing pages first. Politeness: never send more than one request per second to a host, and never let many workers hit one host at once. A single queue cannot do both, so the classic design (from the Mercator crawler) uses two layers.

The URL Frontier: Priority, Then Politeness
Architecture
PriorityPolitenessPrioritizerscore each URLHigh queue60% of picksMedium queue30% of picksLow queue10% of picksBiased pickerno starvationHost routerhost to queueHost A queueone host onlyHost B queueone host onlyHost C queueone host onlyReady-time heapnext allowed time
Key point. One host per back queue plus a ready-time heap gives politeness with no locks.

Front queues choose what is important. Back queues, one per host, choose when a host may be contacted.

Front queues: priority. A prioritizer gives each URL a score, for example from page popularity, how often it changes, and how deep it is. Each score maps to one of several queues (high, medium, low). A biased picker chooses a queue with probability like 60%, 30%, 10%, so important pages go first but low-priority queues still make progress and never starve (wait forever).

Back queues: politeness. Each back queue holds URLs of exactly one host. A router sends a URL to the queue of its host (a map from host to queue). A min-heap (a structure that always gives you the smallest item first) holds one entry per back queue, ordered by the time that host may next be contacted. A fetcher thread pops the heap's top entry, waits until that time, takes one URL from that queue, fetches it, then pushes the queue back with next_time = now + delay, where delay is 1 second or the robots.txt Crawl-delay.

Why this works:

  • One host never has two requests in flight, so politeness is automatic.
  • With 400 hosts active, the heap always has ready work, so we reach 400 pages/s while each host sees only 1 per second.
  • When a back queue empties, it is refilled from the front queues with the next URL, which keeps the number of active hosts constant.

Storage of the frontier. 1 billion entries at 100 bytes is 100 GB. Back queues keep their head in memory and spill the rest to disk in append-friendly files, so reads and writes are sequential and cheap.

Trade-off thinking. A plain FIFO queue is simplest but crawls one big site in a burst (impolite) and ignores importance. A priority-only queue ignores politeness. Two layers cost more complexity but satisfy both rules.

BFS or DFS? Breadth-first search (BFS) crawls all links at depth 1, then depth 2, and so on, using a FIFO queue. Depth-first search (DFS) follows one link chain as far as it goes before backing up. Use BFS-like ordering. DFS dives into a single site and can chase a very long chain of links, an ideal spider trap, and it breaks politeness by staying on one host. BFS finds important, well-linked pages early (they are near the seeds) and spreads load over many hosts. Real crawlers use BFS shaped by priority, not pure BFS.

6.2 robots.txt and DNS caching

robots.txt. Before crawling a host, fetch https://host/robots.txt once and cache the parsed rules per host for about 24 hours. For each URL check the rules for our crawler's name. Handle failures carefully:

  • 404 / 4xx: the site has no rules, so everything is allowed.
  • 5xx or timeout: we do not know. Treat the host as temporarily disallowed and retry later, so we never crawl a site that is merely having a bad moment and did not consent.
  • Respect Crawl-delay by storing it as the host's delay.

DNS caching. A DNS lookup can take 10-100 ms and the default resolver may serialize requests, which would become the hidden bottleneck at 400 fetches a second. Run a local caching resolver with a big in-memory cache, honor TTLs, and cache failures briefly. Because the frontier groups URLs by host, the IP is typically looked up once per host and reused for many pages, so the real lookup rate is only a few per second.

6.3 Duplicate URLs: normalize first, then check

Many different strings mean the same page: HTTP://Example.com:80/a/../b?x=1&y=2 and http://example.com/b?y=2&x=1. Canonicalization (normalization) makes them equal before the seen check:

  • lowercase the scheme and host, drop default ports (80, 443), and remove the #fragment;
  • resolve . and .. path segments and decode safe escapes;
  • sort query parameters and drop known tracking ones (utm_source, session IDs);
  • apply rel="canonical" links when pages declare them.

Then hash the normalized string to 64 bits and test membership. We need a structure that answers 20,000 checks a second.

Remembering Billions of URLs
Comparison

Database lookup

exact, on disk

  1. 1

    Normalize the URL

    lowercase, sort params

  2. 2

    Query the URL table

    one disk read per URL

  3. 3

    Insert if absent

    conditional write

  • Exact answers
  • Durable
  • 20K disk lookups per second is costly
  • Adds latency to every link

Good as the record of truth, not as the first gate

Hash set in RAM

exact, 64-bit fingerprints

  1. 1

    Hash URL to 64 bits

    8 bytes per URL

  2. 2

    Look up in a sharded set

    10B × 8 B = 80 GB

  3. 3

    Add if missing

    snapshot to disk

  • No missed URLs
  • Fast memory lookup
  • 80 GB over several nodes
  • Rare 64-bit hash collisions

Use when missing a URL is unacceptable

Bloom filter

probabilistic, 1% error

  1. 1

    Hash URL k times

    k bit positions

  2. 2

    Check the k bits

    10 bits per URL, 12.5 GB

  3. 3

    Any bit 0 means new

    all 1 means probably seen

  • 6x smaller than the hash set
  • Never repeats a crawl
  • About 1% of new URLs wrongly skipped
  • Cannot delete entries

Best first gate; URL table is the backup

Key point. A Bloom filter never says 'new' for a seen URL; its only error is skipping a rare new one.

Three ways to answer 'have I seen this URL?' for 10 billion URLs at 20,000 checks a second.

Decision: an in-memory Bloom filter as the fast first gate (12.5 GB), because a false positive only means we skip a genuinely new URL (about 1% of discoveries, and most of those would be found again through other links). A "no" from the filter is always correct, so we never crawl something twice by mistake. The durable record of crawled URLs sits in the URL state table, which also lets us rebuild the filter after a crash. If the product cannot tolerate missed URLs (for example a legal archive), use the exact hash set (80 GB, partitioned over a few nodes).

6.4 Duplicate content: checksum and simhash

Different URLs often serve the same page: mirrors, ?ref= variants, printer views. Detecting them saves storage and downstream work.

  • Exact duplicates: checksum. Hash the body (SHA-256 or a 64-bit hash). If that hash is already known, store a pointer instead of the body and skip link extraction.
  • Near duplicates: simhash. A simhash is a 64-bit fingerprint where similar documents get fingerprints that differ in only a few bits. Build it by hashing each word or phrase, summing a +1 or -1 per bit position across all words, and keeping the sign of each total. Two pages are near-duplicates if their simhashes differ in at most about 3 of 64 bits (Hamming distance is the count of differing bits). To search quickly, split the 64 bits into blocks and index by block, so that near matches share at least one identical block.

Cost: 5 billion simhashes at 8 bytes is 40 GB, easily affordable. Content dedup runs after the fetch, inside the parser pipeline, off the fetch critical path.

6.5 Spider traps

A spider trap is a set of pages that generates endless unique URLs: a calendar with a "next month" link forever, /a/b/a/b/a/b/..., or session IDs added to every link. Some are accidental, some malicious. The crawler would otherwise spend its whole budget there. Layer the defenses, since none is perfect alone:

  • Maximum URL length (for example 2,048 characters) and maximum depth from the seed (for example 15 hops).
  • Per-host page budget: crawl at most N pages per host per cycle, scaled by the host's importance, so a trap exhausts only its own quota.
  • Pattern detection: reject URLs with the same path segment repeated 3 or more times, or hosts whose new URLs share one pattern and keep growing.
  • Content dedup: a trap often serves near-identical pages, which simhash catches.
  • Monitoring: alert when one host's pending queue grows faster than it drains.
  • A human blocklist as a last resort.

6.6 Re-crawl scheduling

Pages change at very different speeds. A news homepage changes hourly; an old blog post never does. Re-crawling everything monthly wastes work on static pages and leaves news stale.

  • Store crawl_interval_s per URL. After each fetch compare the new content fingerprint to the old one. Changed: halve the interval (minimum 1 hour). Unchanged: double it (maximum 90 days).
  • Set next_crawl_at = now + interval. A scheduler scans the index on next_crawl_at and enqueues due URLs into the frontier with priority based on importance and staleness.
  • Use conditional requests: send If-None-Match: <etag> and If-Modified-Since. A 304 Not Modified response has no body, so an unchanged page costs a few hundred bytes instead of 100 KB.
  • Also use sitemap files and Last-Modified hints where available, and re-crawl popular pages sooner.

6.7 Distributed crawling: partition by host hash

One machine cannot do 400 pages/s with 100 GB of frontier, so we split the work. The key decision is the partition key: the host, not the URL. Use hash(host) on a consistent hashing ring (from the partitioning lesson), so each crawler node owns a set of hosts.

Partitioning Crawlers by Host Hash
Architecture
Crawler nodesHash ringhost to node mapLink extractorfound new URLsHost routerhash(host)Node 1hosts a.com, b.orgNode 2hosts c.net, d.ioNode 3hosts e.com, f.devPage storeshared bucketbatchesring
Key point. Partition by host, not by URL: one owner per host keeps rate limits and caches local.

Each node owns the hosts whose hash falls in its range, so politeness never needs cross-node locks.

Why host and not URL:

  • Politeness stays local. All URLs of one host land on one node, so that node alone enforces the 1-per-second rule with no cross-node locking.
  • Caches stay local. The robots.txt and DNS data for a host live on the node that needs them.
  • The seen-check can be partitioned the same way. A node sees only its hosts' URLs, so its Bloom filter covers 1/N of the 10 billion.

How a link found on a page of host A reaches host B's owner: the extractor groups new URLs by owner and sends them in batches through a message queue to that node's frontier. Batching matters, because one network call per URL at 20,000 URLs/s would be wasteful. Most links point to the same host, so only a fraction cross nodes.

Rebalancing: with consistent hashing, adding or removing a node moves about 1/N of the hosts. A very large site is owned by one node, but politeness caps its rate to 1 per second anyway, so it is not a hot spot.

6.8 The fetcher / parser / extractor pipeline

Decouple the stages with queues:

  • Fetchers do only network I/O: DNS, robots check, GET, size and time limits. They set a timeout (about 10 seconds), a maximum body size (for example 10 MB) and a redirect limit (about 5), because one huge or endlessly redirecting response must not block a worker.
  • Fetched pages go to a parse queue. Parsers are CPU-bound: they tolerate broken HTML, detect character encoding, extract links and text, and compute fingerprints.
  • Because the parse queue is durable, a slow parser only builds a backlog; fetchers keep going, and we scale parsers by queue depth.
  • New stages (image extraction, language detection) subscribe to the same queue, which is the extensibility requirement from Step 1.

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • DNS. Cause: a slow or serialized resolver. Mitigation: local caching resolver, batching and prefetching DNS for URLs about to leave the frontier.
  • Slow hosts. Cause: a server taking 30 seconds per page ties up a connection. Mitigation: strict timeouts, asynchronous I/O, and a longer delay for hosts that respond slowly (adaptive politeness).
  • Parse backlog. Cause: parsers slower than fetchers. Mitigation: scale parsers on queue depth; apply backpressure by slowing frontier leases when the queue is too long.
  • Frontier growth. Cause: link extraction produces far more URLs than we fetch (50 per page). Mitigation: strict URL filtering, a cap on queue size per host, and dropping the lowest-priority URLs when full.
  • Bloom filter saturation. Cause: the filter fills past its design capacity and false positives rise. Mitigation: monitor its fill ratio and rebuild or resize it with more bits per item before 10 billion URLs.
  • Hot large sites. Politeness caps them, but their pending queue may grow large; apply a per-host budget.

Failures

  • Fetcher crashes. Its leases expire after 5 minutes, and the URLs return to the queue. A duplicate fetch is harmless because of content-seen checks.
  • Crawler node (frontier owner) crashes. The frontier writes every enqueue and ack to an append-only log, and takes a checkpoint (a snapshot of state at a point in time) every few minutes: the queues, the heap and the Bloom filter go to durable storage. A replacement node loads the last checkpoint and replays the log after it. Its hosts are reassigned via the hash ring in the meantime, so politeness is preserved because only one owner exists at a time (enforced with a lease from the coordination service).
  • Lost Bloom filter. Rebuild from the URL state table (a scan of 5 billion rows) if no snapshot exists; it is slow but safe.
  • Target site fails. Retry with exponential backoff (1 minute, 5 minutes, 1 hour), then mark the URL dead after about 3 to 5 failures. A circuit breaker (stop trying a host after many consecutive failures, then probe occasionally) protects our workers from wasting time.
  • Page store or database outage. Pause the parse queue consumers; fetchers stop when backpressure builds. Nothing is lost because the queue is durable.
  • Poison pages. A page that crashes the parser goes to a dead-letter queue after a few attempts so it cannot block the stage.

Interview tip. Name what you would monitor: pages per second, fetch error rate by type (DNS, timeout, 4xx, 5xx), per-host request rate (must stay at or below the limit), frontier size, parse queue depth, duplicate ratio, Bloom filter fill ratio, and the oldest next_crawl_at that is overdue (freshness lag).

Step 8: Final Design Walkthrough

Final Design
Architecture
FrontierSeeds + recrawldue URLs by ageURL frontierpriority + politeFetcher fleetsharded by hostDNS + robotsper-host cacheParserlinks + textURL filterBloom + rulesPage storeobject storageContent dedupsimhashURL state DBnext_crawl_atleaseHTMLlinksstatenew URLs

Solid arrows are the main crawl loop. The dashed arrow is a periodic background job.

Request flow

The frontier selects a URL (priority first, then a host whose politeness timer is ready) and leases it to a fetcher. The fetcher checks the DNS and robots caches, sends a conditional GET, and receives HTML or a 304. The page is saved to object storage and placed on the parse queue.

Data flow

Page bodies live in object storage by content hash. URL state (fingerprint, ETag, next crawl time) lives in the partitioned key-value store. Bloom filter and simhash index live in memory with snapshots. Frontier queues live on disk with in-memory heads and an append-only log. Newly found URLs flow from the parser, through the filter and seen check, to the owner node's frontier via a batched queue.

Background processing

The re-crawl scheduler scans next_crawl_at and re-enqueues due URLs. Checkpointing snapshots the frontier and filters. Maintenance jobs expire robots.txt and DNS caches, delete dead URLs, rebuild the Bloom filter and report metrics.

Critical design decisions

  1. Two-layer frontier (priority front queues, per-host back queues with a ready-time heap), to satisfy importance and politeness together.
  2. Partition by host hash, so politeness, robots.txt and DNS caches stay local.
  3. Bloom filter before exact storage, since 20,000 seen-checks per second must be answered from memory.
  4. Checksum and simhash for content dedup, because many URLs serve the same content.
  5. Layered spider-trap defenses: length, depth, per-host budgets, patterns and content dedup.
  6. Adaptive re-crawl with conditional GET, to keep fresh pages fresh at low bandwidth cost.
  7. Leases, an append-only log and checkpoints, for at-least-once processing and fast recovery.

If time remains, discuss crawling JavaScript-rendered pages (a separate, much more expensive headless-browser fleet used only for hosts that need it), geographic crawlers placed near target sites to cut latency, and priority scoring with link-based ranking.

Common Interview Questions

Chapter quiz

Core Interview Designs · 6 questions

  1. 1.Why is the redirect path optimized with a cache rather than the write path?

  2. 2.With 30 billion total links, which key length is the best fit?

  3. 3.Why can't each gateway keep its own in-memory counter for a per-user limit?

  4. 4.What is the race condition in 'GET tokens, decide, then SET tokens'?

  5. 5.Why store the top-k suggestions on every trie node?

  6. 6.Why does the URL-seen check dominate the design more than the fetch rate does?

0 of 6 answered

Finished this lesson?

0 of 44 lessons done · 0% of the course