Skip to content
Visual explainer 3h to learn 5 steps

Web crawler

Design a polite, distributed crawler with deduplication and a URL frontier.

By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.

Topic 31 of 33

In short

A web crawler downloads billions of pages by repeatedly taking URLs from a frontier, fetching them, extracting links and queuing new ones. It must be polite to each host, avoid revisiting duplicates and scale across many workers.

Explained simply

A web crawler is a program that visits web pages automatically, saves them, finds the links on them, and then visits those links too. Search engines use crawlers to build their index. Other uses include price tracking, archiving and research.

The crawler keeps a big to-do list of addresses (URLs) to visit, called the URL frontier. A worker takes a URL, downloads the page, pulls out all the links, and adds the new ones back to the list. This loop runs on many machines at once.

A good crawler is polite. It reads each site's robots.txt file to learn which pages it may not visit, and it waits between requests to the same site so it does not slow that site down. An impolite crawler gets blocked quickly.

The web is full of repeats: the same page under many URLs, and copies of pages on different sites. The crawler must remember which URLs it has seen and spot pages whose content it already has, or it will waste most of its time.

Press Play on a diagram to walk through it one step at a time.

CycleCrawl loop
  1. 1
    URL frontier

    Prioritised, per-host queues

  2. 2
    Fetcher

    Check robots.txt, download with DNS cache

  3. 3
    Content dedupe

    Skip pages whose fingerprint was seen

  4. 4
    Store and parse

    Save HTML to blob storage, extract links

  5. 5
    URL filter

    Normalise, drop seen URLs via Bloom filter

  6. Back to step 1
SequenceFetching one URL politely
Frontier
Fetcher
Host site
Seen-URL store
  1. 1Next URL for ready host
    Fetcher to Frontier: Next URL for ready host
  2. 2GET /robots.txt (cached)
    Fetcher to Host site: GET /robots.txt (cached)
  3. 3GET page
    Fetcher to Host site: GET page
  4. 4200 HTML
    Host site to Fetcher: 200 HTML
  5. 5Check extracted links
    Fetcher to Seen-URL store: Check extracted links
  6. 6Enqueue new URLs, delay host
    Fetcher to Frontier: Enqueue new URLs, delay host
LayersComponents of a distributed crawler
  1. 1
    Scheduler and frontier

    Priority and per-host queues, sharded by host hash

  2. 2
    Fetchers

    Async HTTP, robots cache, local DNS cache

  3. 3
    Parsers

    Extract links and text, compute fingerprints

  4. 4
    Dedupe services

    Bloom filter for URLs, SimHash for content

  5. 5
    Storage

    Raw pages in blob storage, metadata in a database

In depth

Scope and estimates

Clarify the goal: a general search crawler, or a focused one for a few sites? HTML only, or also PDFs and images? Must we run JavaScript to see content? How often should pages be refreshed? A typical interview scope: HTML only, 1 billion pages per month, refresh popular pages more often, obey robots.txt, store raw pages for an indexer.

The explainer works out about 400 pages per second and 500 TB per month. Two more numbers matter. DNS: if each fetch needed a fresh DNS lookup taking 20 to 100 ms, DNS would become the bottleneck, so run a local caching resolver. Connections: with an average fetch time around 1 second, 400 pages per second means about 400 fetches in flight, so each worker should use asynchronous I/O to keep hundreds of downloads open at once rather than one thread per page.

  • Concurrency ≈ pages per second * average fetch time
  • Cache DNS locally
  • Rendering JavaScript costs far more CPU than plain fetching

Inside the URL frontier

A well-known design (from the Mercator crawler) has two layers of queues. Front queues handle priority: a prioritiser scores each URL by things like page importance and how often it changes, and puts it in one of several priority queues. Back queues handle politeness: each back queue holds URLs for exactly one host, and a small table maps host to back queue.

A heap (min-priority queue) stores, for each back queue, the earliest time that host may be contacted again. A worker pops the host whose time has come, fetches one URL, then sets that host's next allowed time to now plus a delay, often a small multiple of how long the last fetch took. When a back queue empties, it is refilled from the front queues. In a distributed crawler, hosts are assigned to machines by hashing the hostname, so all politeness for a host stays on one machine.

FlowA URL's path through the frontier
  1. 1
    New URL

    Normalised and not seen before

  2. 2
    Prioritiser

    Scores importance and change rate

  3. 3
    Front queue

    One of N priority levels

  4. 4
    Back queue per host

    Fed when that host's queue runs low

  5. 5
    Ready-time heap

    Host is due when its delay has passed

  6. 6
    Fetcher

    Downloads, then resets the host's timer

robots.txt and rate limits

Before crawling a host, fetch https://host/robots.txt and cache it, commonly for up to 24 hours. It contains groups that start with User-agent lines followed by Disallow and Allow rules for path prefixes. RFC 9309 (2022) standardised the format: the most specific (longest) matching rule wins, and if robots.txt returns a 4xx error the crawler may crawl freely, while a 5xx error means treat the whole site as disallowed for now.

Crawl-delay is not part of the standard and some engines ignore it, but a polite crawler honours it if present. Beyond that, set your own limits: one connection per host, a delay of a second or more, and back off on 429 Too Many Requests or 503 responses, respecting a Retry-After header. Send a clear User-Agent with a URL explaining your bot, so site owners can contact you.

  • Cache robots.txt per host, about a day
  • 4xx on robots.txt: allowed; 5xx: stop for now
  • Back off on 429 and 503, honour Retry-After

Deduplicating URLs and content

