System Design

C18

Web crawler: polite, without loops

Fetch billions of pages for a search index without overloading any site, fetching a URL twice, or falling into an infinite URL space.

Not startedSaved in this browser only.
  1. 1The frontier has two levels: a queue per host, and a heap of hosts by the time each may be fetched next. One request per host at a time.
  2. 2Split the frontier by a hash of the host. One node owns a host, so it enforces the delay and dedupes its URLs alone.
  3. 3Normalise every URL, then check a Bloom filter: 9.6 bits per URL at 1%. A false positive skips a page; nothing is fetched twice.
  4. 4Fingerprint content too: SHA-256 for exact copies, simhash for near copies. A budget per host ends every trap.
C18
    A

    The prompt and requirements

    questions first, then numbers
    "Design a crawler that fetches billions of pages, politely per host, without loops, for a search index."
    questionanswer assumed
    How many pages?10 billion in the index, each refreshed every 30 days on average.
    What content?HTML. No JavaScript rendering at first.
    What does polite mean?Obey robots.txt. One connection per host. At least 1 s between requests, or the site's Crawl-delay if longer.
    Freshness?News hourly; most pages weekly to monthly. Visit by change rate.
    Duplicates?A URL once per cycle; the same text stored once; near copies dropped.
    Output?Pages in blob storage, plus a fetch log the indexer reads.
    Traps?A budget of URLs per host per cycle, and a hop limit.
    requirementtarget
    Fetch rateabout 3,858 pages a second, sustained
    Requests per hostone at a time, a delay apart
    robots.txtread before the first page of a host; obeyed for every path
    Same URL fetched twice in a cyclenever
    Same text stored twicenever
    Crawl survives a node failureits hosts move; no page is lost from the frontier

    I crawl 10 billion pages a month and obey robots.txt. Each host gets at most one request a second, and no URL is fetched twice in a cycle.

    B

    Estimates

    arithmetic shown
    rate
    10 B ÷ (30 × 86,400 s) ≈ 3,858 pages a second
    bandwidth
    3,858 × 100 KB × 8 ≈ 3.1 Gbit/s
    storage
    10 B × 100 KB = 1 PB a copy; ÷ 5 compressed ≈ 200 TB
    in flight
    3,858 a second × 1 s a fetch ≈ 3,858 open requests
    hosts
    one page per (1 s fetch + 1 s delay) per host: 3,858 ÷ 0.5 ≈ 7,716 hosts at once
    parsing
    386 MB/s ÷ 11 MB/s a core ≈ 35 cores
    seen-set
    50 B known URLs × 9.6 bits ≈ 60 GB
    links
    3,858 × 100 links ≈ 385,802 Bloom checks a second

    100 KB a page, 5× compression, 1 s a fetch, 100 links a page and 5 known URLs per page are assumptions; say them out loud. The parse rate and bits per URL come from the lab.

    About 3,858 pages a second and 3.1 Gbit/s. Politeness means about 7,716 hosts in rotation at any moment.

    C

    Interfaces

    a pipeline, not a public API
    callshape and result
    POST /seedsA list of URLs. 202; each goes to its owner node.
    frontier.addURL, hops, priority. On the node that owns the host.
    GET pageUser-Agent names the crawler and a contact URL; If-None-Match on a revisit. 200, 304, 404, 429, 503.
    PUT /blobs/:sha256Compressed page. Writing the same key twice is harmless.
    fetch logURL, status, ETag, blob key, simhash, fetched at. Parsers and the indexer read it.
    GET /urls/:urlLast fetch, status, next visit. For operators.

    429 and 503 slow the host down: honour Retry-After, and lengthen its delay.

    Each stage is idempotent: the frontier dedupes URLs, the blob key is the content hash, and the fetch log can be replayed.

    D

    Data model

    the key design per store
    storekeyvaluewhy this key
    URL table, wide-columntest.shop/item/3status, last fetch, ETag, fingerprint, change count, next visitReversed host first: one host is one key range, read and written by its owner.
    Host tableshop.testrobots rules and fetch time, delay, next allowed time, budget left, addresses and TTLOne row per host, on the node that owns it.
    Seen-setnormalised URL9.6 bits in a Bloom filter per nodeMembership only; no false negatives.
    Frontierhost, then hopsqueued URLs on disk; the ready heap in memoryPop by host, then by priority.
    FingerprintsSHA-256; simhashblob key; URL of the first copyExact lookup, and a near search by bits.
    Blob storeSHA-256 of the textcompressed pageContent address: the same text is one object (B9).
    Fetch logpartition by host hashone record per fetchStages read at their own speed and can replay.
    sizes
    60 GB of seen-set; about 200 TB of pages per copy; one URL row per known URL.
    near search
    At scale, store each simhash in several tables, each sorted on a different block of its bits, so a lookup scans a few short ranges.

    URLs are keyed by reversed host and path, so a host's URLs sort together. Pages are keyed by the hash of their text, so a copy costs nothing.

    E

    The architecture

    click a step; its path lights up
    Frontierper-host queuesFetchersone per hostWeb hostsrobots.txt, pagesBlob storekey: SHA-256DNS cacheTTL per hostParsersdedupe, linksSeedsstart URLsRecrawlnext visitIntakeowner node

    Step 1: Admit

    • Seeds and recrawls arrive as URLs. A hash of the host picks the node that owns it.
    • Normalise the URL, check the Bloom filter, the hop limit and the host budget.
    • Push the URL on its host's queue in that node's frontier.

    If it fails

    The node is down: its hosts move to the next node on the hash ring, which replays the frontier log.

    The frontier hands each ready host to a fetcher; the intake on the owner node fills the frontier. The diagram leaves out that last edge to stay readable.

    Owner nodes queue URLs per host, and fetchers take one host at a time. Pages go to blob storage, and parsers send links back to the owners.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    ServiceA queue per host and a heap of hosts by next allowed timeOne request per host at a time, a delay apart, with no idle fetcher.Timers, rate limits
    ServiceHash of the host, mod N (a hash ring at scale)One owner per host: politeness and dedupe without locks between nodes.Sharding
    ServiceBloom filterThe seen-set at 9.6 bits per URL, with no false negatives.LSM reads, caches
    ServiceURL normalisation (RFC 3986)Spellings of one page fold into one key before the filter.Cache keys
    ServiceSHA-256 and simhash fingerprintsExact and near copies are stored once and their links not followed.Spam, plagiarism checks
    HTTProbots.txt, keep-alive, ETag and If-None-MatchRules per site; one connection per host; a 304 on an unchanged revisit.CDNs, API clients
    DNSA resolver cache with TTLOne lookup per host per TTL instead of one per request.Every client
    Blob storeContent-addressed objectsA copy costs nothing; a retried put is harmless.Backups, build caches
    KafkaA partitioned log between stagesFetchers and parsers scale apart; a parser change can replay old fetches.Event pipelines
    RedisA bitmap Bloom filter shared by all nodesNot needed One network call per link; the owner node's local filter costs none.Shared dedupe

    The crawler is mostly data structures: a heap per node for politeness, a Bloom filter for URLs, and fingerprints for content.

    G

    Deep dive: the frontier and politeness

    per-host queues, a heap of hosts, an owner per host
    links inIntakenormaliseseen? Bloomhops, lengthhost budgetdropped: seen,over budgetone queue per host, by hopsforum.testreadynews.testwaits for its delaybooks.testwaits for Crawl-delayshop.testin flight: not in heapready heapmin next-allowed time1 forum.test2 news.test3 books.testdone(host): next =finish + delayfetcherfetcherthe request ends: the host goes back to the heapowner(host) = hash(host) mod N
    politeness methodwherestatus
    Queue per host, heap by next allowed timeServiceApproved
    One FIFO of all URLsServiceBursts one host
    Sleep in the fetcher after each requestServiceIdle fetchers
    Token bucket per hostServiceBurst size 1
    Shared queue, a distributed lock per hostRedisA lock per request
    the frontier on one nodepseudo code
    owner(host) = hash(host) mod N1            // one node per host
    
    add(url, hops):                          // on the owner node
      push url on queue[host], fewest hops first2
      IF host is idle and not in the heap3: push host
    
    next():                                  // a fetcher asks for work
      WAIT until heap.top.next_at <= now
      host = pop heap; host.busy = true
      IF host has no robots.txt yet: RETURN fetch robots.txt4
      RETURN pop queue[host]
    
    done(host, finished_at):
      host.busy = false
      host.next_at = finished_at + max(own delay, Crawl-delay)5
      IF queue[host] is not empty: push host on heap
    1. 1Every URL of a host lands on one node. At scale use a hash ring, so adding a node moves few hosts.
    2. 2The priority inside a host. A real crawler adds an importance score from links.
    3. 3A host with a request in flight is not in the heap, so no second fetcher can take it.
    4. 4The first request to a new host. Its rules and Crawl-delay apply to every later request.
    5. 5The gap counts from the end of a request, so a slow host is also asked less often.
    Tested source Go: frontier · Go: owner of a host · Go: robots.txt
    Go: frontiergo
    
    // Add queues a URL under its host and makes the host eligible if it is idle.
    func (f *Frontier) Add(it Item) {
      f.mu.Lock()
      defer f.mu.Unlock()
      h := f.hosts[it.URL.Host]
      if h == nil {
        h = &hostState{name: it.URL.Host, delay: f.delay, index: -1}
        f.hosts[it.URL.Host] = h
      }
      f.seq++
      it.seq = f.seq
      heap.Push(&h.queue, it)
      f.schedule(h)
    }
    
    // Next blocks until some host may be fetched, marks it busy and returns its next job: robots.txt
    // first for a new host, then its URLs by priority.
    func (f *Frontier) Next(ctx context.Context) (Job, error) {
      for {
        f.mu.Lock()
        wait := 20 * time.Millisecond
        if len(f.ready) > 0 {
          h := f.ready[0]
          if d := time.Until(h.nextAt); d > 0 {
            wait = d
          } else {
            heap.Pop(&f.ready)
            h.busy = true
            job := Job{Host: h.name, Robots: h.robots == nil}
            if !job.Robots {
              job.Item = heap.Pop(&h.queue).(Item)
            }
            f.mu.Unlock()
            return job, nil
          }
        }
        f.mu.Unlock()
        select {
        case <-ctx.Done():
          return Job{}, ctx.Err()
        case <-f.wake:
        case <-time.After(wait):
        }
      }
    }
    
    // Done ends the job on host. A request that finished at `at` makes the host wait its delay from
    // then; a zero `at` (no request was sent) keeps the host's time. A robots.txt job sets the rules
    // and the delay: the crawler's own, or the site's Crawl-delay when that is longer.
    func (f *Frontier) Done(host string, at time.Time, robots *Robots) {
      f.mu.Lock()
      defer f.mu.Unlock()
      h := f.hosts[host]
      h.busy = false
      if robots != nil {
        h.robots = robots
        h.delay = max(f.delay, robots.Delay)
      }
      if !at.IsZero() {
        h.nextAt = at.Add(h.delay)
      }
      f.schedule(h)
    }
    
    // schedule puts an idle host with work into the ready heap and wakes one waiting fetcher.
    func (f *Frontier) schedule(h *hostState) {
      if h.busy || h.index >= 0 || len(h.queue) == 0 {
        return
      }
      heap.Push(&f.ready, h)
      select {
      case f.wake <- struct{}{}:
      default:
      }
    }
    
    Go: owner of a hostgo
    
    // Owner is the node that owns host: a hash of the host name, modulo the node count. Every URL of
    // a host goes to one node, so one node enforces the host's delay and dedupes its URLs alone.
    func (c *Crawler) Owner(host string) int {
      return int(sketches.Hash(host) % uint64(len(c.nodes)))
    }
    
    Go: robots.txtgo
    
    // ParseRobots reads the group for agent, or the "*" group when no group names agent. Allow and
    // Disallow take path prefixes. Crawl-delay is in seconds; it is not in the standard (RFC 9309),
    // but many sites set it, so the crawler honours it when it is longer than its own delay.
    func ParseRobots(body, agent string) Robots {
      type group struct {
        agents []string
        r      Robots
      }
      var groups []*group
      var cur *group
      inAgents := false
      for line := range strings.Lines(body) {
        line, _, _ = strings.Cut(line, "#")
        key, val, ok := strings.Cut(line, ":")
        if !ok {
          continue
        }
        key, val = strings.ToLower(strings.TrimSpace(key)), strings.TrimSpace(val)
        switch key {
        case "user-agent":
          if !inAgents {
            cur = &group{}
            groups = append(groups, cur)
          }
          cur.agents = append(cur.agents, strings.ToLower(val))
          inAgents = true
          continue
        case "allow", "disallow":
          if cur != nil && val != "" {
            cur.r.rules = append(cur.r.rules, rule{prefix: val, allow: key == "allow"})
          }
        case "crawl-delay":
          if s, err := strconv.ParseFloat(val, 64); err == nil && cur != nil && s > 0 {
            cur.r.Delay = time.Duration(s * float64(time.Second))
          }
        }
        inAgents = false
      }
      var star *group
      for _, g := range groups {
        for _, a := range g.agents {
          if a == strings.ToLower(agent) {
            return g.r
          }
          if a == "*" && star == nil {
            star = g
          }
        }
      }
      if star != nil {
        return star.r
      }
      return Robots{}
    }
    
    // Allowed applies the longest matching rule; on a tie, Allow wins. No match means allowed.
    func (r Robots) Allowed(path string) bool {
      best, allow := -1, true
      for _, x := range r.rules {
        if !strings.HasPrefix(path, x.prefix) {
          continue
        }
        if n := len(x.prefix); n > best || (n == best && x.allow) {
          best, allow = n, x.allow
        }
      }
      return allow
    }
    
    hostnodedelayshortest gap, lab
    news.test140 ms40.6 ms
    blog.test140 ms40.7 ms
    forum.test040 ms40.4 ms
    shop.test140 ms40.4 ms
    books.test080 ms80.8 ms
    events.test040 ms40.5 ms

    Tested with 1, 2 and 3 nodes: on every host, two requests were never closer than its delay, measured at the server. Every request for a host came from the node that owns it.

    A fetcher pops the host whose next allowed time is earliest. When the request ends, the host goes back with next time equal to now plus its delay.

    H

    Deep dive: never twice

    normalised URLs, a Bloom filter, content fingerprints
    admit a link, store a pagepseudo code
    admit(link):                             // the intake on the owner node
      key = normalise(link)                  // one spelling per page1
      IF len(key) > 256 OR hops > limit: drop
      IF bloom.has(key): drop                // seen, or a false positive2
      bloom.add(key)
      IF admitted[host] >= budget: drop      // a trap ends here3
      frontier.add(key, hops)
    
    normalise(href, base):
      resolve against base; remove ./ and ../
      lowercase scheme and host; drop :80 and :443
      drop #fragment, utm_* and sessionid; sort the query
    
    store(page):                             // the parser
      text = the main text, without navigation4
      IF sha256(text) is stored: drop        // exact copy
      IF a stored simhash is within 14 bits5: drop
      put the page under sha256(text); route its links
    1. 1Without it, #comments, :80, utm_source and session ids each look like a new page.
    2. 2A false positive skips a page this cycle. A false negative cannot happen, so nothing is fetched twice.
    3. 3An infinite URL space still has one host. The budget caps what one host can cost per cycle.
    4. 4Copies differ in menus and links. Fingerprint the text a reader sees.
    5. 5Chosen from the measured distances on the right.
    Tested source Go: intake · Go: normalise · Go: parse and store
    Go: intakego
    
    // intake admits or drops each link that reaches this node: too long, too many hops, seen
    // before (Bloom filter), or past the host's budget. An admitted URL joins its host's queue.
    func (c *Crawler) intake(ctx context.Context, n *node) {
      for {
        var l link
        select {
        case <-ctx.Done():
          return
        case l = <-n.inbox:
        }
        key, host := l.u.String(), l.u.Host
        why := ""
        switch {
        case len(key) > c.cfg.MaxURLLen:
          why = SkipLong
        case l.hops > c.cfg.MaxHops:
          why = SkipHops
        case n.seen.Has(key):
          why = SkipSeen
        default:
          n.seen.Add(key)
          if n.admitted[host] >= c.cfg.HostBudget {
            why = SkipBudget
          }
        }
        if why != "" {
          c.event("skip", n.id, host, l.u.RequestURI(), why)
          c.work.Done()
          continue
        }
        n.admitted[host]++
        n.frontier.Add(Item{URL: l.u, Hops: l.hops})
        c.event("admit", n.id, host, l.u.RequestURI(), "")
      }
    }
    
    Go: normalisego
    
    // Normalize resolves href against base and returns one canonical spelling of the URL, so that
    // spellings of the same page dedupe to one key. It lowercases the scheme and host, drops a
    // default port, the fragment, tracking and session parameters, removes dot segments, and sorts
    // the query. Links that are not http or https return an error.
    func Normalize(base *url.URL, href string) (*url.URL, error) {
      ref, err := url.Parse(strings.TrimSpace(href))
      if err != nil {
        return nil, fmt.Errorf("parse %q: %w", href, err)
      }
      u := base.ResolveReference(ref) // also removes . and .. segments
      u.Scheme = strings.ToLower(u.Scheme)
      if u.Scheme != "http" && u.Scheme != "https" {
        return nil, fmt.Errorf("%q: scheme %q is not crawled", href, u.Scheme)
      }
      host, port := strings.ToLower(u.Hostname()), u.Port()
      if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") {
        port = ""
      }
      u.Host = host
      if port != "" {
        u.Host = host + ":" + port
      }
      u.Fragment, u.RawFragment, u.User = "", "", nil
      if u.Path == "" {
        u.Path = "/"
      }
      q := u.Query()
      for k := range q {
        if slices.Contains(dropParams, strings.ToLower(k)) {
          delete(q, k)
        }
      }
      u.RawQuery = q.Encode() // Encode sorts by key
      return u, nil
    }
    
    Go: parse and storego
    
    // parser stores each fetched page unless it copies a stored page, and sends its links, one hop
    // further, to the nodes that own them. A copy's links are not followed.
    func (c *Crawler) parser(ctx context.Context) {
      for {
        var f fetched
        select {
        case <-ctx.Done():
          return
        case f = <-c.parse:
        }
        u := f.item.URL
        if why := c.store.Put(MainText(f.body), f.body, c.cfg.NearBits); why != "" {
          c.event("skip", f.node, u.Host, u.RequestURI(), why)
          c.work.Done()
          continue
        }
        for _, m := range hrefRe.FindAllSubmatch(f.body, -1) {
          v, err := Normalize(u, string(m[1]))
          if err != nil { // a mailto: or javascript: link: count it and move on
            c.mu.Lock()
            c.skips[SkipScheme]++
            c.mu.Unlock()
            continue
          }
          c.send(link{u: v, hops: f.item.Hops + 1})
        }
        c.work.Done()
      }
    }
    
    seen-set for 50 B URLssizestatus
    Bloom filter per owner node, 1%60 GBApproved
    Sorted URL file, merged with each batchon diskExact
    Hash set of URLs in memoryterabytesNot approved
    One shared Redis setterabytesMemory, hops
    threshold 14 bits: near copy at or under2 words changed0 to 11 bits10 words changed2 to 19 bitsunrelated pages19 to 47 bits081624324048bits that differ
    simhashpseudo code
    simhash(text):
      votes = 64 counters at 0
      FOR EACH run of 3 words1 IN text:
        h = hash64(the 3 words)
        FOR EACH bit b: votes[b] += 1 IF h has b set ELSE -1
      RETURN the bits whose votes are > 02
    
    near(a, b) = popcount(a XOR b) <= 143
    1. 1Shingles: an edit changes only the 3 runs that contain the word.
    2. 2Similar texts share most votes, so most bits agree.
    3. 3The number of differing bits. Unrelated texts differ in about 32 of 64.
    Tested source Go: simhash
    Go: simhashgo
    
    // Simhash is a 64-bit fingerprint of a text in which similar texts get similar bits. Each run of
    // 3 words (a shingle) is hashed; every hash votes +1 on each bit it has set and -1 on each bit it
    // has clear; the fingerprint keeps the bits with a positive total. A small edit changes a few
    // shingles, which moves few totals across 0, so few bits differ.
    func Simhash(text string) uint64 {
      words := strings.Fields(strings.ToLower(text))
      var votes [64]int
      for i := 0; i+3 <= len(words); i++ {
        h := sketches.Hash(strings.Join(words[i:i+3], " "))
        for b := range 64 {
          if h>>b&1 == 1 {
            votes[b]++
          } else {
            votes[b]--
          }
        }
      }
      var fp uint64
      for b, v := range votes {
        if v > 0 {
          fp |= 1 << b
        }
      }
      return fp
    }
    
    // Distance is the number of bits in which two fingerprints differ.
    func Distance(a, b uint64) int { return bits.OnesCount64(a ^ b) }
    
    lab crawl
    327 links dropped as seen; 1 exact and 1 near copy dropped after the fetch.
    measured
    2-word edits: 0 to 11 bits. Unrelated pages: 19 to 47 bits.

    Tested: every one of the 50 pages of the synthetic web was requested exactly once, and no URL was requested twice. A 64-bit simhash over billions of pages has used a 3-bit threshold (Manku, Jain and Das Sarma, 2007); short pages need more.

    I normalise each URL and check a Bloom filter on the owner node. After the fetch, SHA-256 catches exact copies and simhash catches near copies.

    I

    Deep dive: traps, robots and recrawl

    limits, rules, change rate
    events.test/2604260526062607260826092610261126122701270227032704270512 months fetchedthen the host budget of 16 URLs ran out;2 next months dropped at the intakeEach box is a month (year, then month). Without a limit the chain never ends in either direction.
    trapdefence
    Calendars and next-page links with no endBudget per host; hop limit
    Session ids in URLsNormalisation drops them
    Filter and sort parameters in every orderSorted query; budget per host
    Repeating paths: /a/b/a/b/a/bURL length limit; repeated segments
    A site that answers 200 for any URLNear-copy fingerprint; budget
    recrawl and robots.txtpseudo code
    after each visit:
      send If-None-Match: last ETag          // 304: no body sent1
      changed = the text fingerprint differs
      interval = interval ÷ 2 IF changed ELSE interval × 1.52
      interval = clamp(interval, 1 hour, 30 days)3
      next_visit = now + interval
    
    robots(host):                            // once per host; reuse at most 24 h4
      rules = the group for our agent, else the * group
      allowed(path) = the longest matching rule; Allow wins a tie5
      delay = max(own delay, Crawl-delay)
    1. 1An unchanged page costs a request but no download.
    2. 2In the lab, a page that changes on a fixed period settles near 0.37 of it.
    3. 3A static page drifts to the ceiling; the crawl budget goes to pages that change.
    4. 4RFC 9309 asks crawlers not to use a cached robots.txt for more than 24 hours.
    5. 5The RFC 9309 rule: the longest match decides; on equal length, Allow.
    Tested source Go: next visit · Go: robots.txt
    Go: next visitgo
    
    // NextVisit adapts how long to wait before fetching a page again. A page that changed since the
    // last visit is visited twice as often; a page that did not is visited half as often again.
    // The interval stays within [lo, hi]. Pages that change often converge on short intervals, and
    // pages that never change drift to the ceiling, so fetches go where content changes.
    func NextVisit(interval time.Duration, changed bool, lo, hi time.Duration) time.Duration {
      if changed {
        interval /= 2
      } else {
        interval += interval / 2
      }
      return min(max(interval, lo), hi)
    }
    
    Go: robots.txtgo
    
    // ParseRobots reads the group for agent, or the "*" group when no group names agent. Allow and
    // Disallow take path prefixes. Crawl-delay is in seconds; it is not in the standard (RFC 9309),
    // but many sites set it, so the crawler honours it when it is longer than its own delay.
    func ParseRobots(body, agent string) Robots {
      type group struct {
        agents []string
        r      Robots
      }
      var groups []*group
      var cur *group
      inAgents := false
      for line := range strings.Lines(body) {
        line, _, _ = strings.Cut(line, "#")
        key, val, ok := strings.Cut(line, ":")
        if !ok {
          continue
        }
        key, val = strings.ToLower(strings.TrimSpace(key)), strings.TrimSpace(val)
        switch key {
        case "user-agent":
          if !inAgents {
            cur = &group{}
            groups = append(groups, cur)
          }
          cur.agents = append(cur.agents, strings.ToLower(val))
          inAgents = true
          continue
        case "allow", "disallow":
          if cur != nil && val != "" {
            cur.r.rules = append(cur.r.rules, rule{prefix: val, allow: key == "allow"})
          }
        case "crawl-delay":
          if s, err := strconv.ParseFloat(val, 64); err == nil && cur != nil && s > 0 {
            cur.r.Delay = time.Duration(s * float64(time.Second))
          }
        }
        inAgents = false
      }
      var star *group
      for _, g := range groups {
        for _, a := range g.agents {
          if a == strings.ToLower(agent) {
            return g.r
          }
          if a == "*" && star == nil {
            star = g
          }
        }
      }
      if star != nil {
        return star.r
      }
      return Robots{}
    }
    
    // Allowed applies the longest matching rule; on a tie, Allow wins. No match means allowed.
    func (r Robots) Allowed(path string) bool {
      best, allow := -1, true
      for _, x := range r.rules {
        if !strings.HasPrefix(path, x.prefix) {
          continue
        }
        if n := len(x.prefix); n > best || (n == best && x.allow) {
          best, allow = n, x.allow
        }
      }
      return allow
    }
    
    robots.txt answerwhat the crawler does
    200Apply the group for its agent, else the * group
    404Crawl everything (events.test in the lab)
    5xx or unreachableAssume full disallow; try again later (RFC 9309)
    Crawl-delayNot in the RFC; honour it when longer than the own delay

    Tested: shop.test disallows /cart/, and none of its 3 cart pages was requested. Over 180 simulated days, a static page sat at the 30-day ceiling.

    Every host gets a budget per cycle, robots.txt is read first and cached, and pages that change often are visited often.

    J

    See it: the frontier queues drain

    recorded from a lab crawl; press play
    queued URLsrequests to the host over timenode 0books.testdelay 80 ms0events.testdelay 40 ms0forum.testdelay 40 ms0node 1blog.testdelay 40 ms0news.testdelay 40 ms0shop.testdelay 40 ms0

    Seeds go to the intake of the node that owns each host.

    pages fetched
    0 of 62
    seen before
    0 links
    host budget
    0 links dropped
    robots.txt
    0 URLs not fetched
    copies
    0 exact, 0 near

    robots.txt page fetch. On every host, two marks are at least one delay apart; the shortest gap measured was 0.4 ms over the delay.

    Each host's queue drains one request per delay. The crawl made 68 requests in 675 ms, and every gap was at least the host's delay.

    K

    Failure cases

    what breaks, and why no site is hammered
    eventresultwhy it is safesaved by
    A host is slow or hangsThe request times out.The host is busy only for that request; other hosts keep moving.Timeout
    A site answers 429 or 503It is overloaded.Honour Retry-After and lengthen that host's delay.Host delay
    robots.txt answers 5xxThe rules are unknown.Assume full disallow and try later, as RFC 9309 says.robots.txt
    A crawler node diesIts hosts stop.The hash ring moves them; the next owner replays the frontier log.Hash ring
    A parser diesPages wait in the log.It resumes from its offset; blob puts and link admits are idempotent.Fetch log
    The DNS resolver is slowNew hosts wait.Cached answers serve known hosts until their TTL.DNS cache
    The Bloom filter gives a false positiveA new page is skipped.Found next cycle with a fresh filter; nothing is fetched twice.Bloom
    An infinite URL spaceLinks never end.The host budget drops them; the lab fetched 12 months.Budget
    One page under many URLsSpellings differ.Normalisation folds them; the text fingerprint catches the rest.Fingerprint
    L

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One node, frontier in memory2+ frontier on disk, Bloom3+ N nodes by host hash4+ fetchers per regionmore load →
    Work per second against one core1001k10k100k1M10MPages to fetch: 3,858 per secondPages to fetch3,858Links to check: 385,802 per secondLinks to check385,802Parse, 1 core, lab: 308 per secondParse, 1 core, lab308Bloom checks, 1 core, lab: 5,200,000 per secondBloom checks, 1 core, lab5,200,000per second, log scale
    stepaddit handlesmove up when you see
    1One node: frontier and seen-set in memory, async fetchers.About 308 pages a second per core to parse; each host one page per delay.The frontier or the URL set outgrows memory.
    2Frontier on disk, a Bloom filter for seen URLs.Billions of queued URLs; 9.6 bits per known URL in memory.One node's network or cores saturate.
    3N nodes by host hash, with a fetch log between stages.3,858 pages a second needs about 35 parse cores and 3.1 Gbit/s, split over nodes.Fetches to far regions take most of the time.
    4Fetchers in several regions, each host to the nearest.Shorter round trips; a host stays with one owner.Top of the ladder.

    Demand, derived in panel B. Lab rates come from one laptop core; read them as orders of magnitude.

    About 35 cores parse the stream, and a Bloom check is cheap. The limit is politeness: I need thousands of hosts in rotation, split by host hash.

    M

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    How do you size the Bloom filter?m = −n ln p ÷ (ln 2)² bits and k = (m ÷ n) ln 2 hashes. At 1% that is 9.6 bits and 7 hashes per URL.B10
    A node joins. Do all hosts move?With a hash ring, only the hosts between the new node and its neighbour move. Mod N would move most of them.X2
    How do pages reach the index?The indexer reads the fetch log, tokenises the text and builds inverted lists per term.B8
    Where do the pages live?In blob storage, keyed by content hash and compressed. Old versions expire by policy.B9
    Why a log between fetchers and parsers?The stages run at different speeds and fail apart. A new parser can replay old fetches.B6
    Is politeness a rate limit?Yes, per host, with a burst of 1. The heap enforces it without a counter per request.B3
    Why one connection per host?A kept-alive connection saves a handshake per page, and one connection is the polite load.B1
    A host times out often. What then?Lengthen its delay, cap its retries, and stop for a while after repeated failures.O2
    How do you rank which pages to fetch first?A link-based score from the last cycle, computed in a batch job, sets the priority in the frontier.B7
    N

    Drill

    predict, then reveal

    0 of 10 known

    1. Two crawler nodes discover links to the same host. How do you keep its requests one at a time?

    2. Why a heap of hosts and not a sleep in the fetcher after each request?

    3. The Bloom filter says "seen" for a URL that was never fetched. What happens?

    4. How large is the seen-set for 50 billion URLs?

    5. What stops the infinite calendar?

    6. Why is the near-copy threshold 14 bits here and not 3?

    7. books.test sets Crawl-delay to twice the crawler delay. What gap did the lab measure?

    8. Why fingerprint the main text and not the whole HTML?

    9. A page changes every 6 hours. How often does the adaptive rule visit it?

    10. Why cache DNS?

    O

    Numbers to say

    derived and measured
    rate
    10 B pages in 30 days: 3,858 a second, 3.1 Gbit/s.
    hosts
    About 7,716 hosts in rotation at 1 page per 2 s each.
    parse
    About 308 pages a second per core on 34 KB pages (11 MB/s).
    Bloom
    9.6 bits per URL at 1%; about 5.2 million checks a second per core.
    simhash
    Edits of 2 words: at most 11 bits; unrelated: at least 19 bits.
    lab crawl
    62 pages, 6 DNS lookups, 327 seen links dropped, gaps at least the delay (+0.4 ms).
    events.test
    Budget 16: 4 pages, 12 calendar months, the rest dropped.

    Go on an 8-core laptop shared with other jobs; the crawl ran against a local server with a 40 ms delay. Use the lab numbers as orders of magnitude.