Web crawlers (also known as spiders or bots) are automated scripts that systematically browse the World Wide Web. While search engines like Google or Bing are the most famous use cases, crawlers are also essential for copyright infringement detection, web archiving, and data mining for training large language models.
Designing a web crawler is a classic system design interview question. It tests your ability to handle massive scale, manage distributed queues, and deal with the unpredictable nature of the internet.
Requirements (functional and non-functional)
Before jumping into the architecture, we need to align with the interviewer on what exactly we are building. A crawler for a specialized pricing engine will look very different from a general-purpose search engine crawler.
Functional Requirements
- Seed URLs: The system should accept a list of starting URLs to begin the crawl.
- Fetching: It must download web pages, extract links, and recursively fetch new URLs.
- Storage: The crawler must store the downloaded HTML content for downstream processing (like indexing).
- Robots.txt compliance: The system must respect the rules defined in a website's
robots.txtfile.
Non-functional Requirements
- Scalability: The internet is massive. The system should be able to crawl billions of pages efficiently.
- Politeness: The crawler must not overwhelm target servers. It should rate-limit requests to the same domain.
- Fault Tolerance: Crawls can take weeks. If a node crashes, the system must recover without losing significant progress.
- Deduplication: The system must avoid crawling the same URL twice and should detect duplicate content to save storage.
Capacity estimates
Let us assume our goal is to crawl 1 billion pages per month.
Throughput:
- 1 billion pages / 30 days / 24 hours / 3600 seconds = ~400 pages per second (QPS).
- Peak QPS might be 2x or 3x this, so let's design for 1,000 QPS.
Storage:
- Assume the average size of a web page is 2 MB (including HTML and extracted metadata).
- 1 billion pages * 2 MB = 2 Petabytes (PB) per month.
- If we store data for 5 years, we need 120 PB of storage.
Bandwidth:
- Ingress: 400 pages/sec * 2 MB = 800 MB/sec (or 6.4 Gbps).
- This requires a robust network infrastructure, likely spread across multiple data centers.
Memory for URL Deduplication:
- If we use a Bloom filter for 1 billion URLs, assuming a false positive rate of 0.1%, we need about 1.44 bytes per URL.
- 1 billion * 1.44 bytes = ~1.44 GB of RAM. This easily fits in memory on a single machine, though we will likely distribute it.
API design
While a crawler is primarily a background job system, we need administrative APIs to manage the crawl process.
POST /v1/crawl/seeds
Adds new seed URLs to the crawler.
- Body:
{"urls": ["https://example.com", "https://curebugs.com"]} - Response:
202 Accepted
GET /v1/crawl/status
Retrieves the current health and metrics of the crawler.
- Response:
{"pages_crawled": 1500000, "active_workers": 50, "queue_size": 12000000}
Data model
We need to store three main types of data: the URL frontier (queue), the downloaded documents, and the deduplication state.
| Data Type | Storage Choice | Justification |
|---|---|---|
| URL Frontier | Redis / Kafka / Custom DB | Needs high-throughput enqueuing and dequeuing. A custom disk-backed queue or Redis is common. |
| Document Storage | Object Store (S3, GCS) | 120 PB of unstructured HTML blobs is best suited for cheap object storage. |
| Document Metadata | NoSQL (Cassandra / DynamoDB) | Fast lookups for document metadata (URL, timestamp, content hash) using the URL hash as the partition key. |
| Deduplication Cache | RAM (Bloom Filter) + Redis | Extremely fast lookups to check if a URL has been seen. |
High-level architecture
Here is the end-to-end flow of our web crawler:
- URL Frontier: Stores URLs to be downloaded. It prioritizes URLs and ensures politeness.
- Fetcher: Pops URLs from the frontier, resolves the IP address via DNS, and downloads the HTML.
- Content Parser: Validates the HTML and extracts text/links.
- Content Deduplication: Checks if the exact or near-exact content has been stored before.
- Link Extractor & Filter: Pulls
hreftags, normalizes them (e.g., resolving relative paths), and filters out blacklisted domains or unsupported file types (like.pdfor.png). - URL Deduplication: Checks if the new URLs have already been crawled or are already in the frontier.
Deep dives
Let us explore the most complex parts of the system: Politeness, Deduplication, and DNS Resolution.
1. The URL Frontier and Politeness
The URL Frontier is not just a simple FIFO queue. If we use a standard queue, we might dequeue 100 URLs from wikipedia.org in a row. Fetching them simultaneously would bombard Wikipedia's servers, effectively launching a Distributed Denial of Service (DDoS) attack. This violates our politeness requirement.
To solve this, we implement a Politeness Framework using a two-tier queue system (often attributed to the Mercator crawler architecture):
- Front Queues (Prioritization): URLs are assigned a priority (e.g., based on PageRank, update frequency, or domain authority). High-priority URLs go into higher-priority queues.
- Back Queues (Politeness): Each back queue is strictly assigned to a single domain (e.g., Queue 1 only has
apple.comURLs, Queue 2 only hascurebugs.comURLs). - Heap/Timer: A min-heap tracks the earliest time each back queue can be accessed again. If a worker wants a URL, it pulls from the heap. If the required delay hasn't passed, the worker waits.
Here is a simplified implementation of a Politeness Queue manager:
import time
from collections import deque
import heapq
class PolitenessQueue:
def __init__(self, delay_seconds):
self.domain_queues = {}
self.next_allowed_time = [] # Min-heap of (timestamp, domain)
self.delay = delay_seconds
def add_url(self, domain, url):
if domain not in self.domain_queues:
self.domain_queues[domain] = deque()
heapq.heappush(self.next_allowed_time, (time.time(), domain))
self.domain_queues[domain].append(url)
def get_next_url(self):
if not self.next_allowed_time:
return None
# Peek at the domain that can be crawled next
earliest_time, domain = self.next_allowed_time[0]
now = time.time()
if now < earliest_time:
time.sleep(earliest_time - now)
# Pop the domain, get the URL
heapq.heappop(self.next_allowed_time)
url = self.domain_queues[domain].popleft()
# Re-insert the domain into the heap with the new allowed time
if self.domain_queues[domain]:
heapq.heappush(self.next_allowed_time, (time.time() + self.delay, domain))
return url2. Deduplication Strategies
Crawlers face two types of duplication: URL duplication (seeing the same link multiple times) and Content duplication (different URLs pointing to the exact same content, like example.com/product and example.com/product?ref=twitter).
URL Deduplication: Storing 1 billion URLs in a traditional database index and querying it for every extracted link would cripple our throughput. Instead, we use a Bloom Filter.
- A Bloom filter is a probabilistic data structure that tells us if an element is definitely not in the set, or possibly in the set.
- If the Bloom filter says "not seen", we safely add the URL to the frontier.
- If it says "possibly seen", we do a slower fallback check against our NoSQL database to confirm.
Content Deduplication: To detect exact duplicates, we can hash the HTML content (using MD5 or SHA-256) and store the hash. However, web pages often have dynamic timestamps, ads, or slightly different headers. To detect near-duplicates, we use algorithms like SimHash or MinHash (Locality Sensitive Hashing). These algorithms generate similar hashes for similar documents. If the Hamming distance between two SimHashes is below a certain threshold, we flag them as duplicates and discard the new one.
3. DNS Resolution Bottleneck
Every time the fetcher requests a URL, it must resolve the domain name to an IP address. DNS operates over UDP and can take anywhere from 10ms to 200ms. If a worker thread blocks on DNS resolution, our throughput plummets.
Solution:
- Local DNS Cache: Maintain a local cache (like
dnsmasq) on every worker node. - Custom DNS Client: Standard OS DNS resolvers are synchronous. We should use asynchronous DNS libraries to resolve multiple IPs concurrently without blocking worker threads.
- Cron Updates: Periodically refresh the IP addresses of popular domains in the background.
Bottlenecks and trade-offs
- Network I/O vs. CPU: Crawling is heavily I/O bound (waiting for network responses). However, content parsing and SimHash calculations are CPU bound. Trade-off: We should separate fetcher workers (high network, low CPU) from parser workers (low network, high CPU) so we can scale them independently.
- Storage vs. Compute: Storing 120 PB of raw HTML is expensive. We can compress the HTML (e.g., using GZIP or Brotli) before storing it in S3. Trade-off: Compression saves massive amounts of storage costs but increases CPU utilization on the worker nodes.
- Strict vs. Loose Politeness: If we strictly wait 5 seconds between requests to a domain, crawling a massive site like Amazon could take years. Trade-off: We can dynamically adjust the politeness delay based on the target server's response times. If the server responds in 50ms, we might lower the delay. If we get
429 Too Many Requests, we exponentially back off.
Questions an interviewer will ask next
1. How do you handle spider traps?
A spider trap is a web page designed to create infinite loops for crawlers (e.g., a calendar that lets you click "Next Month" infinitely).
Answer: We mitigate this by setting a strict maximum depth limit for URLs. We also limit the maximum length of a URL string and use pattern matching to detect repeating directories (e.g., site.com/a/b/a/b/a/b).
2. How do you crawl dynamic, JavaScript-heavy sites (like React/SPA)? Traditional crawlers only see the initial empty HTML shell. Answer: We can use headless browsers (like Puppeteer or Playwright) to render the JavaScript. However, this is extremely resource-intensive. A hybrid approach is best: only use headless browsers for domains that are known to require it, or if the initial HTML lacks meaningful content.
3. How do you keep the search index fresh? Pages change over time. How do we know when to recrawl? Answer: We implement a recrawl queue. We predict the change frequency of a page based on historical data (e.g., a news homepage changes hourly, an old blog post changes rarely). We prioritize recrawling based on this predicted frequency combined with the page's overall popularity (PageRank).