URL dedupe starts with normalisation so equal URLs look equal: lowercase the scheme and host, remove default ports (:80, :443), resolve ./ and ../, drop the #fragment, and strip known tracking parameters such as utm_source. Then check a seen-URL set. A Bloom filter (a bit array plus several hash functions) answers is-it-new in a few bits per URL; it never says a seen URL is new, but it sometimes says a new URL was seen, which only skips a few pages.

Content dedupe catches the same page under different URLs. An exact hash (like SHA-256) of the normalised text finds identical copies. Near-duplicates, such as the same article with a different ad or date, need a fingerprint like SimHash, where similar documents produce fingerprints that differ in only a few bits. Also honour rel=canonical links, which tell you which URL the site considers the main one.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Clarify scope and politeness rules~35m
  2. 2
    Estimate pages and bandwidth~35m
  3. 3
    Design the URL frontier~35m
  4. 4
    Respect robots.txt and rate limits~35m
  5. 5
    Deduplicate URLs and content~35m

Key points

  • Politeness: one connection per host and a delay between requests.
  • Partition the frontier by host so each host maps to one worker queue.
  • Bloom filters cheaply test whether a URL was already seen.
  • Content fingerprints such as SimHash catch duplicate pages under different URLs.
  • Guard against spider traps with depth and URL-length limits.

Key terms

Tap a card to flip it. 0/5 known

Examples

text
Goal: 1B pages per month
  1B / (30 * 10^5 s) ≈ 400 pages/s, ~800 peak
  avg page 500 KB -> 400 * 500 KB = 200 MB/s download
  storage: 1B * 500 KB = 500 TB/month (compress ~5x)

Seen URLs: 1B * ~10 bits in Bloom filter ≈ 1.25 GB RAM

Throughput, bandwidth and dedupe memory.

Normalising URLs before the seen check

These three links point at the same page: HTTP://Example.com:80/a/./b/?utm_source=x#top, http://example.com/a/b/ and http://example.com/a/c/../b/. Without normalisation the crawler fetches it three times. The function lowercases scheme and host, drops the default port, resolves dot segments, removes utm_ parameters, sorts the rest, and drops the fragment. Real crawlers add site-specific rules, but this catches the common cases.

python
from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode
import posixpath

def normalise(url: str) -> str:
    s = urlsplit(url)
    scheme, host = s.scheme.lower(), (s.hostname or "").lower()
    port = s.port
    if port and not ((scheme == "http" and port == 80) or (scheme == "https" and port == 443)):
        host += f":{port}"
    path = posixpath.normpath(s.path or "/") + ("/" if s.path.endswith("/") and s.path != "/" else "")
    query = urlencode(sorted((k, v) for k, v in parse_qsl(s.query) if not k.startswith("utm_")))
    return urlunsplit((scheme, host, path, query, ""))

print(normalise("HTTP://Example.com:80/a/./b/?utm_source=x#top"))  # http://example.com/a/b/

Checking robots.txt in Python

Python's standard library includes a robots.txt parser. Step 1: point it at the site's robots.txt and read it once (then cache the object per host). Step 2: before each fetch, ask can_fetch with your bot's user agent and the URL. Step 3: read crawl_delay, which returns None if the site did not set one, and use your own default then. Note that this parser is simpler than RFC 9309 in some edge cases, so large crawlers often use a stricter library.

python
from urllib.robotparser import RobotFileParser

rp = RobotFileParser("https://example.com/robots.txt")
rp.read()
agent = "MyCrawler/1.0 (+https://mycrawler.example/bot)"
url = "https://example.com/private/page"
if rp.can_fetch(agent, url):
    delay = rp.crawl_delay(agent) or 1.0
    print("fetch after", delay, "s")
else:
    print("disallowed by robots.txt")

Quick reference

  • Concurrent fetches ≈ pages/s * average fetch seconds
  • Front queues for priority, back queues for one host each
  • Hash the hostname to pick the crawler machine
  • Cache robots.txt per host; 5xx on robots.txt means don't crawl yet
  • Back off on 429 and 503; honour Retry-After
  • Normalise URLs before the Bloom filter check
  • Exact hash for identical pages, SimHash for near-duplicates
  • Limit depth, URL length and pages per host to escape spider traps

Common mistakes

  • Hammering one host with many parallel requests.
  • Not normalising URLs, so tracking parameters create endless duplicates.
  • Letting DNS lookups become the throughput bottleneck.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why assign each host to exactly one crawler machine?

Question 2

2What does a Bloom filter risk getting wrong?

Question 3

3Under RFC 9309, what should a crawler do if robots.txt returns a 503 error?

Question 4

4Two news sites publish the same article with different ads around it. Which technique detects that?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a robots.txt that blocks all bots from /admin/ and /search, but allows /search/help.

  2. Exercise 2medium

    Size a Bloom filter for 5 billion URLs with about a 1 percent false positive rate.

  3. Exercise 3hard

    A site generates calendar pages with a next-day link forever. Design defences against this spider trap without hurting normal sites.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is robots.txt legally binding?
It is a convention, not a security control, and its legal weight varies by country. Respectable crawlers follow it, and ignoring it is a fast way to get blocked.
Should a crawler run JavaScript?
Only for pages that need it. Running a headless browser costs far more CPU and time than a plain HTTP fetch, so many crawlers fetch HTML first and render only selected pages later.
How often should pages be recrawled?
It depends on how often they change. Crawlers track change history per page and revisit fast-changing pages, like news front pages, much more often than static ones.
What is a sitemap?
A sitemap is an XML file, often listed in robots.txt, where a site lists its URLs and when they last changed. It helps crawlers find pages they might miss.
ShareXLinkedInWhatsApp