Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 51

Building a Scalable Web Crawler: Politeness, Duplication, and Google-Specific Considerations

This lesson is built with resources from youtube.com, hellointerview.com and 1 more site.

Hello! Welcome to your next lesson on designing core infrastructure systems.

In our last lesson, we designed a highly-performant search autocomplete system. We saw how a specialized data structure, the Trie, combined with an offline processing pipeline, could serve suggestions at massive scale with very low latency. Today, we'll design the system that provides the raw data for a service like Google Search in the first place: a web crawler.

This lesson directly addresses your requested deep dive, which is a core problem for companies like Google: Design a web crawler, addressing politeness, deduplication, and scalability.

For a Staff-level interview, a correct answer goes far beyond a simple script that fetches pages. It requires a distributed, fault-tolerant system that can navigate the messy, vast, and sometimes uncooperative landscape of the public internet. We will focus on the trade-offs and design patterns required to build such a system.

1. Understanding the Problem: Requirements and Scale

A web crawler is a bot that systematically browses the web, typically for the purpose of web indexing. It starts with a list of "seed" URLs and recursively follows the links on those pages to discover and download new ones. Our goal is to extract and store the text content from these pages, which could later be used to build a search index or train a large language model (LLM).

Let's begin by establishing the functional and non-functional requirements, which are crucial for scoping the problem.

Design a Web Crawler

The article 'Design a Web Crawler' from Hello Interview provides an excellent breakdown of typical requirements for this problem. Let's use it to frame our discussion.

Please read the sections 'Understanding the Problem' and 'Non-Functional Requirements'. Pay close attention to the scale (10 billion pages) and the time constraint (5 days), as these will heavily influence our architectural decisions.

Based on this, our core requirements are:

  • Functional:
    1. Crawl the web starting from a set of seed URLs.
    2. Extract text from each page.
    3. Store the extracted text.
  • Non-Functional:
    1. Scalability: Handle 10 billion pages.
    2. Efficiency: Complete the crawl in under 5 days.
    3. Politeness: Be a "good citizen" of the internet; don't overload websites.
    4. Fault Tolerance: The system must be resilient to failures of its own components and external websites.

Before drawing any boxes and arrows, a key Staff-level practice is to perform back-of-the-envelope calculations to grasp the magnitude of the problem. This justifies the need for a distributed system.

Design a Web Crawler System Design Interview w/ a Ex-Meta Staff Engineer

This video from a former Meta Staff Engineer provides a great walkthrough of the kind of quantitative reasoning expected in an interview. He calculates the number of machines needed to meet the strict 5-day deadline.

Watch the segment from 43:25 to 47:45. The key takeaway is how to reason from the total number of pages and average page size to the required network bandwidth and, finally, to the number of crawler machines needed. Note the hand-wavy but justified assumption about usable bandwidth.

The estimation reveals that even with highly network-optimized machines, we need a small fleet of them running in parallel. This confirms our need for a distributed architecture right from the start.


2. High-Level Architecture & Data Flow

Let's start with a simple, foundational architecture that follows a basic data flow.

Web Crawler Architecture Diagram
A high-level view of a web crawler's architecture. At its core is a 'URL Frontier' that manages URLs to be crawled, 'Fetchers' that download content, and 'Parsers' that extract data and new links. Source: Medium

This architecture can be broken down into a simple, iterative flow:

  1. URL Frontier: A queue holding all URLs we intend to crawl, initialized with seed URLs.
  2. Fetcher (Crawler): A worker that takes a URL from the frontier.
  3. DNS Resolution: The fetcher resolves the URL's domain to an IP address.
  4. Download: The fetcher downloads the page's raw HTML content.
  5. Parser: A worker that processes the HTML.
    • It extracts the text content and stores it in a blob store (like S3).
    • It extracts all hyperlinks (<a> tags) found on the page.
  6. Loop: The newly discovered URLs are added back to the URL Frontier.

