Skip to content

    System Design

    Case Study: Web Crawler

    Design a polite web crawler: the URL frontier, per-host rate limits, robots.txt under RFC 9309, URL and content deduplication, crawler traps and recrawls.

    By Published 23 min read

    Share

    What you'll learn: By the end of this lesson you will be able to (1) design a crawler whose throughput is limited by politeness rather than by its own hardware, (2) build a URL frontier with priorities and per-host queues, (3) apply the robots.txt rules of RFC 9309 correctly, including what to do when the file cannot be fetched, (4) deduplicate URLs and page content at billions of items, and (5) recognise crawler traps and schedule recrawls.

    Picture a census taker with a million doors to knock on. Each door has a small sign beside it saying which rooms visitors may not enter. Knock twice in one minute and the household calls the police, so the census taker keeps a notebook of when each door was last knocked, and always walks to a door that has rested. Some streets are copies of other streets, and some houses are fake doors that open onto another fake door forever. The notebook is the hard part, not the walking.

    A web crawler is that census taker. Fetching one page is a single HTTP request. Fetching a billion pages without hurting anyone, without wasting the budget on duplicates and without being trapped is a scheduling and bookkeeping problem. This lesson is a design walk-through with no real crawling: it describes components and data, and the exercises use a made-up site.

    This is an educational reference design, not the verified internal architecture of any company. No company is named, and every number is an illustrative assumption. The lesson assumes the case-study template, message queues and object and blob storage.

    The core idea

    A crawler is a loop of "take a URL, fetch it, find new URLs", and every difficulty is a decision about which URL goes next, which never goes at all, and which waits. Three gates sit in that loop:

    1. Admission: is this URL worth adding (valid, in scope, not already seen)?
    2. Permission and pacing: may we fetch it (robots.txt), and has this host rested long enough?
    3. Content: is what came back new, or a copy of something we already hold?

    The data structure that carries the decisions is the URL frontier: the crawler's to-do list that also decides the order and timing of fetches. Almost every scaling problem becomes a frontier problem.

    Three illustrations run through the lesson:

    • Minimal example: one host with three pages, crawled with a one-second delay between requests.
    • Realistic example: ShopStream keeps a catalogue-enrichment crawler over the public pages of supplier sites that have agreed to be crawled, so it can notice price and availability changes.
    • Failure example: a calendar page that links to "next month" forever, and a robots.txt file that starts returning server errors.

    Requirements and scope

    Functional:

    • Start from seed URLs and sitemaps, follow links, and fetch HTML pages.
    • Obey robots.txt and never exceed a per-host request rate.
    • Store each fetched page and its metadata for a downstream indexer.
    • Skip URLs and content already seen.
    • Recrawl pages to keep them fresh, favouring pages that change.

    Non-functional (assumptions):

    • Politeness is a hard constraint, not a tuning knob.
    • The crawl survives machine failures without starting over: a restarted fetcher loses at most the URLs it was holding.
    • Duplicates are tolerated in small numbers. Missing a few pages is acceptable. Hammering one host is not.

    Out of scope: rendering JavaScript, indexing and ranking, deep legal questions about what may be collected, and login-protected content. A crawler that is not polite or not identified is a different, hostile kind of program that this lesson does not design.

    Back-of-envelope estimate

    All numbers are illustrative assumptions.

    Quantity Assumption Result
    Corpus 1 billion pages, each refreshed on average every 30 days 1,000,000,000 / (30 x 86,400 s) = about 386 pages per second
    Planning headroom 2x for bursts and retries about 770 pages per second
    Page size 100 KB average 386 x 100 KB = 38.6 MB/s, about 309 Mbit/s; 100 TB per full cycle
    Links per page 10 about 3,860 URL admission checks per second
    Concurrent fetches 386 pages/s x 1 s average fetch (Little's law) about 386 in flight
    URL-seen set, exact 1 billion fingerprints x 8 bytes 8 GB before overhead
    URL-seen set, Bloom filter 1% false positives needs 9.585 bits per item; 0.1% needs 14.378 about 1.2 GB or 1.8 GB
    Politeness floor At least 1 s between requests to one host 386 pages/s needs at least 386 different hosts active at once
    One large host 1,000,000 pages at one request per second 1,000,000 s, about 11.6 days

    Two rows matter most. The politeness floor caps the crawl rate by how many distinct hosts you can keep busy, so a corpus concentrated on a few big hosts crawls slowly however many machines you add. The single large host shows that its freshness is bounded by its delay, not by your capacity.

    The Bloom filter figures come from the Redis documentation, which gives the bits per item and hash-function counts for each error rate. The 2001 Mercator report describes a hash set of 8-byte URL checksums that needed slightly over 5 GB per billion URLs once pointers and counters were included, so 8 GB here is a round, conservative figure.

    API design

    A crawler has no public API. It has internal contracts between its components:

    Frontier.add(url, priority, discoveredFrom)        # admission -> frontier
    Frontier.lease(workerId, maxUrls)  -> [url]        # fetcher asks for work; each URL is a lease with a deadline
    Frontier.complete(url, outcome, nextFetchHint)     # fetched, failed, blocked, or retry later
    Robots.check(host, path, userAgentToken) -> allow | disallow
    Robots.get(host) -> parsed rules, fetchedAt, status
    Fetcher.fetch(url, ifNoneMatch?) -> status, headers, body
    Store.put(contentHash, bytes)                      # raw page, by content hash
    Index.seen(urlFingerprint) -> bool                 # URL-seen test

    Two details carry weight. lease hands out work with a deadline, so a crashed fetcher's URLs return to the queue instead of vanishing. ifNoneMatch lets a recrawl ask "has this changed?" and receive a cheap answer instead of the whole page.

    Data model

    Only three things are large: URLs, hosts and page bodies.

    • Host record, keyed by scheme, host and port: parsed robots rules, when they were fetched and their status, the current delay between requests, next_allowed_at, and a consecutive-error counter.
    • URL record, keyed by the URL fingerprint: the normalised URL, host, state, priority, depth, last_fetched_at, etag, last_modified, content_hash, and a change counter that drives recrawl priority.
    • Page body, in object storage keyed by content_hash, so two URLs with identical content store the bytes once. The index points at hashes, never at inline bytes.

    The frontier is partitioned by host, using consistent hashing. One frontier shard owns all the queued URLs of a host, so it alone knows when that host may next be contacted, and no cross-machine coordination is needed for politeness. The URL-seen set is partitioned the same way: a URL is checked on the shard that owns its host, so the check is local.

    High-level design

    Web crawler high-level designSeeds and sitemaps to URL admission (URLs); URL admission to URL frontier (new only); URL frontier to Fetchers (lease); Fetchers to Robots cache (may I?); Fetchers to Web servers (GET); Fetchers to Raw page store (store); Fetchers to Parser (body); Parser to URL admission (links); Parser to Content-seen index (hash)Seeds and sitemapsSeeds andsitemapsURL admission: normalise, scope, seenURL admissionnormalise, scope,seenURL frontier: priority, per hostURL frontierpriority, perhostFetchers: leases, pacingFetchersleases, pacingRobots cache: rules per hostRobots cacherules per hostWeb servers: not oursWeb serversnot oursRaw page store: by content hashRaw page storeby content hashParser: links, content hashParserlinks, contenthashContent-seen indexContent-seenindexURLsnew onlyleasemay I?GETstorebodylinkshash

    Figure 1. The crawl loop. How to read this: URLs enter admission, only new ones reach the frontier, fetchers lease them, ask the robots cache and fetch. Parsed links loop back to admission, which is why the system never runs out of work on its own.

    Admission and the frontier are where state lives. Fetchers and parsers are stateless workers that can be killed and replaced. The parser sits behind a queue (message queues) so a slow parse never blocks the fetchers.

    sequenceDiagram accTitle: One polite fetch accDescr: A fetcher leases a URL from the frontier, checks the cached robots rules, fetches the page, stores it and reports the outcome so the frontier can set the host's next allowed time. participant F as Fetcher participant Q as Frontier shard participant R as Robots cache participant W as Web server participant S as Page store F->>Q: lease(urls) Q-->>F: url, host, lease deadline F->>R: check(host, path) R-->>F: allow F->>W: GET url (with If-None-Match when known) W-->>F: 200 and body, or 304 F->>S: put(contentHash, body) F->>Q: complete(url, outcome, nextFetchHint) Q->>Q: next_allowed_at = now + delay for this host

    Figure 2. One fetch. How to read this: the delay is applied by the frontier after the fetch completes, using the time that fetch took, so the host's rest period starts when the host finished serving us.

    Deep dive 1: robots.txt

    The Robots Exclusion Protocol is specified in RFC 9309. A crawler reads its rules before fetching anything else from a host, and the rules decide which paths may be requested.

    Where the file lives and how long it lasts. The rules are at /robots.txt at the top-level path of the service, so each combination of scheme, host and port has its own file. A crawler may cache the file and SHOULD NOT use a cached copy for more than 24 hours unless the file has become unreachable. The cache is therefore small and keyed by host.

    Which group applies. Each group starts with one or more user-agent lines. Matching is on a product token, case-insensitively, and if no group matches, the group for * applies, if one exists. If nothing matches, no rules apply and everything is allowed.

    Which rule wins. The most specific match, meaning the one with the most octets, wins. If an allow and a disallow rule are equally specific, the allow rule SHOULD be used. Two special characters are supported: * matches zero or more characters and $ anchors the end of the pattern. Path matching should be case sensitive. A rule set with no match allows the URL.

    What a failed fetch means. The two failure classes point in opposite directions, and designs often confuse them:

    Robots.txt response What RFC 9309 says Our behaviour
    Success Follow the parseable rules Use them, cache them
    Redirects SHOULD follow at least five consecutive redirects; beyond that the file MAY be treated as unavailable Follow up to five hops, treat the result as the host's rules
    4xx ("unavailable") The crawler MAY access any resource on the server Treat as no restrictions, retry the file later
    5xx ("unreachable") The crawler MUST assume complete disallow; after a long period (the RFC's example is 30 days) it MAY treat the file as unavailable or keep using a cached copy Pause the host entirely, back off, keep the last good copy within limits

    A server error on robots.txt is a stop sign, not a green light. A crawler that treats an outage as permission will crawl sites during exactly the moments their operators are fixing them.

    Other points. The RFC says a parser limit SHOULD exist and MUST be at least 500 kibibytes, so the crawler should parse the first part of a huge file and ignore the rest. It states that these rules "are not a form of access authorization": robots.txt politely asks, it does not protect anything, and the RFC says it is not a substitute for real content security. It does not define a crawl delay. A Crawl-delay line, where a site publishes one, is a non-standard extension some crawlers honour, so our delay logic must work without it. Lines such as Sitemap: are outside the core grammar; the RFC lets crawlers interpret such records as long as they do not disturb parsing of the defined ones, and the sitemaps protocol describes the Sitemap: line.

    Identification. A crawler should send a User-Agent header (RFC 9110 says a user agent SHOULD send one), and that header should carry a stable product token and a page describing the crawler and how to reach its operator. The token in robots.txt matching and the token in the header must be the same name, or site operators cannot write rules for you.

    Deep dive 2: the frontier and politeness

    The frontier has two jobs that conflict. Priority says which URLs matter most. Politeness says which hosts are allowed a request right now. A single FIFO queue satisfies neither: because pages link to pages on the same site, a FIFO queue fills with runs of one host, and many threads then hit that host simultaneously.

    The 2001 Mercator report describes the structure this lesson adapts. It first used a "weak politeness guarantee" (only one thread talks to a host at a time) and then found that this still allowed a stream of requests with no pauses between them, which drew complaints from administrators. Its stronger design has two layers:

    • A front end of priority FIFO queues. A prioritizer assigns each new URL a priority, and queues are chosen at random with a bias towards high priority.
    • A back end of FIFO queues, each holding URLs of a single host, plus a table mapping hosts to queues and a heap ordered by the time each host may next be contacted. A fetcher takes the heap's root (waiting until its time has come), downloads the head URL of that host's queue, then re-inserts the queue with a new timestamp. If a back-end queue empties, it is refilled from the front end.

    The report says its production crawls used about three times as many back-end queues as crawling threads and waited ten times as long as the previous download took before contacting that host again. Those are that report's settings, not rules, but the idea of a delay proportional to server response time is sound: a slow host is probably a stressed host, and slowing down is the right response.

    Frontier with priority and per-host queuesPrioritizer to Priority queues (enqueue); Priority queues to Per-host queues (refill); Host map to Per-host queues (route); Per-host queues to Ready-time heap (handle); Ready-time heap to Fetchers (host ready); Fetchers to Ready-time heap (new time)Prioritizer: score each URLPrioritizerscore each URLPriority queues: high to lowPriorityqueueshigh to lowPer-host queues: one host eachPer-hostqueuesone host eachHost map: host to queueHost maphost to queueReady-time heap: next allowed timeReady-timeheapnext allowed timeFetchersFetchersenqueuerefillroutehandlehost readynew time

    Figure 3. The politeness frontier. How to read this: priority decides which URL enters a host queue; the heap decides when that host's queue may be served. Fetchers never choose a host, they take whichever is ready, which spreads load evenly.

    Distributing it. Each frontier shard owns a set of hosts and runs this structure for them. A shard has a fixed number of fetchers attached, so politeness is enforced in one process, with no distributed lock. If a shard fails, its hosts move to another shard on the ring and the leased URLs reappear when their lease deadlines pass. A host moving shards briefly risks two requests close together, which a few seconds of "cool-down after takeover" removes.

    Setting the delay. Use the larger of: a configured floor, a multiple of the last response time, and any delay the host's own signals demand. A Retry-After header (RFC 9110, either a number of seconds or an HTTP date) on a 503 response says how long the service expects to be unavailable, so the host's next_allowed_at moves at least that far. Repeated errors double the delay and eventually pause the host, the same backoff idea as in timeouts, retries, backoff and jitter.

    DNS. Resolving a name can take a long time, and the Mercator report calls it a well-documented bottleneck of crawlers; it built its own multi-threaded resolver because the standard interface serialized lookups. A crawler resolves each host once per delay window and caches the result inside the shard (see DNS for TTLs), and it checks the resolved address when a host sits behind many names.

    Deep dive 3: deduplication

    There are two different questions and they need two different structures.

    URL deduplication ("have I seen this address?"). Two textually different URLs can name the same page. RFC 3986 section 6 describes comparison and normalisation: a simple string comparison produces false negatives because of URL aliases, and syntax-based normalisation reduces them. The relevant steps are lowercasing the scheme and host, upper-casing percent-encoding hex digits, decoding percent-encoded octets that correspond to unreserved characters, removing dot segments from the path, and, for http, treating an empty path as / and dropping an empty or default port. A crawler adds its own rules, such as dropping fragments (they are never sent to the server) and sorting query parameters, and it must decide per site whether tracking parameters are noise. Those extra rules are policy, not standard: they should be configurable and conservative, since wrongly merging two distinct pages hides one of them.

    After normalising, compute a 64-bit fingerprint and test membership:

    Structure Memory for 1 billion URLs False positives False negatives Notes
    Hash set of 8-byte fingerprints about 8 GB, sharded Only on fingerprint collision None Exact enough, grows linearly
    Bloom filter at 1% about 1.2 GB 1% of new URLs wrongly "seen" None Cannot delete; fixed capacity
    Bloom filter at 0.1% about 1.8 GB 0.1% None More memory, fewer skipped pages
    On-disk sorted fingerprint file, merged in batches disk-sized Only on collision None Mercator's most efficient disk design, throughput fell as merges grew

    A Bloom filter, per the Redis documentation, can guarantee that an item is absent but only estimate that it is present, so a "not seen" answer is certain and a "seen" answer is wrong some of the time. For a crawler the cost of a false positive is one skipped page, and with 1% wrong, about 1 in 100 genuinely new URLs is never fetched from that source, though another link to it may succeed later. That is acceptable for web-scale discovery and unacceptable for a crawl that must be complete, such as a small catalogue crawl, where an exact set is cheap. Filters also fill up: when a Bloom filter is sized for too few items its error rate grows, so size it for the corpus plus growth, and shard it by host so each filter stays modest.

    Content deduplication ("have I seen this page?"). Different URLs often return the same bytes (mirrors, printer views, session-id variants). After fetching, hash the normalised content and look it up in the content-seen index. A hit means the page is a duplicate: store a pointer, do not store the bytes again, and do not extract links from it a second time. The Mercator report describes the same content-seen test after the document is written. Exact hashes catch only identical bytes. Near-duplicates, such as pages that differ by a timestamp, need similarity hashing, which is a larger topic, and a crawler can start without it.

    flowchart TD accTitle: Should this discovered link enter the frontier accDescr: A decision flow for each extracted link covering normalisation, scope, host budget, depth and the URL-seen test before the URL is added to the frontier. A["Link extracted from a page"] --> B["Normalise the URL"] B --> C{"Scheme and domain in scope?"} C -- no --> X["Drop"] C -- yes --> D{"Within host URL budget and depth limit?"} D -- no --> X D -- yes --> E{"Fingerprint already seen?"} E -- yes --> X E -- no --> F["Record fingerprint"] F --> G["Assign priority and add to frontier"]

    Figure 4. The admission decision. How to read this: every discovered link passes four tests in order of cost, cheapest first. Robots rules are not checked here: they can change, so they are applied at fetch time against the cached copy.

    Deep dive 4: traps, scope and recrawling

    Crawler traps. A site can generate unlimited distinct URLs: a calendar with a next-month link, session ids appended to every URL, a search page that links to ever more filter combinations, or a relative link that repeats a path segment each time. Normal dedup does not help because every URL really is new. Defences are budgets:

    • A maximum URLs per host and per path prefix (illustratively 100,000 for ordinary hosts, overridable for known large ones).
    • A maximum depth from the seed, and a maximum URL length.
    • A detector for repeating path segments and for a rapidly growing number of query-parameter variants of the same path.
    • Priority decay: URLs found deep inside a low-value pattern get low priority, so they sit behind everything else and cost little even if never fetched.

    Recrawling. After the first pass the frontier must also re-queue pages. A reasonable policy gives each URL a next-visit time based on how often it changed in the past: pages that changed at every visit are revisited sooner, pages that never changed are revisited less often. Sitemaps help by naming URLs and, optionally, their last modification; the protocol says the lastmod field should reflect when the page itself last changed, and treats changefreq as a hint rather than a command. Treat them as hints and verify.

    Recrawls use conditional requests. With the validator saved from the last fetch, the crawler sends If-None-Match; RFC 9110 says that when the condition is false for a GET or HEAD request the origin server responds with 304 (Not Modified). A 304 carries no body, so a recrawl of an unchanged page costs a header exchange, and the crawler records "unchanged" and pushes the next visit further out.

    Storage and the downstream handoff

    Fetchers write the body to object storage under its content hash and a small metadata row (URL, fetch time, status, hash) to a stream. The indexer reads the stream and never talks to fetchers, so if the indexer is down for a day, metadata queues up and the crawl continues. Retention is a policy decision: keep the latest copy and a limited history unless a downstream product needs more.

    Bottlenecks and scaling

    • Distinct-host supply. Throughput equals active hosts divided by the per-host delay, so a crawl of a few huge hosts is slow however large the fleet. The fix is breadth: spread the crawl across hosts, and accept that a single large host takes days.
    • Frontier memory and disk. Billions of URLs do not fit in memory. Keep the heads and tails of each queue in memory and spill the bulk to disk, as the Mercator report describes.
    • URL-seen throughput. A few thousand checks per second per cluster is modest when sharded by host, but a disk-resident set needs batching to avoid one seek per check.
    • Hot shards. Politeness serializes a very large host anyway, so it costs queue space, not fetch capacity: move it to a shard with room.
    • Retry storms. After an outage every failed URL is due at once. Add jitter to retry times.

    Failure modes

    Failure Effect Mitigation
    Fetcher crashes holding leases URLs stuck Lease deadlines return them to the queue; fetches are idempotent GETs
    Frontier shard fails Its hosts stop being crawled Re-assign hosts on the ring, cool-down before first fetch, persisted queues
    robots.txt returns 5xx Unknown permission Treat as complete disallow, back off, keep last good copy within the 30-day idea of RFC 9309
    robots.txt returns 404 No restrictions apply Crawl, re-check within 24 hours
    Host starts returning errors or slows down Crawl may worsen the outage Grow the delay, honour Retry-After, pause the host after repeated failure
    Crawler trap Budget burned on one site Host and prefix budgets, depth limits, priority decay
    Bloom filter saturates More false "seen" answers Alert on estimated fill, rebuild larger, shard by host
    Duplicate pages dominate Wasted storage and parse time Content-hash lookup before parsing

    Trade-offs worth stating

    Decision Option A Option B How to choose
    Politeness enforcement Per-shard host ownership Global rate-limit service Ownership: no network hop, no shared lock
    URL-seen test Exact fingerprint set Bloom filter Exact for small or must-be-complete crawls, Bloom for web scale
    Frontier order Breadth-first FIFO Priority plus per-host queues The second, as soon as politeness or freshness matters
    robots.txt on 5xx Assume disallow Assume allow Disallow: the RFC requires it
    Recrawl Fixed interval Change-history based Change-history, with conditional requests to make revisits cheap
    Dedup of content Exact hash Similarity hash Exact first; similarity when storage or index quality needs it

    Interview cheat sheet

    Requirements: polite, robots-compliant, fresh, deduplicated. Estimate: rate, bandwidth and URL-seen memory (about 386 pages/s, 309 Mbit/s and 1.2 GB for the illustrative corpus). Design: frontier, fetchers, parser and stores, all sharded by host. Deep dives: robots.txt (5xx means disallow), per-host queues with a ready-time heap, two kinds of dedup, trap budgets. Failures: crashed fetchers (leases), shard loss, robots outage. Trade-offs: exact set versus Bloom filter, owned versus global politeness.

    Build it

    This lesson has no lab. A runnable crawler would have to make real requests, and none are made here. The exercises below use a fake site served in memory.

    In practice: ShopStream's supplier-page crawler

    NOTE

    This is a realistic scenario, not a case history. It describes no real company, and every number is an illustrative assumption.

    The situation

    ShopStream's catalogue team wants to notice when supplier websites change a product's price or availability. About 2,000 supplier sites have given written permission to be crawled, and the team wants each product page re-checked about once a day. The sites vary from a few hundred pages to a few hundred thousand.

    Starting architecture

    A single scheduled script loops over a CSV of product-page URLs and fetches them with a fixed pool of 50 threads. It has no robots handling, no per-host limit, and it treats any failure as "try the next URL".

    Options considered

    Option Gain Cost Risk
    A. Keep the script, add sleeps No new system Throughput collapses on big sites; no change tracking Still bursts when many URLs share a host
    B. Per-host frontier with robots cache, conditional requests Polite, cheap revisits A small service and a state store Needs ownership and monitoring
    C. Ask suppliers for feeds Best data quality Slow, depends on each supplier Many will never build one

    The decision

    Choose B for the sites that have no feed, and track feeds as a longer-term track (C). The frontier is one shard per supplier group, with the host as the unit of politeness.

    Field Entry
    Context Permission is explicit, but sites differ widely in size and capacity.
    Decision Per-host queues, a one-second floor delay raised to ten times the last response time, robots.txt honoured even though permission exists, conditional requests, and a per-host URL budget.
    Consequences (good) Revisits mostly return 304, hosts see a predictable trickle, and one slow supplier does not stall the rest.
    Consequences (bad) A 300,000-page supplier needs days to refresh fully, so the product pages most likely to change are prioritised and the rest are refreshed more slowly.
    Revisit when More than a handful of suppliers complain about load, or a supplier publishes a machine-readable feed.

    Rollout and verification

    1. Run the crawler against a made-up local site that serves a robots.txt with a Disallow rule, a slow page, a 503 with Retry-After, and an endless calendar. Verify each behaviour with assertions on the request log: no request to a disallowed path, no two requests to the host closer than the delay, the 503 pause honoured, the trap stopped by the budget.
    2. Turn on three cooperative suppliers and watch the request rate per host against the configured delay.
    3. Add the rest in batches of 200 hosts, watching error rates and 304 ratios.
    4. Alert on any host receiving more requests per minute than its delay allows.

    The 2 a.m. failure

    At 2 a.m. a supplier's robots.txt starts returning 500 during their own deployment. A version of the crawler that treated the failure as "no rules" would crawl all 40,000 of that supplier's pages with the old script's thread pool. This design treats a 5xx as complete disallow, pauses the host, retries the file with backoff, and resumes when it returns a normal response. The on-call engineer sees a "host paused: robots unreachable" count rise and takes no action unless it lasts for hours.

    Architect's notes

    • Make politeness a property of the data structure. If a developer can bypass the delay by calling the fetcher directly, someone will.
    • Honour robots.txt even when you have permission. It is a cheap, shared language with the site operator, and operators may use it to keep you away from fragile paths.
    • Publish a crawler page and a contact. The operator who finds you in their logs should be able to reach you before they block you.
    • Plan for a host that dislikes you. Keep a per-host blocklist with a reason and an expiry date, editable without a deploy.
    • Measure the distinct-host supply early. A crawl plan that ignores host concentration promises throughput the delay arithmetic forbids.

    Common mistakes

    • Treating a robots.txt server error as permission. RFC 9309 requires assuming complete disallow for 5xx.
    • Caching robots.txt forever. The RFC says not to exceed 24 hours unless the file is unreachable.
    • One global FIFO queue. It creates bursts against single hosts. Use per-host queues and a ready-time heap.
    • A fixed delay for every host. A slow server needs a longer one. Scale with response time and honour Retry-After.
    • Normalising too little. Aliases of one page flood the frontier. Normalise per RFC 3986 and test with real data.
    • No trap budgets. A single calendar can consume the whole crawl.
    • Using a Bloom filter where completeness matters. False positives silently skip pages.

    Key takeaways

    • The frontier is the design. It orders URLs by priority and releases hosts by time.
    • Politeness caps throughput. The number of distinct active hosts and the per-host delay set the ceiling.
    • Partition by host. Frontier, URL-seen set and robots cache then need no cross-machine coordination.
    • robots.txt failure modes differ. 4xx means unrestricted, 5xx means disallow, and a cache lifetime of 24 hours applies.
    • Robots rules are not security. They are a request that polite clients honour.
    • Two dedups, two structures. Normalise and fingerprint for URLs, hash the bytes for content.
    • Bound everything. Host budgets, depth, URL length and priority decay turn a trap into a bounded cost.
    • Revisit cheaply. Conditional requests turn most recrawls into a 304.

    Practice exercises

    Exercise 1 - Starter (30 min): Redo the estimate for 5 billion pages refreshed every 14 days with 200 KB pages. Compute pages per second, bandwidth, the hosts needed at a two-second delay, and the Bloom filter size at 0.1% false positives.

    Exercise 2 - Intermediate (2 hours): Write the robots.txt decision table for a crawler: given a response status (200, 301 chain of 3, 301 chain of 7, 404, 429, 500, timeout), state whether the crawler may fetch, whether it retries, and when. Then write six test cases for the longest-match and allow-wins-ties rules, including a pattern with * and one with $.

    Exercise 3 - Advanced (half day): Plan a fault-injection test against a fake in-memory site: kill a fetcher mid-lease, kill a frontier shard, make robots.txt return 500, and serve an endless calendar. For each, state the invariant you assert (no request closer than the delay, no request to a disallowed path, all leases eventually complete or expire) and what the request log must show.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments