A web crawler (Googlebot, Bingbot, Common Crawl) starts from a set of seed URLs, downloads pages, extracts their links and repeats, building a copy of the web for a search index, an archive or a training dataset. Following links is the easy part; it is a Breadth-First Search over a graph with tens of billions of nodes. The real design work is in what to fetch next (priority), how fast to hit each site (politeness), what you have already seen (URL and content deduplication), when to come back (recrawl), and not getting stuck (traps), all spread across many machines.
Think of it like
Librarians cataloging every library in the world
A team of librarians sets out to catalog every book, following the bibliography of each book to find more. They keep a to-do list sorted by importance, but they must not send fifty people into the same small village library at once, so each library gets its own queue and a polite pause between visits. They check the posted rules on each library's door (robots.txt), keep a cheap 'already seen' list so they don't catalog the same title twice, notice when two books are photocopies of each other, and revisit the newspaper archive daily but the medieval manuscripts only once a year. And they learn to recognize the hall of mirrors that generates an endless corridor of identical rooms.
1. Requirements
Functional
- Start from seed URLs and discover new pages by following links
- Fetch HTML pages and hand them (with metadata) to downstream consumers such as an indexer
- Obey robots.txt and per-site rate limits
- Skip duplicate URLs and duplicate or near-duplicate content
- Recrawl pages to keep the copy fresh, more often for pages that change often
- Prioritize important pages
Non-functional
- Scale: about 1 billion fetches per day, horizontally scalable
- Politeness: never overload a website; back off when it struggles
- Robustness: survive traps, malformed HTML, slow or hostile servers
- Fault tolerance: a worker crash loses no frontier state
- Extensibility: new content types and processors plug in
- Efficiency: do not waste bandwidth on duplicates or unchanged pages
| In scope | Out of scope (mention, then park) |
|---|---|
| URL frontier: priority and politeness | Building the search index and ranking (see Search Systems) |
| robots.txt, DNS, fetching | Rendering JavaScript-heavy pages at scale (mention a separate rendering tier) |
| URL and content deduplication | Images, video and PDF processing |
| Recrawl scheduling and traps | Deep web content behind logins and forms |
| Distribution across workers and failure handling | Spam and quality classification of pages |
2. Back-of-the-envelope estimation
Target 1 billion fetches per day (new pages plus recrawls). Assume an average HTML page of 100 KB uncompressed that compresses about 4:1 for storage, a typical fetch takes about a second end to end, and each page links to dozens of URLs, so we discover far more URLs than we fetch. See Back-of-the-Envelope Estimation.
Fetch rate
~11.6k /s
1B pages per day
Download
~9.3 Gb/s
100 KB average page
Stored content
~9 PB /yr
compressed 4:1
Seen-URL Bloom filter
~12 GB
10B URLs at 1% FPR
3. Interfaces
A crawler has no public API, but its internal interfaces matter: the frontier service that hands out URLs, the output stream that downstream systems consume, and the robots.txt contract with every website.
syntax = "proto3";
service Frontier {
// Add discovered or scheduled URLs. The frontier dedups and scores them.
rpc Enqueue(EnqueueRequest) returns (EnqueueResponse);
// A fetcher leases up to max_urls whose hosts may be contacted now.
rpc Lease(LeaseRequest) returns (LeaseResponse);
// Report the outcome; this sets the host's next allowed time and the URL's next crawl time.
rpc Complete(CompleteRequest) returns (CompleteResponse);
}
message EnqueueRequest {
repeated string urls = 1;
string discovered_from = 2; // parent URL, for priority and trap detection
int32 depth = 3;
}
message EnqueueResponse { int32 accepted = 1; }
message LeaseRequest { string fetcher_id = 1; int32 max_urls = 2; }
message LeaseResponse { repeated Lease leases = 1; }
message Lease {
string url = 1;
string lease_id = 2;
int64 lease_expires_ms = 3; // unacknowledged leases return to the queue
string etag = 4; // for conditional GET
string last_modified = 5;
}
message CompleteRequest {
string lease_id = 1;
int32 http_status = 2; // 200, 304, 404, 429, 503...
int64 fetch_ms = 3;
bool content_changed = 4;
int32 retry_after_sec = 5;
}
message CompleteResponse {}User-agent: *
Disallow: /search
Disallow: /cart/
Allow: /search/help
User-agent: ExampleBot
Crawl-delay: 5
Disallow: /private/
Sitemap: https://www.example.com/sitemap.xml4. Data model
| Data | Key | Store | Why |
|---|---|---|---|
| URL records | Reversed host + path (com.example.www/docs/a) | Wide-column store (Bigtable, HBase, Cassandra) | Tens of billions of rows; reversed hosts keep a site's pages adjacent for scans |
| Host records | Hostname | Key-value store + in-memory cache | robots rules, crawl delay, IP, error rate, page budget |
| Frontier queues | Priority band, then host | Disk-backed queues (RocksDB, Kafka, custom files) | Billions of entries; only queue heads need to be in memory |
| Seen-URL set | URL fingerprint | Bloom filter in RAM + exact store on disk | Fast 'have we seen this?' for every extracted link |
| Page content | URL + fetch time | Object storage as WARC files | Large, append-only, compressed batches. See Blob & Object Storage |
| Content fingerprints | Checksum and SimHash | Key-value store and SimHash index | Exact and near-duplicate detection |
CREATE TABLE urls (
url_key text PRIMARY KEY, -- reversed host + path, e.g. 'com.example.www/docs/a?x=1'
url text,
host text,
status int, -- last HTTP status
etag text,
last_modified text,
content_sha256 blob, -- exact-duplicate check
simhash bigint, -- near-duplicate check
first_seen_at timestamp,
last_fetched_at timestamp,
last_changed_at timestamp,
revisit_secs int, -- current adaptive recrawl interval
next_fetch_at timestamp,
priority float, -- importance (link-based score, site quality)
depth int -- link hops from a seed: a trap signal
);5. High-level architecture
The crawl is a loop. The frontier decides which URL to fetch next under priority and politeness rules. Fetchers check robots.txt, resolve DNS through a cache and download the page. The parser extracts text and links; content goes through dedup into storage, and links go through the URL filter (normalize, check the seen set) back into the frontier. A recrawl scheduler re-enqueues known URLs when they are due. Press play on each flow.
6. Deep dive: the URL frontier
The frontier has two jobs that pull in opposite directions: fetch important URLs first, and never fetch from the same host too often. The classic design, from the Mercator crawler (Heydon and Najork, 1999), splits it into two layers of queues.
- Priority signals: link-based importance (PageRank-like scores), site quality, how often the page changes, depth from the seeds, and freshness demand (a news site's front page).
- Many more back queues than fetcher threads: Mercator suggested about three times as many, so a fetcher almost always finds a host that is ready.
- Disk-backed queues: only queue heads are in memory; the bulk lives in sequential files or an embedded store, which makes appends and pops cheap.
- Leases, not deletes: a URL handed to a fetcher is leased; if the fetcher crashes, the lease expires and the URL returns to its queue. See Message Queues & Pub/Sub.
7. Deep dive: politeness and robots.txt
Crawling too fast can take a small website down, get your crawler's IP ranges blocked, and in the worst case becomes a denial-of-service attack. Politeness is not optional: it is the constraint the whole frontier is built around.
| Rule | How the crawler applies it |
|---|---|
| One connection per host | Back queues make this structural: a host's queue is either in flight or waiting in the heap |
| A gap between requests | Commonly a multiple of the last fetch time (a slow server gets more breathing room), at least a floor such as 1 s |
| Per-IP limits | Thousands of small sites can share one shared-hosting IP; limit by IP as well as by hostname |
| Back off on 429 and 503 | Honor Retry-After; double the host's delay; pause the host after repeated errors |
| Crawl-delay | Non-standard; some crawlers honor it (Bing), others ignore it (Google sets rates from server responsiveness instead) |
| Identify yourself | A User-Agent like ExampleBot/2.1 (+https://example.com/bot) so site owners can learn about and contact you |
- 1
Fetch robots.txt first
Before the first page from a host, fetch
/robots.txtand cache the parsed rules. The Robots Exclusion Protocol was standardized as RFC 9309 in 2022. - 2
Match the most specific group
Use the group whose
User-agentmatches your crawler's name; fall back to*. - 3
Longest match wins
For a path, the matching
AlloworDisallowrule with the longest pattern applies; RFC 9309 saysAllowwins a tie. - 4
Handle errors carefully
A 4xx response (no file) means everything is allowed. A 5xx or network failure means assume everything is disallowed for now, and retry later.
- 5
Refresh periodically
RFC 9309 says crawlers should not use a cached copy for more than 24 hours unless the file is unreachable.
- 6
Respect page-level directives
<meta name="robots" content="noindex, nofollow">andrel="nofollow"links affect indexing and link following for that page.
8. Deep dive: DNS and fetching
Name resolution is a classic hidden bottleneck. A DNS lookup can take tens to hundreds of milliseconds, and standard library resolvers are often blocking with limited concurrency; the Mercator authors reported that DNS was a major bottleneck until they built their own multi-threaded resolver. Crawlers run a local caching resolver, issue lookups asynchronously, and prefetch DNS for hosts whose back queues are about to become ready. See Domain Name System (DNS).
- Async I/O: one fetcher process can keep thousands of connections open with an event loop; 12,000 in-flight requests need only a modest fleet.
- Timeouts and caps: connect timeout of a few seconds, total timeout of ~30 s, maximum body size (truncate beyond ~10 MB), and decompression limits to defuse gzip bombs.
- Redirects: follow a small number (say 5) or, better, treat the target as a new URL for the frontier so politeness and dedup apply to it.
- Conditional requests: send
If-None-Match/If-Modified-Since; a304 Not Modifiedcosts a few hundred bytes instead of the whole page. - Connection reuse: keep-alive and HTTP/2 reduce TLS handshakes when fetching several pages from the same host in sequence.
- JavaScript rendering: pages that build their content in the browser need a headless browser, which costs one to two orders of magnitude more CPU. Search engines run rendering as a separate, later stage only for pages that need it.
9. Deep dive: deduplication
URL dedup: normalize, then check a Bloom filter
The same page has many spellings: HTTP://Example.com:80/a/../b/?utm_source=x#top is http://example.com/b/. Normalize first, then test membership in the seen set. A Bloom filter answers 'definitely new' or 'probably seen' using about 10 bits per URL, with no false negatives. A false positive means a never-seen URL is wrongly skipped, which is an acceptable small loss for a crawler. See Bloom Filters & Probabilistic Structures.
from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
TRACKING = {"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
"gclid", "fbclid", "sessionid", "phpsessid", "jsessionid"}
MAX_URL_LENGTH = 2048
MAX_PATH_DEPTH = 16
def normalize(base: str, href: str) -> str | None:
url = urljoin(base, href.strip()) # resolves relative links and "../"
parts = urlsplit(url)
if parts.scheme not in ("http", "https"):
return None # mailto:, javascript:, ftp: ...
host = (parts.hostname or "").lower().rstrip(".")
if not host:
return None
default_port = 80 if parts.scheme == "http" else 443
netloc = host if parts.port in (None, default_port) else f"{host}:{parts.port}"
params = sorted((k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
if k.lower() not in TRACKING)
path = parts.path or "/"
if len(url) > MAX_URL_LENGTH or path.count("/") > MAX_PATH_DEPTH:
return None # likely a crawler trap
return urlunsplit((parts.scheme, netloc, path, urlencode(params), "")) # drop #fragmentContent dedup: checksums and SimHash
Different URLs often serve identical or almost identical content: mirrors, www and bare domains, print versions, pages that differ only in a timestamp or an ad. Studies of the web have repeatedly found that a large share of pages (often cited around a quarter to a third) are duplicates or near-duplicates. Detecting them saves storage, indexing work and crawl budget.
Exact checksum
- Hash the normalized text (SHA-256 or a 64-bit fingerprint)
- Catches byte-identical copies only
- One key-value lookup per page
- A changed timestamp or ad defeats it
SimHash
- 64-bit fingerprint where similar documents differ in few bits
- Near-duplicate if the Hamming distance is ≤ 3
- Google described using it for about 8 billion pages (2007)
- Fast lookups by splitting the fingerprint into blocks
MinHash shingling
- Estimate Jaccard similarity of word-shingle sets
- Pioneered by Broder at AltaVista (1997)
- Tunable with locality-sensitive hashing bands
- More storage per document than SimHash
- 1
Shingle
Split the page's visible text into overlapping word n-grams (for example 3 words).
- 2
Hash
Hash each shingle to 64 bits.
- 3
Vote
Keep 64 counters. For every shingle, add 1 to counter i if bit i of its hash is 1, otherwise subtract 1.
- 4
Fingerprint
Bit i of the SimHash is 1 if counter i ended positive. Changing a few shingles flips only a few bits.
- 5
Compare
Two pages are near-duplicates when their fingerprints differ in at most k bits (k = 3 for 64-bit fingerprints in Google's study).
10. Deep dive: recrawl scheduling
Pages change at wildly different rates: a news homepage changes every few minutes, a product page every few days, an academic paper never. Recrawling everything at the same rate wastes most of the budget. Instead, estimate each page's change rate from its history and adapt its revisit interval, then prioritize by how valuable a fresh copy is.
- Use free signals: XML sitemaps with
lastmod, RSS and Atom feeds, and push protocols such as IndexNow tell the crawler what changed without polling. - Conditional GETs make polling cheap, so frequent checks of rarely changing but important pages are affordable.
- Ignore boilerplate changes: compare the main-content checksum, not the raw bytes, so a rotating ad or timestamp does not count as a change.
- Split the budget: reserve capacity for discovery (new URLs) versus refresh (known URLs) and tune the ratio to the crawl's purpose.
11. Deep dive: crawler traps
| Trap | Example | Defense |
|---|---|---|
| Infinite calendars | /calendar?month=2026-12, next month link forever | Per-host page budget; depth limits; deprioritize URLs that differ only in a numeric parameter |
| Session IDs in URLs | /page;jsessionid=8F2A... on every link | Strip known session parameters; content dedup collapses the copies |
| Parameter permutations | Faceted search: color × size × sort × page | Sort and filter parameters; cap distinct URLs per path pattern |
| Ever-deeper paths | /a/b/a/b/a/b/... from relative links or symlink loops | Max URL length and path depth; detect repeating segments |
| Soft 404s | Every unknown URL returns 200 with 'not found' | Probe a random nonsense URL per host; dedup identical 'error' bodies |
| Hostile servers | Endless slow responses, gzip bombs, huge pages | Timeouts, size and decompression caps, per-host error budgets |
12. Distributed crawling and failures
Partition the work by host: hash each hostname with Consistent Hashing to a crawler node that owns that host's back queue, robots rules, DNS cache entries and politeness clock. Politeness then needs no cross-node coordination. Links discovered on one node that belong to hosts owned by another are batched and sent to the owner (for example through a Kafka topic partitioned by host hash).
- Seen-URL set: partition the Bloom filter and exact store by URL hash (or co-locate with the host owner) so each check is local.
- Node failure: frontier queues are durable and leases expire, so another node takes over the dead node's host range and resumes. See Heartbeats & Gossip Protocols.
- Hot hosts: a giant site (Wikipedia, a large news site) is still limited by politeness, so it cannot overload its owner node; the bottleneck is the crawl budget the site allows.
- Geographic placement: crawling from data centers near the target servers reduces latency, which raises per-host throughput under the same politeness gap.
- Downstream decoupling: fetched documents go to a stream that indexers, archivers and analytics consume at their own pace. See Batch & Stream Processing.
- Observability: pages per second, error rate by status code, per-host backoff counts, frontier size and duplicate rate show whether the crawl is healthy. See Observability.
Implementation
Each host has its own queue and a next-allowed time. A min-heap returns the host that may be contacted soonest; after each fetch the gap grows with slow responses and doubles on 429/503, and only one request per host is in flight.
class MinHeap<T> {
private items: T[] = [];
constructor(private less: (a: T, b: T) => boolean) {}
get size() { return this.items.length; }
peek(): T | undefined { return this.items[0]; }
push(x: T): void {
const a = this.items;
a.push(x);
for (let i = a.length - 1; i > 0; ) {
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop(): T | undefined {
const a = this.items;
const top = a[0];
const last = a.pop();
if (a.length > 0 && last !== undefined) {
a[0] = last;
for (let i = 0; ; ) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.less(a[l], a[m])) m = l;
if (r < a.length && this.less(a[r], a[m])) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
interface HostState { queue: string[]; nextAllowedAt: number; delayMs: number; inHeap: boolean; inFlight: boolean }
export class PolitenessScheduler {
private hosts = new Map<string, HostState>();
private ready = new MinHeap<{ at: number; host: string }>((a, b) => a.at < b.at);
constructor(private minDelayMs = 1_000, private maxDelayMs = 10 * 60_000) {}
add(url: string): void {
const host = new URL(url).host;
let h = this.hosts.get(host);
if (!h) {
h = { queue: [], nextAllowedAt: 0, delayMs: this.minDelayMs, inHeap: false, inFlight: false };
this.hosts.set(host, h);
}
h.queue.push(url);
if (!h.inHeap && !h.inFlight) {
this.ready.push({ at: h.nextAllowedAt, host });
h.inHeap = true;
}
}
/** The next URL that may be fetched now, how long to wait, or null if nothing is queued. */
next(now: number): { url: string; host: string } | { waitMs: number } | null {
const top = this.ready.peek();
if (!top) return null;
if (top.at > now) return { waitMs: top.at - now };
this.ready.pop();
const h = this.hosts.get(top.host)!;
h.inHeap = false;
h.inFlight = true; // one request per host at a time
return { url: h.queue.shift()!, host: top.host };
}
/** Report a finished fetch; schedules the host's next slot. */
done(host: string, now: number, fetchMs: number, status: number, crawlDelayMs = 0): void {
const h = this.hosts.get(host)!;
h.inFlight = false;
if (status === 429 || status === 503) h.delayMs = Math.min(h.delayMs * 2, this.maxDelayMs);
else h.delayMs = Math.max(this.minDelayMs, h.delayMs * 0.9); // recover slowly
h.nextAllowedAt = now + Math.max(h.delayMs, crawlDelayMs, 10 * fetchMs);
if (h.queue.length > 0) {
this.ready.push({ at: h.nextAllowedAt, host });
h.inHeap = true;
}
}
}Key takeaways
- The crawl loop is simple; the design lives in the frontier, which balances priority (front queues) against politeness (one back queue per host plus a heap of next-allowed times).
- Politeness caps throughput per host, so total throughput comes from crawling thousands of hosts in parallel.
- Obey robots.txt per RFC 9309: most specific user agent, longest match wins, cache for at most a day, and treat server errors as 'disallow for now'.
- Normalize URLs, then use a Bloom filter for the seen set: about 10 bits per URL, and false positives only cost a skipped page.
- Detect exact duplicates with checksums and near-duplicates with SimHash (Hamming distance ≤ 3 on 64 bits).
- Recrawl adaptively by observed change rate, use conditional GETs, cap per-host budgets against traps, and partition everything by host.
Common pitfalls
- A single global FIFO queue: it either hammers one host (many of its links are adjacent) or needs a global lock to stay polite.
- Synchronous DNS resolution, which quietly caps the whole crawler's throughput.
- Skipping URL normalization, so tracking parameters and session IDs multiply one page into thousands of URLs.
- Recrawling every page on the same schedule, wasting budget on static pages while news pages go stale.
- No per-host budget or depth limit, letting a calendar or faceted-search trap consume the crawl.
Interview tips
- Clarify the purpose (search, archive, dataset) and scale, then estimate fetch rate, bandwidth, storage and the seen-set size.
- Draw the Mercator frontier and explain why back queues hold exactly one host each.
- When you mention the Bloom filter, state its failure mode (false positives skip new URLs) and why that is acceptable here.
- Name at least three traps and their defenses; interviewers love this robustness discussion.
Real-world applications
- Search engines (Googlebot, Bingbot) crawl continuously with importance- and freshness-driven scheduling; Google has described rendering JavaScript pages in a separate stage after the initial fetch.
- Common Crawl publishes regular open crawls of billions of pages as WARC files, widely used for research and for training language models.
- The Internet Archive's Wayback Machine crawls for preservation, favoring completeness and exact snapshots.
- SEO auditors, price monitors and link checkers are small focused crawlers with the same politeness and dedup needs.
Practice problems
Test yourself
In a Mercator-style frontier, why does each back queue hold URLs from exactly one host?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.