This basic flow works conceptually, but a single worker type doing everything is inefficient and fragile. For a robust system, we must break this into a multi-stage pipeline.


3. A Robust, Pipelined Architecture

A core principle in designing large-scale data processing systems is the separation of concerns. Fetching a webpage is a network-I/O-bound task that is prone to failure (timeouts, server errors). Parsing HTML is a CPU-bound task that is generally more reliable. Mixing them complicates scaling and error handling.

A better approach is a pipelined architecture with distinct services and message queues connecting them.

Design a Web Crawler System Design Interview w/ a Ex-Meta Staff Engineer

Let's refine our initial design. The same Hello Interview video explains the rationale for splitting the crawler into a 'fetch' stage and a 'parse' stage, connected by queues.

Watch the section on 'Fault Tolerance' from 19:38 to 27:37. Focus on: The motivation for splitting the monolithic crawler into a Fetcher and a Parser. How this split allows for independent scaling and better fault isolation. The use of message queues (like SQS) with features like exponential backoff and dead-letter queues (DLQs) to handle transient network failures gracefully.

This leads to a more robust design:

  1. URL Frontier (SQS Queue): Contains URLs to be fetched.
  2. Fetcher Service: A pool of workers that:
    • Pulls a URL from the Frontier.
    • Downloads the raw HTML.
    • Saves the raw HTML to a blob store (e.g., S3).
    • Places a message (e.g., a pointer to the S3 object) onto the Parsing Queue.
  3. Parsing Queue (SQS Queue): Contains pointers to raw HTML that needs to be parsed.
  4. Parser Service: A pool of workers that:
    • Pulls a message from the Parsing Queue.
    • Retrieves the raw HTML from S3.
    • Extracts text and saves it to a final data store.
    • Extracts new URLs and adds them to the URL Frontier (after deduplication).

This architecture is superior because if parsing fails, we don't need to re-fetch the page from the internet; we just re-process the raw HTML from our own S3 bucket. If fetching fails, the message can be retried automatically by SQS with an exponential backoff strategy, and if it fails repeatedly, it's moved to a DLQ for later analysis without blocking the entire system.


4. Deep Dive: Politeness

A web crawler that hammers a single website with thousands of requests per second is effectively performing a denial-of-service (DoS) attack. Politeness is a critical non-functional requirement to prevent this.

Design a Web Crawler

The Hello Interview article provides a detailed guide on implementing politeness.

Read the section '2) How can we ensure politeness and adhere to robots.txt?'. This covers the two main pillars of politeness: respecting robots.txt and global rate limiting.

Politeness has two main components:

  1. robots.txt Compliance: This is a file websites can host at /robots.txt to give directives to crawlers. Our system must:

    • Fetch and cache this file for every new domain it encounters.
    • Obey Disallow rules, which forbid crawling certain URL paths.
    • Obey Crawl-delay directives, which specify a minimum waiting time between requests to that domain.
  2. Rate Limiting: Even if robots.txt doesn't specify a delay, a good-faith crawler should self-impose a rate limit (e.g., 1 request per second per domain).

Implementing this in a distributed system with thousands of independent fetchers is a classic coordination problem. Simply having each fetcher sleep() is not enough. The solution requires a centralized decision-maker.

Web Crawler Host Politeness Mechanism
This diagram shows an effective pattern for managing politeness. Instead of fetchers pulling URLs directly, a 'Host Politeness Manager' routes URLs into per-host queues. This ensures that URLs for a single domain (e.g., Host A) are processed sequentially with the correct delay, preventing multiple fetchers from hitting the same domain simultaneously. Source: Substack

This "smart scheduler" or "politeness manager" can be implemented with a few key components:

  • Domain Metadata DB: Stores robots.txt rules and the last-crawled time for each domain.
  • Per-Host Queues: A mechanism to group URLs by host. A fetcher must acquire a "turn" to crawl a specific host.
  • Centralized Rate Limiter (e.g., Redis): Before fetching, a worker checks with a Redis-based rate limiter (using a sliding window algorithm) to see if the domain's rate limit has been exceeded. If so, the URL is put back on the queue with a delay. Jitter (a small, random delay) is added to prevent workers from retrying in a synchronized, thundering herd.

