Design a Web Crawler
Understanding the Problem
🕷️ What is a web crawler? A web crawler (or spider) is a program that discovers and downloads web pages automatically. It starts from a list of seed URLs, fetches each page, pulls out the links, and adds the new ones to its list of pages to visit. Search engines, archives, price trackers and LLM training pipelines all start with one. The hard part isn't fetching a page; it's fetching billions of them politely, without repeating work, and without getting lost in the infinite corners of the web.
You'll hear several versions of this question. The classic one is "design a distributed crawler for a search engine." A well-known twist asks you to crawl using 10,000 phones (or nodes) with no central server, which turns it into a peer-to-peer coordination problem. And a more recent version asks you to crawl the web to collect LLM training data, which changes what you keep and what you throw away. They share the same core loop (frontier, fetch, parse, dedup), so we'll design that first and cover each twist in the deep dives.
Functional Requirements
Core Requirements
- The crawler should start from a set of seed URLs, fetch pages, extract their links, and keep discovering and fetching new pages.
- The crawler should store each page's content and metadata for downstream consumers (a search indexer, a training data pipeline).
- The crawler should re-crawl pages over time so stored content stays reasonably fresh.
Below the line (out of scope)
- Indexing and ranking. The crawler hands pages to the indexer; see Design a Web Search Engine.
- Content behind logins or paywalls.
- Images, video and other media, beyond recording their URLs.
Non-Functional Requirements
Ask your interviewer how many pages and how fast. A standard target is 10 billion pages in about 5 days.
Core Requirements
- The crawler must be polite: obey
robots.txt, and never send a single site more than about one request per second unless it says otherwise. - The crawler should sustain about 25k pages per second (10B pages / 432,000 seconds ≈ 23k/s).
- The crawler should not fetch the same URL twice in a crawl cycle, and should not store the same content twice.
- The crawler should be fault tolerant: losing a machine loses no more than a few minutes of work, and nothing has to restart from scratch.
- The crawler should be robust to the hostile parts of the web: malformed HTML, endless calendar pages, slow servers, and sites that generate infinite URLs.
Below the line (out of scope)
- Ranking which pages matter beyond simple priorities.
- Low-latency discovery (finding a new page within seconds). That's a news-style crawler; see Design a News Aggregator.
Now the numbers. At 23k pages a second and an average page of around 100 KB of HTML, we download about 2.3 GB/s, roughly 18 Gbps. Storing 10B pages raw is 1 PB; compressed, more like 200 TB. Those are big but ordinary numbers: a few dozen machines with 1-10 Gbps links can do the fetching.
The surprising number is on the other side. Each page has on the order of 50 outgoing links, so the crawler has to answer "have we seen this URL before?" about 50 × 23k ≈ 1.2 million times a second. And because of the politeness rule, the 23k fetches per second have to be spread over at least 23k different hosts at any moment, each with its own clock.
This is the shift most candidates miss. Bandwidth and parsing scale by adding machines. The real design problems are the URL frontier (what to fetch next, without hitting any site too hard) and deduplication (a million membership checks a second against billions of URLs).
The Set Up
Planning the Approach
We'll build the crawl loop first, then split fetching from parsing so each can scale and retry on its own, then add re-crawling. The deep dives cover politeness, dedup, scaling and fault tolerance, and the two twists.
Defining the Core Entities
- URL record: a normalized URL with its host, priority, last fetch time, last content hash and next scheduled fetch time. There's one for every URL we know about, fetched or not.
- Frontier: the set of URLs waiting to be fetched, organized so we can pick the next one quickly while respecting each host's rate limit.
- Host: a domain (or IP) with its cached
robots.txtrules, crawl delay and the earliest time we may hit it again. - Page: the fetched content: raw HTML in blob storage, plus the extracted text, outgoing links, status code and a content hash.
API or System Interface
A crawler has no user-facing API. Its interfaces are internal: how URLs get in, and how pages get out.
// Input
POST /seeds { urls: [...], priority } // operator adds seeds
// Frontier (internal)
enqueue(url, priority)
dequeue(fetcherId) -> { url, host } // only returns a URL whose host is allowed now
// Output: one event per fetched page, on a Kafka topic
page_fetched { url, finalUrl, status, fetchedAt, s3Key, contentHash, outlinks: [...] }
Downstream consumers (an indexer, a training-data pipeline) subscribe to page_fetched and read content from S3. The crawler doesn't need to know who they are.
Data Flow
- Take a URL from the frontier.
- Resolve its host (DNS), check
robots.txt, fetch it. - Store the raw response, extract text and links.
- Normalize each link, drop the ones we've already seen, add the rest to the frontier.
- Schedule the page's next re-crawl.
High-Level Design
1) The crawler should fetch pages and keep discovering new ones
The simplest crawler is a queue and a pool of workers. Seed URLs go on the queue. Each worker pulls a URL, downloads it, saves the HTML to S3, parses out the links, and pushes them back onto the queue.
This works for a few thousand pages, and it shows the loop. At our scale, it has four problems:
- No politeness. Links on a page mostly point to the same site. The queue fills up with thousands of URLs from one host, and dozens of workers hit it at once.
- No dedup. Every page that links to the homepage re-adds it, so popular URLs get fetched over and over, and cycles never end.
- Fetching and parsing are tied together. If the parser crashes on bad HTML, we lose the fetch and do it again. Fetching is network-bound and parsing is CPU-bound, so they want different machines.
- No memory. We can't re-crawl, because nothing records what we fetched or when.
We'll fix the last two now and leave politeness and dedup for the deep dives.
2) The crawler should store each page's content and metadata
Split the worker into stages connected by queues:
- Fetchers pull a URL from the frontier, resolve DNS, check
robots.txt, download the page with a timeout and a size cap (say 10 seconds and 5 MB), and write the raw response to S3 under a key derived from the URL hash and fetch time. They then publish a smallfetchedmessage (URL, status, S3 key) to Kafka. Fetchers do no parsing, so a single machine with asynchronous I/O can keep thousands of connections open at once. - Parsers consume
fetchedmessages, read the HTML from S3, extract the main text, title, language and outgoing links, and compute a content hash. They write the extracted text to S3 and the metadata to a URL table, and publishpage_fetchedfor downstream consumers. - A Link Filter takes the outgoing links, normalizes them, drops ones we've already seen, and adds new ones to the frontier.
Because the raw HTML is in S3 before parsing starts, a parser failure just means the message is redelivered and parsed again. We never re-download a page because of a bug in our own code, and we can re-run a new parser over old crawls.
The URL table is large (tens of billions of rows) and simple (lookup by URL, update after each fetch), so a wide-column or key-value store fits: Cassandra, Bigtable or DynamoDB, keyed by a hash of the normalized URL.
3) The crawler should re-crawl pages to keep content fresh
Every URL record carries a next_fetch_at. A Re-crawl Scheduler scans for URLs that are due (the URL table is partitioned, so each scheduler instance scans its own partitions) and puts them back on the frontier with an appropriate priority.
How often should we re-crawl? Pages change at very different rates: a news homepage changes every few minutes, a 2014 blog post almost never. So we adapt:
- When a re-fetch returns the same content hash, double the interval (up to a cap, say 60 days).
- When the content changed, halve it (down to a floor, say 1 hour for important pages).
- Start new pages at a default (say 7 days) and adjust from there.
Re-crawls also use conditional requests. We store the ETag and Last-Modified headers from the last fetch and send them back as If-None-Match and If-Modified-Since. A server that supports them replies 304 Not Modified with no body, which saves bandwidth for both sides.
Potential Deep Dives
1) How do we keep the crawler polite?
Politeness is a hard requirement, not a nice-to-have. An impolite crawler gets blocked, and it can hurt small sites badly. It has three parts: obey robots.txt, limit the rate per host, and back off when a site struggles.
robots.txt is the easy part. Fetch it once per host, cache it for about a day, and check every URL against it before fetching. Honor Crawl-delay when it's present, and identify the crawler with a clear user agent and a contact URL so site owners can reach us or block us specifically.
Rate limiting per host is the hard part, because it has to be enforced across thousands of fetchers.
Bad Solution: A Global Rate Limit
Approach
Cap the total fetch rate and hope that spreading it over many sites keeps any one site safe.
Challenges
It doesn't. URLs arrive in clumps from the same site (a page's links mostly point back to its own host), so the queue regularly holds long runs of one host, and the fetchers hit it together. A global limit doesn't protect any individual site.
Good Solution: A Shared Per-Host Lock
Approach
Before fetching, a fetcher asks Redis for permission: SET host:{h} 1 NX PX 1000. If the key was set, the fetcher may hit the host now, and nobody else can for one second. If not, it puts the URL back and takes another.
Challenges
It's correct, but wasteful. When the frontier is clumped, most dequeued URLs belong to hosts that were just fetched, so fetchers spend their time pulling URLs, failing the check and putting them back. That's also around 25k+ Redis calls a second just for permission checks, many of them failures. The frontier should never hand out a URL that can't be fetched yet.
Great Solution: A Frontier with One Queue per Host
Approach
Organize the frontier around hosts, in two layers:
- Priority queues (a handful, from high to low). New URLs go in by priority: seeds and high-value sites first, deep pages of obscure sites last.
- Per-host queues. A router pulls from the priority queues (more often from the high ones) and appends each URL to the queue for its host. Each per-host queue holds only that host's URLs.
- A ready heap keyed by each host's
next_allowed_time. A fetcher asking for work pops the host at the top of the heap (the one whose wait has ended first), takes one URL from that host's queue, and pushes the host back into the heap withnext_allowed_time = now + delay.
The delay is per host: by default about 1 second, or the site's Crawl-delay, or a multiple of how long its last response took (a slow server gets a longer gap). By construction, a host is never handed to two fetchers at once and never sooner than its delay.
Backoff is just a change to the delay. On a 429 or 503, multiply the host's delay (honoring Retry-After when present). On timeouts or connection errors, back off further, and after a run of failures, park the host for hours.
Challenges
The per-host queues hold billions of URLs, far more than memory. Keep the head of each queue in memory and the rest on local disk (RocksDB works well, keyed by host + sequence), refilling as the head drains. Also, a host isn't quite the right unit: many small sites share one IP on a shared hosting provider, and hitting 500 of them at once hits one server. Large crawlers also cap concurrent requests per IP, using the DNS results they already have.
One host can only be crawled about once a second, so one host with 10 million pages takes 115 days at that rate. A crawl-time target of "5 days" only works because the web is spread over hundreds of millions of hosts. Say this when you discuss politeness: it explains why the frontier has to keep many thousands of hosts active at once.
2) How do we avoid fetching the same URL, or storing the same page, twice?
There are two kinds of duplicates: the same URL reached through different links, and different URLs that return the same content.
URL normalization comes first, so trivially different strings become the same URL: lowercase the scheme and host, remove default ports (:80, :443), resolve . and .. segments, drop the #fragment, sort query parameters, and strip known tracking parameters like utm_source. Respect <link rel="canonical"> when the page provides it.
Then we need a "have we seen this URL?" check at about 1.2M lookups per second.
Bad Solution: Check the URL Table
Approach
Look up each normalized link in the URL table, and add it to the frontier only if there's no row.
Challenges
That's a million random reads a second against a table of tens of billions of rows, almost all of them misses or hits on URLs we've seen many times. Cassandra can do it with enough nodes, but we'd be paying for a large cluster to answer a yes/no question.
Good Solution: A Bloom Filter
Approach
A Bloom filter is a bit array plus k hash functions. Adding a URL sets k bits; checking a URL tests them. If any bit is 0, the URL is definitely new. If all are 1, it's probably been seen. At about 10 bits per element and 7 hash functions, the false positive rate is about 1%. For 10 billion URLs that's 100 billion bits, around 12 GB, which fits in the memory of one large machine, or comfortably across a few.
Challenges
False positives mean we silently skip about 1% of genuinely new URLs. For a search crawler that's usually acceptable (important pages have many inbound links, so they get rediscovered through other paths), but it should be a conscious choice. Bloom filters also can't delete entries, and the filter has to survive a restart, so we checkpoint it to disk periodically.
Great Solution: Partitioned Seen-Sets Next to the Frontier
Approach
Partition everything by host. Each crawler node owns a slice of the hosts (more on how in the next deep dive) and keeps the seen-set for its hosts locally: a Bloom filter in memory in front of an exact set on local disk (RocksDB keyed by URL hash). A Bloom "no" (the common case for genuinely new URLs) is answered in memory; a Bloom "yes" is confirmed against RocksDB, so we don't lose the 1%. Each node only handles the lookups for its own hosts, so the 1.2M/s is split across all nodes, and there's no central dedup service to scale.
Challenges
Links for hosts owned by another node have to be forwarded there, which is cross-node traffic. Batching helps a lot: buffer outgoing links per destination node and send them every second or so.
Content dedup is the other half. Many URLs serve the same content: http and https versions, session IDs in URLs, mirrors, syndicated articles. The parser hashes the extracted main text (SHA-256) and checks it against a content-hash index. If it already exists, we record the URL as a duplicate pointing to the original and don't store or index it again. Near-duplicates (the same article with a different sidebar or date) need a similarity hash: SimHash produces a 64-bit fingerprint where similar documents differ in only a few bits, so two pages within, say, 3 bits are treated as duplicates. MinHash is the other common choice, and it comes up again for training data below.
Spider traps are the last kind of duplicate work: URLs that are endlessly different but worthless, like a calendar with a "next month" link forever, or a site that appends a session ID to every link. Defend with simple limits: a maximum URL length (around 2,000 characters), a maximum path depth, a cap on pages per host per crawl cycle (scaled by the host's importance), and detection of repeating path segments (/a/b/a/b/a/b/).
3) How do we scale across machines and survive failures?
At 23k pages a second, a few dozen fetcher machines handle the bandwidth, but the frontier and the seen-set are stateful. How do we split them up?
Partition by host. Hash each host to one of N crawler nodes. A node owns its hosts' per-host queues, their seen-set, their robots.txt cache and their politeness clocks. This one choice makes politeness local (only one node ever fetches a given host, so there's no cross-node rate limiting) and dedup local (all of a host's URLs land on the same node). It's also good for connection reuse, since one node keeps an HTTP/2 or keep-alive connection open to the hosts it fetches.
Use consistent hashing rather than hash(host) % N, so adding or removing a node moves only about 1/N of the hosts instead of almost all of them. A small coordination service (ZooKeeper or etcd) holds the node list; every node watches it and computes the ring itself.
DNS deserves a mention. At 23k fetches a second, a public resolver would rate-limit us quickly, and a slow lookup stalls the fetch. Run a caching resolver on every node (or a shared resolver cluster), cache records for their TTL, and resolve the next few hosts in the ready heap ahead of time.
Fault tolerance. We need to lose as little as possible when a node dies:
- The frontier's on-disk state (per-host queues, seen-set) is checkpointed every few minutes to S3, along with the Bloom filter.
- Links forwarded between nodes go through Kafka, partitioned by owning node, rather than direct RPC. If a node is down, its links wait in Kafka instead of being lost.
- When a node dies, its range of the ring moves to its neighbors. They load the latest checkpoint for those hosts and replay Kafka from the checkpoint's offset. A few minutes of fetches might be repeated, which is harmless: every write in the pipeline is keyed by URL, so repeats are idempotent.
Interviewers often ask "what happens if a crawler node dies mid-crawl?" A strong answer names what state the node held (queues, seen-set, politeness clocks), where it's checkpointed, and why replaying a few minutes of work is safe (idempotent writes keyed by URL).
4) What if we have to crawl with 10,000 phones and no central server?
This twist changes the constraints: 10,000 devices, each with modest bandwidth, limited storage and battery, unreliable connectivity, and no central coordinator to own the frontier or assign work. Devices can talk to each other, and we want each URL crawled exactly once with as little communication as possible.
The partition-by-host idea carries straight over. What's missing is the central service that tells everyone who owns what.
Bad Solution: Broadcast Every Discovered URL
Approach
When a device finds a URL, it tells all the others, and they agree who takes it.
Challenges
With 10,000 devices and 50 links per page, every page generates 500,000 messages. It doesn't scale, and "agree who takes it" is itself a consensus problem.
Good Solution: Static Hash Assignment
Approach
Give every device the same list of all 10,000 device IDs at startup. The owner of a URL is hash(host) % 10000. Every device can compute ownership locally, with no messages. A device crawls only URLs whose host it owns, and sends every other discovered link directly to its owner (batched). Each device keeps its own frontier and seen-set for its hosts.
Challenges
Phones go offline constantly. When device 4,217 drops, nobody crawls its hosts, and links sent to it are lost. And because the assignment is modular, there's no way to hand its hosts to someone else without changing % 10000 to % 9999, which reassigns nearly every host.
Great Solution: Consistent Hashing with Gossip and Replicas
Approach
Put the devices on a consistent hash ring (several virtual positions per device to even out the load). A host is owned by the first device clockwise from its hash.
- Membership by gossip. Each device periodically exchanges its view of who's alive with a few random peers. Within a few seconds to a minute, every device learns about joins and failures, with no central server. A device that misses heartbeats for long enough is marked dead, and its ring positions are removed.
- Successor replicas. A device's frontier and seen-set are small (10B URLs / 10,000 devices ≈ 1M URLs each), so each device also sends its state changes to the next one or two devices on the ring. When it dies, its successor already holds its hosts' frontier and takes them over immediately.
- Batched forwarding. Buffer outbound links by destination and send them every few seconds; drop links already seen by a local Bloom filter of recently forwarded URLs, so popular URLs aren't sent over and over. Messages carry the sender's ring version, so a receiver that no longer owns a host can forward it on.
- Content goes straight to storage. Phones don't keep pages. Each one uploads fetched pages directly to object storage with pre-signed URLs (or to a nearby peer acting as storage), keeping only the frontier locally.
- Device-aware scheduling. Only crawl while charging and on Wi-Fi, and let each device pull at its own pace, so a slow phone simply crawls its hosts more slowly rather than holding anything up.
Challenges
Gossip is eventually consistent, so for a short time two devices might both think they own a host, and fetch a URL twice. That's tolerable (dedup at storage by URL and content hash catches it). Detecting that the crawl is finished is harder without a coordinator: a device can be idle now and receive new links later. Distributed termination detection works, but in practice a crawl like this is time-boxed rather than run to completion. Ask your interviewer whether some lightweight bootstrap service (to hand out the initial peer list and seed URLs) is allowed. It usually is, as long as it isn't in the crawl's critical path.
The key insight interviewers look for here: ownership must be computable locally by everyone, from shared knowledge, with no lookup. Consistent hashing gives you that, and it degrades gracefully when nodes come and go.
5) How does crawling for LLM training data change the design?
The crawl loop is the same, but the goal is different. A search crawler wants coverage and freshness: every important page, re-crawled often. A training-data crawler wants a large amount of high-quality, deduplicated, legally usable text, and it's fine with a snapshot that's months old. That moves the effort from fetching to filtering.
Respect opt-outs, strictly. Training crawlers should use a distinct, documented user agent so site owners can allow or block them separately from search crawlers in robots.txt, and the crawler must honor it. Honor noai-style meta tags and other opt-out signals the team commits to, keep a domain-level blocklist (sites that requested removal, known personal-data sites), and record provenance (URL, fetch time, the robots.txt that applied) for every document so it can be removed later.
Prioritize differently. Seed from high-quality sources (reference sites, documentation, books, forums with good answers), and prioritize by a page-quality score rather than link popularity alone. Re-crawl rarely; most text doesn't need to be fresher than one snapshot.
Filter in a separate pipeline. The parsers publish raw extracted text; a batch pipeline (Spark over S3) does the expensive work in stages, each cutting the data down:
- Extraction: strip navigation, ads and boilerplate, keep the main text.
- Language identification with a fast classifier, so each language can be handled and sampled on purpose.
- Quality filtering: heuristics (too short, too many symbols, too repetitive) plus a small classifier trained to tell high-quality text from spam and machine-generated junk.
- Safety and privacy: remove or mask personal information like emails and phone numbers, and filter toxic content.
- Deduplication at scale: exact dedup by hash, then near-dedup with MinHash and locality-sensitive hashing (LSH). MinHash estimates the overlap between two documents' sets of word n-grams; LSH groups documents whose signatures share a band so that only candidate pairs are compared, instead of all pairs. Duplicate text causes models to memorize it, so this step matters more than for search.
JavaScript-heavy pages matter more here, since a lot of modern text is rendered client-side. Use a pool of headless browsers for pages where the static HTML has little text, but treat them as a small, expensive tier: rendering costs on the order of 10-100x a plain fetch.
If you're asked about LLM data specifically, lead with opt-out compliance and dedup. Interviewers want to hear that you know the legal and quality issues dominate, not that you can download pages faster.
Final Design
The full flow:
- Seeds and re-crawl candidates enter the frontier with a priority. Each crawler node owns a slice of hosts by consistent hashing, with membership in ZooKeeper or etcd.
- On each node, priority queues feed per-host queues; a heap of next-allowed times hands fetchers only hosts that may be hit now, after checking cached
robots.txtrules. - Fetchers resolve DNS through a local cache, download with conditional requests, timeouts and size caps, write raw responses to S3, and publish a
fetchedevent to Kafka. - Parsers extract text and links, dedup content by hash and SimHash, update the URL table (Cassandra), and publish
page_fetchedfor the indexer or the training-data pipeline. - Links are normalized and forwarded through Kafka to the node that owns their host, which checks its Bloom filter and exact seen-set before adding new URLs to its frontier.
- The Re-crawl Scheduler re-enqueues URLs whose
next_fetch_athas passed, with intervals that adapt to how often each page changes. Frontier state is checkpointed to S3 so a failed node's hosts can be taken over quickly.
What is Expected at Each Level?
Mid-level
You should get the basic loop right (frontier, fetch, parse, enqueue links), store pages in blob storage, and recognize that duplicates and politeness need handling. With prompting, you should propose robots.txt checks, a per-host delay and some way of tracking seen URLs, and separate fetching from parsing.
Senior
You should do the math and identify the frontier and dedup as the real problems. Expect to design a host-partitioned frontier with per-host queues and a ready heap, size a Bloom filter and discuss its false positives, describe content dedup with hashes and near-duplicates, and explain how state is checkpointed and recovered when a node fails. You should handle the P2P twist with consistent hashing.
Staff+
You should talk about the crawler as a long-running system with trade-offs between coverage, freshness, politeness and cost: how to prioritize the frontier, adapt re-crawl intervals, handle shared-IP hosting, and defend against traps. For the P2P version, expect gossip, replication to successors, and an honest discussion of termination. For LLM data, you should put compliance, provenance and dedup quality first and explain why they shape the architecture.