For a Staff-level discussion, the most sophisticated approach involves a dedicated scheduling component that manages both politeness and priority.

Design a Basic Search Engine (Google or Bing) | System Design Interview Prep

The video 'Design a Basic Search Engine' has one of the best explanations of an advanced URL Frontier that handles both politeness and priority.

Watch the deep dive on the 'URL Frontier' from 10:59 to 16:16. This is a masterclass in designing a component that balances crawling important pages more frequently (priority) with not overwhelming any single server (politeness). Pay attention to the use of multiple queue sets and a heap.


5. Deep Dive: Deduplication and Efficiency

Crawling is expensive. We must avoid re-processing the same data. Deduplication happens at two levels.

Design a Web Crawler

Let's return to the Hello Interview article for a discussion on deduplication strategies.

Read the subsections on URL-level deduplication and content-level deduplication within the 'Scale and Efficiency' section.

  1. URL-Level Deduplication: This is straightforward. Before adding a newly discovered URL to the frontier, the Parser service checks a database (e.g., a URL table in DynamoDB or Bigtable where the URL is the primary key) to see if we've ever seen this URL before. If so, we discard it.

  2. Content-Level Deduplication: This is more subtle and impactful. Many different URLs can point to identical content. To avoid parsing and storing the same text multiple times, we can:

    • Hash the Content: After the Fetcher downloads the raw HTML, it computes a hash (e.g., SHA-256) of the content.
    • Check for Hash: Before placing the item on the Parsing Queue, it checks if this hash has been seen before.
    • Implementation Trade-offs:
      • Database Index: Store the hashes in a metadata database and create a global secondary index (GSI) on the hash column. This is a robust and simple solution. A lookup is .
      • In-Memory Set (Redis): Store hashes in a massive Redis set for lookups. This is faster but requires managing a large in-memory dataset, adding operational complexity and cost.
      • Bloom Filter: This is a probabilistic data structure that can definitively say "this hash has not been seen" or "this hash has probably been seen." It's extremely space-efficient but introduces a small chance of false positives (i.e., accidentally discarding a new page). As noted in the resources, this is often an over-engineered solution when you don't have strict memory constraints, and a simple DB index is more practical. Knowing when not to use a trendy solution is a sign of senior engineering judgment.

Finally, to avoid getting stuck in crawler traps (infinite loops of generated pages), we can add a depth attribute to our URL metadata and stop crawling any branch that exceeds a certain depth from the original seed URL.


Conclusion

We have designed a web crawler that is scalable, robust, and polite. It moves beyond a simple script to a full-fledged distributed system, reflecting the complexity required for a Google-scale operation.

Key Takeaways:

  • Architecture: A multi-stage pipelined architecture (Fetcher, Parser) connected by message queues is essential for fault tolerance and scalability.
  • Politeness: This is a first-class concern, handled by a centralized system that manages robots.txt rules, per-domain rate limits, and crawl delays. A sophisticated URL Frontier can also manage crawl priority.
  • Deduplication: A multi-layered strategy is crucial. We deduplicate at the URL level to avoid re-adding known URLs and at the content level (using hashing) to avoid processing duplicate content.
  • Practical Trade-offs: For a Staff-level discussion, justifying choices is key. For example, preferring a simple database index for content deduplication over a more complex Bloom filter demonstrates practical, real-world engineering judgment.

Preview of the Next Lesson:

We've now covered two of your requested deep dives: search autocomplete and web crawling. Next, we will tackle the Uber-focused problem: Design a navigation and ETA system. This will pivot us from large-scale data ingestion and retrieval to the world of real-time geospatial data, graph algorithms (like Dijkstra's), and processing rapidly changing inputs like traffic conditions.