Case study: design a web crawler
A senior-level walkthrough of a web crawler: the URL frontier and politeness, robots.txt, URL normalization and the seen set, partitioning by host, duplicates and revisits, traps and failures, with tested C#.
Case studyApplied40 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 2 data models
- 2 API designs
- 1 live simulation
- 6 code samples
- 8 interviewer follow-ups
- 1 decision checkpoint
- 4 self-checks
On this page16 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Queues and asynchronous work, Rate limiting
- A crawler is limited by politeness, not by workers or bandwidth. A global queue ran at 1,000 pages a second and sent 65% of its requests to a host less than a second after the last one. Per-host queues were polite but took 918 minutes for the same pages, because one host held 54,978 of them.
- Build the frontier in two layers. Priority decides what is worth fetching, and a queue per host with a heap of next-allowed times decides when. Cap the pages taken from any one host, and note that past about 300 workers adding more changes nothing.
- Read robots.txt by status first (a 404 means no rules, a 5xx means stay away), then by the longest matching rule, and normalize every URL before asking whether it is new: 98,499 spellings of 20,000 pages became 20,000.
- Keep the seen set in a Bloom filter at about 10 bits a URL, 12 GB for ten billion, and know its error: it never forgets a URL and skips about 1% of new ones, so it is rebuilt with new seeds.
- Partition all state by host so that politeness needs no coordination, find near-duplicate pages with simhash, and spend revisits where they buy the most freshness, using the sibling lesson on near-duplicates and freshness.
6 code samples (258 lines), collapsed so the explanation stays in focus.
A web crawler starts from a few known pages, fetches them, pulls out the links, and fetches those, again and again, handing what it finds to something else: a search index, an archive, a price tracker, a training set. The loop fits in one sentence, which is why interviewers like the question. The loop is easy. The constraints are what make it a design problem.
There are three. The crawler is a guest on other people's servers, so how fast it may go is decided by each site and not by the crawler's hardware. The web is endless and repetitive: one page has many addresses, many pages are copies of other pages, and some sites generate links without end. And the web keeps changing, so the crawl is never finished and the question is always which pages are worth fetching again.
This lesson builds the design around those three and tests the core pieces in C#: three frontier policies on a skewed web, a robots.txt matcher and a URL normalizer. Finding near-duplicate pages and deciding when to visit a page again have enough theory to be a lesson of their own, near-duplicates and freshness, and this lesson summarises what an answer needs from it. It leans on rate limiting for politeness, on queues for the frontier, and on probabilistic data structures and search for the seen-set filter and for what happens to the pages afterwards.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| What is the crawl for? | A search index wants breadth and freshness. An archive wants fidelity and keeps the raw bytes. A price tracker wants a few hundred sites, very fresh |
| The whole web, or a list of sites? | Billions of pages need a partitioned frontier and a compact seen set. A few thousand sites fit on one machine with a good frontier |
| How fresh must pages be? | News within minutes needs feeds and a priority lane. The long tail can wait a month. Freshness is a budget, not a setting |
| HTML only, or also scripts, PDFs and images? | Running a page's scripts in a headless browser costs far more than fetching it, so it is a separate, budgeted stage |
| What do we promise sites? | Obey robots.txt, say who we are with a contact address, limit the load on each host, and honour removal requests |
| What must never happen? | Hammering one site, wandering forever in a trap, fetching what robots.txt forbids, losing the frontier in a crash |
A good scope for 45 minutes: crawl the public web for a search index, HTML only, a billion pages a month, polite to every host, deduplicated, and revisited by a policy. Mention JavaScript rendering, forms behind logins and focused crawling of one topic as extensions.
State assumptions out loud. They are illustrative and the interviewer may change them.
target: 1 billion pages a month (assumed)
rate: 1e9 / (30 x 86,400 s) = ~390 pages a second
peak: 2x after an outage or a backlog = ~800 a second
page: ~100 KB of HTML, ~25 KB compressed on the wire (assumed)
bandwidth: 390 x 25 KB = ~10 MB/s, about 80 Mbit/s
storage: 1e9 x 25 KB = ~25 TB of raw pages a month
links: ~40 links per page = ~40e9 URLs offered a month
new: assume 1 in 20 is new = ~2e9 new URLs a month
seen set: ~10e9 URLs ever seen x 9.6 bits = ~12 GB (Bloom filter)
checks: 40e9 a month = ~15,000 "is it new?" questions a second
in flight: 390 a second x 0.3 s a fetch (Little) = ~120 at once
one host: 1 request a second = 86,400 pages a day, at most
big site: 10M pages / 86,400 = ~116 days from one host alone
refresh: 10e9 pages and 1e9 fetches a month = once in 10 monthsFive conclusions:
- Bandwidth and storage are modest. Eighty megabits a second and 25 TB a month is a handful of ordinary machines. Nothing here needs special hardware.
- Concurrency, not CPU, sizes the fleet. By Little's law about 120 fetches are in flight at once, and an asynchronous fetcher holds thousands per machine. The work is waiting on other people's servers.
- Politeness is the real ceiling. A site that may be contacted once a second yields at most 86,400 pages a day. A host with ten million pages takes 116 days however many workers exist, so the biggest sites decide how long a crawl takes.
- "Have we seen this?" is the hottest operation. Forty links per page and nineteen of twenty already known means about 15,000 checks a second, which must be answered from memory.
- The crawl never ends. A corpus ten times the monthly fetch budget can be revisited once in ten months on average. Which pages to revisit, and how often, is the real scheduling problem.
A crawler has no public API. The contract that matters is internal, between the frontier and the fetchers.
| Call | Who calls it | Meaning |
|---|---|---|
POST /v1/urls | The link filter, and seed loaders | Offer discovered URLs, already normalized, with a priority hint |
POST /v1/leases | A fetcher | Take up to N due URLs, each from a different host, for a short lease |
POST /v1/results | A fetcher | Report how each fetch ended: status, final URL, validators, content hash, links, timing |
GET /v1/hosts/{host} | An operator | Show the host's rules, gap, budget and recent errors |
- auth
- service token of a fetcher
- body
- { "worker": "f-4172", "max": 50 }
- note
- every URL in one lease is from a different host, and a host is leased to one worker at a time, so politeness needs no coordination between fetchers
- note
- a lease that expires puts its URLs back in the frontier, and fetching a page twice is harmless
- 200{ "lease_id": "l_77", "expires_at": "2026-11-17T10:05:00Z", "urls": [ { "url_id": "u_8c1", "url": "https://shop.example/p/1", "host": "shop.example" } ] }
- 204nothing is due yet
- auth
- service token of a fetcher
- idempotency
- lease_id plus url_id, so a retried report counts once
- body
- { "url_id": "u_8c1", "status": 200, "final_url": "https://shop.example/p/1", "etag": "\"v7\"", "content_hash": "9f2c...", "links": 41, "fetch_ms": 310 }
- note
- 304 means unchanged and carries no body, 429 and 503 carry a Retry-After that lengthens the host's gap, and a network error is recorded by class
- 200recorded, the next fetch time is set by the refresh policy
url_hashbigint
64-bit hash of the normalized URL
PKhosttext
SHARD KEYINDEXurltext
statetext
new, queued, leased, fetched, failed or disallowed
prioritysmallint
1 is best, set from importance and how fresh it must be
next_fetch_attimestamptz
when it is due, set by the refresh policy
INDEXetagtext
validators for a conditional request
NULLlast_modifiedtext
NULLcontent_hashbigint
exact-duplicate check
NULLsimhashbigint
near-duplicate check
NULLvisitsint
how often we looked
changes_seenint
how often it had changed since the visit before
fail_countsmallint
The change rate is not stored: it is estimated from visits and changes_seen.
hosttext
PKrobotstext
the file as last fetched
NULLrobots_statussmallint
how that fetch ended, which decides what is allowed
robots_fetchedtimestamptz
read it again after a day
gap_msint
least time between requests, raised by errors and slow answers
next_allowedtimestamptz
the heap key: when this host may be contacted next
budget_leftint
pages still allowed in this period
errors_recentsmallint
drives the backoff
The pages themselves go to object storage, and the link graph to a column store used for ranking.
Read it as three loops around the frontier, the structure that holds every URL still to be fetched. The fetch loop takes a due URL, checks the host's rules and fetches politely. The discovery loop parses the page, normalizes its links, drops the ones already seen and feeds the rest back. The refresh loop records whether the page had changed and sets when it is due again. Each loop has its own pressure: the fetch loop is limited by politeness, the discovery loop by the speed of the "have we seen this?" question, and the refresh loop by a budget that can never cover everything.
Partition every piece of crawler state by host, not by URL. All the URLs of a host then live on one node, and so does everything that must be consistent about that host: when it may next be contacted, its robots.txt, its page budget, its cached DNS answer, and the part of the seen set that holds its URLs. Politeness needs no coordination between nodes, because only one node ever talks to a host.
- Placement. Hash the host name onto a ring (see replication and sharding), so that adding or losing a node moves about one host in N.
- Discovery crosses nodes. A parser that finds a link to a host owned elsewhere sends it to that node in batches, and the owner does the seen check and the enqueue.
- Balance by hosts, not by pages. Politeness caps every host at about one request a second, so the load on a node follows the number of hosts it owns that have work, not their URL counts. A huge site is not a hot node. It is a long tail in time, which is why it gets a budget.
- A node dies. Its hosts move to the next nodes on the ring. The new owner rebuilds their queues from the URL table (every row whose state is queued), reads each robots.txt again, and waits one gap before the first request. Pages in flight are leased again when their leases expire, and fetching a page twice is harmless.
- Decouple the stages. The fetcher writes the page to object storage and publishes an event, and the parser, duplicate detector and indexer read the stream at their own speed (see logs and Kafka), so a slow parser backs up a queue and not the fetchers.
- DNS is a bottleneck of its own. Resolve hosts asynchronously, cache answers for their time to live (failures too), and resolve a host as soon as it enters the frontier.
The frontier is the crawler's to-do list, and it has two jobs that pull in opposite directions: hand out the most valuable URLs first, and never contact one host too often. A single priority queue does the first and ruins the second, because the best URLs often sit on the same few sites.
The standard answer, used by Mercator and described in most textbooks, has two layers. Front queues sort URLs by priority (importance, how overdue a refresh is, how shallow the page is). Back queues hold the URLs of one host each, first in first out, and a heap orders the hosts by the time each may next be contacted. A fetcher takes the host at the top of the heap, waits if it is not due yet, fetches one URL, and puts the host back with its next-allowed time set to now plus the gap. A back queue that empties is refilled from the front queues. Mercator's designers suggested about three times as many back queues as fetch threads, so that some host is always ready.
Before the code, commit to one answer.
Decision checkpoint · pick one
A crawl of half a million URLs on five thousand hosts runs from one shared queue. The sites that hold the most pages are complaining about bursts of requests. What do you change first?
Commit to an answer first. The reasoning for every option appears after you pick.
The simulation compares three policies on a web with the skew real sites have: 500,000 URLs on 5,000 hosts, the host at rank r holding a share proportional to 1/r (a Zipf shape), so the biggest host has 54,978 URLs, the hundredth 550 and the smallest 11. There are 300 workers, a fetch takes 0.3 seconds, and a host should not be contacted more than once a second.
C# · CrawlRun, Frontier
using System;
using System.Collections.Generic;
using System.Linq;
public sealed record CrawlRun(int Fetched, double Seconds, int Violations, int MaxConcurrentOnAHost, double Utilization);
public static class Frontier
{
// A global first-in first-out queue: a free worker takes the next URL, whichever host it belongs to. Fast, and rude.
public static CrawlRun Fifo(int[] urlsPerHost, int workers, double fetchSeconds, double gap, Random random)
{
var queue = new List<int>();
for (int h = 0; h < urlsPerHost.Length; h++) queue.AddRange(Enumerable.Repeat(h, urlsPerHost[h]));
for (int i = queue.Count - 1; i > 0; i--) { int j = random.Next(i + 1); (queue[i], queue[j]) = (queue[j], queue[i]); } // links from everywhere arrive mixed
var free = new PriorityQueue<int, double>();
for (int w = 0; w < workers; w++) free.Enqueue(w, 0);
var lastStart = new double[urlsPerHost.Length];
Array.Fill(lastStart, double.NegativeInfinity);
var activeOnHost = new int[urlsPerHost.Length];
var finishing = new PriorityQueue<(int Host, double At), double>();
int violations = 0, maxConcurrent = 0;
double end = 0, busy = 0;
foreach (int host in queue)
{
free.TryDequeue(out int worker, out double start);
while (finishing.TryPeek(out var f, out double at) && at <= start) { finishing.Dequeue(); activeOnHost[f.Host]--; }
if (start - lastStart[host] < gap) violations++;
lastStart[host] = start;
maxConcurrent = Math.Max(maxConcurrent, ++activeOnHost[host]);
finishing.Enqueue((host, start + fetchSeconds), start + fetchSeconds);
free.Enqueue(worker, start + fetchSeconds);
end = Math.Max(end, start + fetchSeconds);
busy += fetchSeconds;
}
return new CrawlRun(queue.Count, end, violations, maxConcurrent, busy / (workers * end));
}
// One queue per host and a heap of hosts ordered by the time each may next be contacted. A free worker takes the host that is
// due first and waits for it if need be, so no host ever sees two requests closer than `gap`. `budget` caps pages per host.
public static CrawlRun PerHostQueues(int[] urlsPerHost, int workers, double fetchSeconds, double gap, int budget)
{
var remaining = urlsPerHost.Select(n => Math.Min(n, budget)).ToArray();
var due = new PriorityQueue<int, double>();
for (int h = 0; h < remaining.Length; h++) if (remaining[h] > 0) due.Enqueue(h, 0);
var nextAllowed = new double[remaining.Length];
var free = new PriorityQueue<int, double>();
for (int w = 0; w < workers; w++) free.Enqueue(w, 0);
int fetched = 0;
double end = 0, busy = 0;
while (due.TryDequeue(out int host, out _))
{
free.TryDequeue(out int worker, out double freeAt);
double start = Math.Max(freeAt, nextAllowed[host]); // wait here if the host is not due yet
nextAllowed[host] = start + gap;
if (--remaining[host] > 0) due.Enqueue(host, nextAllowed[host]);
free.Enqueue(worker, start + fetchSeconds);
end = Math.Max(end, start + fetchSeconds);
busy += fetchSeconds;
fetched++;
}
return new CrawlRun(fetched, end, 0, 1, busy / (workers * end));
}
}C#
using System;
using System.Diagnostics;
using System.Linq;
const int Hosts = 5_000;
double harmonic = Enumerable.Range(1, Hosts).Sum(k => 1.0 / k);
int[] urls = Enumerable.Range(1, Hosts).Select(k => (int)Math.Round(500_000 / harmonic / k)).ToArray();
Console.WriteLine($"{urls.Sum()} URLs, the biggest host has {urls[0]}, the 100th {urls[99]}, the smallest {urls[^1]}");
var rude = Frontier.Fifo(urls, 300, 0.3, 1.0, new Random(5));
var polite = Frontier.PerHostQueues(urls, 300, 0.3, 1.0, budget: int.MaxValue);
var budgeted = Frontier.PerHostQueues(urls, 300, 0.3, 1.0, budget: 2_000);
void Show(string name, CrawlRun r) => Console.WriteLine($"{name,-22} {r.Fetched,7} pages in {r.Seconds / 60,7:F0} min, {r.Fetched / r.Seconds,6:F0} pages/s, requests too close together {r.Violations,6} ({r.Violations / (double)r.Fetched:P0}), most at once on one host {r.MaxConcurrentOnAHost,3}, workers busy {r.Utilization:P0}");
Show("global FIFO", rude);
Show("per-host queues", polite);
Show("per-host, 2,000 cap", budgeted);
Debug.Assert(rude.Violations > rude.Fetched / 2 && rude.MaxConcurrentOnAHost > 20); // fast, and it hammers the hosts
Debug.Assert(polite.Violations == 0 && polite.Seconds > 10 * 3600); // polite, and it needs more than ten hours
Debug.Assert(budgeted.Violations == 0 && budgeted.Seconds < polite.Seconds / 20); // a cap per host ends it in minutes
// Politeness, not the number of workers, sets the pace: past about 300 workers, more of them change nothing.
var sweep = new[] { 30, 100, 300, 1_000, 3_000 }.Select(w => (Workers: w, Run: Frontier.PerHostQueues(urls, w, 0.3, 1.0, budget: 2_000))).ToList();
foreach (var (workers, run) in sweep)
Console.WriteLine($"{workers,5} workers: {run.Fetched / run.Seconds,4:F0} pages/s, {run.Seconds / 60:F0} min, workers busy {run.Utilization:P0}");
Debug.Assert(sweep[0].Run.Seconds > sweep[2].Run.Seconds * 1.5); // too few workers is slower
Debug.Assert(sweep[4].Run.Seconds > sweep[2].Run.Seconds * 0.9); // ten times as many is not faster| Policy | Pages | Time | Pages a second | Requests too close together | Most at once on a host | Workers busy |
|---|---|---|---|---|---|---|
| Global FIFO queue | 499,988 | 8 min | 1,000 | 322,896 (65%) | 55 | 100% |
| Queue per host | 499,988 | 918 min | 9 | 0 | 1 | 1% |
| Queue per host, 2,000 pages a host at most | 340,042 | 35 min | 163 | 0 | 1 | 16% |
The same three queues at a size you can watch: 121 URLs on 12 hosts, again with one big host and a long tail. Open the simulation, run each queue, then move the number of workers.
Try it · simulationCrawl floor: one crawl, three queues
What the numbers say:
- A global queue is the fastest and the rudest. Links from everywhere arrive mixed, so a free worker takes whatever is next. 65% of requests came less than a second after another to the same host, and up to 55 were in flight to one host at once. From that host's side it looks like an attack.
- Per-host queues are polite, and the slowness is real. The biggest host holds 54,978 URLs and may be contacted once a second, so it alone needs more than 15 hours. The crawl takes 918 minutes with 99% of the workers idle. The size of the fleet is not the problem.
- A budget changes the question. Capping each host at 2,000 pages ends the crawl in 35 minutes and leaves out 159,946 pages from the deep end of the largest sites. "How fast" becomes "which 2,000 are worth fetching", and priority answers it: take each host's best pages, not its first ones.
- More workers do not help. With the budget, 30 workers manage 82 pages a second, 100 manage 139, 300 manage 163, and 1,000 and 3,000 manage 169 and 170. The floor is the biggest host: 2,000 URLs at one a second is 33 minutes.
The speed of a polite crawler is the number of hosts it can work on at once divided by the gap, so crawls spread across sites instead of drilling into one. Real politeness is more than a fixed gap. Say who you are, with a User-Agent that links to a page with contact details. Start near a second, lengthen the gap when a host is slow or failing, and shorten it only with evidence: a 429 or 503 means slow down, and Retry-After says for how long (RFC 9110 (opens in a new tab)). Use one connection at a time per host and count a renderer's subresource requests against it. Do not depend on Crawl-delay: the robots.txt standard defines only user-agent, allow and disallow, so crawlers differ on whether they read it.
Before the first fetch from a host, the crawler fetches /robots.txt, the file where a site says what automated visitors may do. The Robots Exclusion Protocol was a convention for almost thirty years and became RFC 9309 (opens in a new tab) in 2022. It is advice, not access control: a page the file asks crawlers to avoid is still public. The rules are short, and the edge cases are where candidates slip.
| Situation | What the standard says | Why it matters |
|---|---|---|
| The file answers 2xx | Parse it. Use the group for your own product token, otherwise the * group | A crawler called examplebot follows its own group and ignores the * one |
| 404 or another 4xx | The file is unavailable, so the crawler may fetch anything | A site without a file has no rules |
| 5xx, or no answer | The file is unreachable, so assume everything is disallowed | A failing server is not permission. Retry later |
| Two rules match a URL | The longest pattern wins, and allow wins a tie | Disallow: /private with Allow: /private/press opens the press pages |
| Patterns | A prefix. * matches any run of characters and a final $ anchors the end | /*.pdf$ blocks PDF files and not /a.pdfx |
| How long to keep a copy | At most about a day, longer only if the host cannot be reached | Rules change, and a stale copy is a politeness bug |
C# · What a crawler may fetch from one host, decided from that host's robots.txt (RFC 9309).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
// What a crawler may fetch from one host, decided from that host's robots.txt (RFC 9309).
public sealed class RobotsPolicy
{
private readonly bool _allowAll, _disallowAll;
private readonly List<(bool Allow, string Pattern)> _rules = new();
private RobotsPolicy(bool allowAll, bool disallowAll) { _allowAll = allowAll; _disallowAll = disallowAll; }
// The status code decides before the body does: no file means no rules, and a host that cannot answer means stay away.
public static RobotsPolicy FromResponse(int status, string body, string agent)
{
if (status >= 200 && status < 300) return Parse(body, agent);
return status >= 400 && status < 500 ? new RobotsPolicy(true, false) : new RobotsPolicy(false, true);
}
public static RobotsPolicy Parse(string body, string agent)
{
var groups = new List<(List<string> Agents, List<(bool Allow, string Pattern)> Rules)>();
bool lastWasAgent = false;
foreach (string raw in body.Split('\n'))
{
string[] kv = raw.Split('#')[0].Split(':', 2);
if (kv.Length < 2) continue;
string field = kv[0].Trim().ToLowerInvariant(), value = kv[1].Trim();
if (field == "user-agent")
{
if (!lastWasAgent) groups.Add((new List<string>(), new List<(bool, string)>())); // user-agent lines in a row share a group
groups[^1].Agents.Add(value.ToLowerInvariant());
}
else if ((field == "allow" || field == "disallow") && groups.Count > 0 && value.Length > 0) // "Disallow:" alone blocks nothing
groups[^1].Rules.Add((field == "allow", value));
lastWasAgent = field == "user-agent";
}
var mine = groups.Where(g => g.Agents.Contains(agent.ToLowerInvariant())).ToList(); // its own group, else the * group
if (mine.Count == 0) mine = groups.Where(g => g.Agents.Contains("*")).ToList();
var policy = new RobotsPolicy(false, false);
foreach (var g in mine) policy._rules.AddRange(g.Rules);
return policy;
}
// The longest matching rule wins, and an allow beats a disallow of the same length. No match means allowed.
public bool Allowed(string pathAndQuery)
{
if (pathAndQuery == "/robots.txt") return true;
if (_disallowAll) return false;
int best = -1;
bool allowed = true;
foreach (var (allow, pattern) in _rules)
{
if (!Matches(pattern, pathAndQuery)) continue;
if (pattern.Length > best || (pattern.Length == best && allow)) { best = pattern.Length; allowed = allow; }
}
return _allowAll || allowed;
}
// A pattern is a prefix. * matches any run of characters and a final $ means the URL must end there.
private static bool Matches(string pattern, string target)
{
bool anchored = pattern.EndsWith('$');
string body = Regex.Escape(anchored ? pattern[..^1] : pattern).Replace("\\*", ".*");
return Regex.IsMatch(target, "^" + body + (anchored ? "$" : ""), RegexOptions.CultureInvariant);
}
}C#
using System;
using System.Diagnostics;
string file = @"
User-agent: *
Disallow: /private
Allow: /private/press
Disallow: /*.pdf$
Disallow: /search?
User-agent: examplebot
Disallow: /
Allow: /public
";
var anyBot = RobotsPolicy.Parse(file, "otherbot");
Debug.Assert(!anyBot.Allowed("/private/report"));
Debug.Assert(anyBot.Allowed("/private/press/kit")); // the longer rule wins
Debug.Assert(anyBot.Allowed("/Private/report")); // paths are case sensitive
Debug.Assert(!anyBot.Allowed("/files/a.pdf") && anyBot.Allowed("/files/a.pdfx")); // * and $
Debug.Assert(!anyBot.Allowed("/search?q=cats") && anyBot.Allowed("/search"));
var named = RobotsPolicy.Parse(file, "ExampleBot"); // its own group applies, and the * group does not
Debug.Assert(!named.Allowed("/index.html") && named.Allowed("/public/a") && !named.Allowed("/private/press/kit"));
Debug.Assert(RobotsPolicy.Parse("User-agent: *\nAllow: /a\nDisallow: /a", "x").Allowed("/a/b")); // equally specific: allow wins
Debug.Assert(RobotsPolicy.Parse("User-agent: *\nDisallow:", "x").Allowed("/anything")); // an empty Disallow blocks nothing
// Status first: a missing file is permission, a failing server is not.
Debug.Assert(RobotsPolicy.FromResponse(404, "", "x").Allowed("/anything"));
Debug.Assert(!RobotsPolicy.FromResponse(200, "User-agent: *\nDisallow: /", "x").Allowed("/anything"));
var down = RobotsPolicy.FromResponse(503, "", "x");
Debug.Assert(!down.Allowed("/anything") && down.Allowed("/robots.txt")); // stay away, but keep asking for the file
Console.WriteLine("robots.txt: longest match, allow wins ties, 404 allows, 503 forbids");Where the policy lives and when it is checked:
- In the host store, fetched before the first URL of a host is leased and read again after a day, with the status of the fetch, because the status decides what is allowed.
- Right before every fetch, not only when a link is found, since a URL queued last week may be disallowed today. A disallowed URL is dropped and marked
disallowed, so the next page that links to it does not queue it again. - A failing file pauses the host until a retry with backoff gets an answer.
- It controls fetching, not secrecy and not the index. A URL blocked from crawling can still be known from links elsewhere.
The same page has many URLs. HTTP://Example.COM:80/a/b/../c, http://example.com/a/c?utm_source=news and the same address followed by #top are one page. Without normalizing, the crawler fetches it three times and counts three new links, so the first defence is to write every URL in one canonical form before asking whether it has been seen.
Some rules never change which page a URL names (the syntax-based normalization of RFC 3986): lowercase the scheme and host, drop the default port and a trailing dot on the host, resolve . and .. segments, write percent-escapes in one form, and drop the fragment, because the server never sees it. Crawlers add two heuristics: sort the query parameters, and drop parameters that identify a visitor or a campaign (utm_*, fbclid, gclid). What to leave alone matters as much. A trailing slash, index.html, a leading www. and http against https can be different pages on some servers, so guessing there trades duplicates for lost pages. A page's canonical link and a hash of its content catch the rest later.
C# · UrlNormalizer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public static class UrlNormalizer
{
// Query parameters that identify a visitor or a campaign, not a page. Dropping them is a heuristic, so keep the list short and explicit.
private static readonly HashSet<string> Tracking = new(StringComparer.OrdinalIgnoreCase) { "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid" };
public static string Normalize(string url)
{
var u = new Uri(url);
string host = u.IdnHost.ToLowerInvariant().TrimEnd('.');
string port = u.IsDefaultPort ? "" : ":" + u.Port;
string path = DecodeUnreserved(u.AbsolutePath); // dot segments are already resolved by Uri
var pairs = u.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('=', 2))
.Where(p => !Tracking.Contains(p[0]))
.OrderBy(p => p[0], StringComparer.Ordinal).ThenBy(p => p.Length > 1 ? p[1] : "", StringComparer.Ordinal)
.Select(p => DecodeUnreserved(p.Length > 1 ? p[0] + "=" + p[1] : p[0]));
string query = string.Join("&", pairs);
return $"{u.Scheme.ToLowerInvariant()}://{host}{port}{path}{(query.Length > 0 ? "?" + query : "")}";
}
// %7E and %7e mean "~", which needs no escape, and %2f and %2F are the same escape: write each in its one canonical form.
private static string DecodeUnreserved(string s) => Regex.Replace(s, "%([0-9a-fA-F]{2})", m =>
{
char c = (char)Convert.ToInt32(m.Groups[1].Value, 16);
return char.IsAsciiLetterOrDigit(c) || c is '-' or '.' or '_' or '~' ? c.ToString() : "%" + m.Groups[1].Value.ToUpperInvariant();
});
}C# · The same page written in many ways collapses to one canonical URL.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// The same page written in many ways collapses to one canonical URL.
string[] same =
{
"HTTP://Example.COM:80/a/b/../c/index.html?b=2&a=1#top",
"http://example.com/a/c/index.html?a=1&b=2",
"http://example.com./a/./c/index.html?utm_source=news&a=1&b=2&fbclid=xyz",
"http://EXAMPLE.com/a/c/index.html?a=1&b=2#section-3",
};
Debug.Assert(same.Select(UrlNormalizer.Normalize).Distinct().Count() == 1);
Debug.Assert(UrlNormalizer.Normalize("https://example.com:443/%7euser/x%2fy") == "https://example.com/~user/x%2Fy");
Debug.Assert(UrlNormalizer.Normalize("https://example.com:8443/p") == "https://example.com:8443/p"); // a non-default port is part of the identity
// Pages that really differ must stay different: another query value, another path, a trailing slash (which servers may treat differently).
string[] different = { "http://example.com/a?id=1", "http://example.com/a?id=2", "http://example.com/a/", "http://example.com/a", "http://example.com/A" };
Debug.Assert(different.Select(UrlNormalizer.Normalize).Distinct().Count() == different.Length);
// 20,000 pages, each linked from elsewhere in five different spellings.
var spell = new Random(4);
var spellings = new List<string>();
for (int page = 0; page < 20_000; page++)
{
string canonical = $"http://site{page % 500}.example/section{page % 37}/item{page}?id={page}&lang=en";
for (int variant = 0; variant < 5; variant++)
{
string u = canonical.Replace("http://", spell.Next(2) == 0 ? "http://" : "HTTP://").Replace(".example/", spell.Next(2) == 0 ? ".example:80/" : ".EXAMPLE/");
if (spell.Next(2) == 0) u += "&utm_campaign=c" + spell.Next(100);
if (spell.Next(2) == 0) u += "#frag" + spell.Next(100);
if (spell.Next(2) == 0) u = u.Replace("?id=" + page + "&lang=en", "?lang=en&id=" + page);
spellings.Add(u);
}
}
Console.WriteLine($"{spellings.Count} spellings, {spellings.Distinct().Count()} distinct as written, {spellings.Select(UrlNormalizer.Normalize).Distinct().Count()} after normalizing");
Debug.Assert(spellings.Select(UrlNormalizer.Normalize).Distinct().Count() == 20_000);A hundred thousand spellings of 20,000 pages came to 98,499 different strings as written and 20,000 after normalizing, and the pages that really differ stayed apart.
Now the seen set. Ten billion URLs stored exactly, as an 8-byte hash each, is 80 GB queried 15,000 times a second. A Bloom filter in front answers "definitely new" or "probably seen" from memory. The probabilistic data structures lesson sizes one from the formulas and measures it: about 9.6 bits and 7 hashes per item for a 1% false-positive rate, and it measured 1.01% against a 1.00% design. For ten billion URLs that is 12 GB, which splits across the nodes that already partition the frontier by host.
The error falls on the crawler's cheap side, and it is worth saying exactly how. Nothing that was added is ever forgotten, so a URL is never fetched twice because the filter lost it. But about 1% of new URLs are wrongly judged seen, and since bits are never cleared, a URL that collides once collides every time it is offered, so it stays lost. Two habits contain the damage. Rebuild the filter now and then with a different hash seed, so that a page lost to one filter is not lost to the next, and let seeds, sitemap entries and high-priority URLs bypass the filter and use an exact lookup in the URL table. The filter is a shortcut for the long tail of ordinary links, not the source of truth.
Two more jobs sit behind the fetchers, and each has enough theory to be a lesson of its own: near-duplicates and freshness builds both in tested C#. What an interview answer needs from it fits in two paragraphs.
Duplicate pages. The same content turns up under many URLs: mirrors, printer-friendly versions, syndicated articles, a page whose only change is a counter. A hash of the extracted text finds identical copies and misses everything else, so a crawler also keeps a 64-bit simhash of each page's main content. Every three-word shingle votes on every bit and the fingerprint is the sign of each total, so pages that share most of their text are a few bits apart: unrelated pages averaged 31.9 bits apart in the test, and one word changed in 300 moved a page 2.7 bits. Two pages within 3 bits are copies (the paper by Manku, Jain and Das Sarma uses 64 bits and 3 for eight billion pages). Finding the neighbours without a scan uses the pigeonhole principle: cut the fingerprint into blocks and keep a table for each choice of the blocks that must match. Four tables of 16-bit keys returned exactly the full-scan answer while comparing about 13 of 200,000 fingerprints, and at web scale about twenty tables of 32-bit keys leave about 41 to compare among eight billion. Fingerprint the main content and not the whole page, because a shared template makes different pages look alike, and let the result steer the crawl: a URL pattern that keeps producing copies loses priority and budget.
Revisits. A crawler whose monthly budget is a tenth of its corpus can revisit each page once in ten months on average, so it must choose. Model a page's changes as random at lambda a day and its visits as f a day: the copy is fresh for (1 - e^-x) / x of the time, with x = lambda / f, and a visit buys about one over lambda days of freshness. That makes visiting in proportion to the change rate a trap (it left 9.9% of a 10,000-page copy fresh, against 73.6% for visiting every page equally), and the best allocation, which puts each visit where it buys the most and gives the fastest pages none, kept 77.4%. The crawler does not know lambda, so it estimates it from visits that say only whether a page changed, with an estimator that corrects for the changes hidden between visits (it recovered 2.00 changes a day where counting reported 0.86). Cheap revisits use conditional requests (If-None-Match with the stored ETag, answered 304 with no body). Sitemaps and feeds are hints to trust only as far as a site's history supports, and home pages and listings get a budget of their own because they link to new pages.
Some pages are harmless to people and ruinous to a crawler, and most of the defences are budgets, which the frontier already has.
| Trap or awkward page | What it looks like | Defence |
|---|---|---|
| An endless calendar, filter combinations or a growing path | A "next month" link that never ends, every mix of filters, /a/b/a/b/... | A page budget per host, a depth limit, a cap on URL length and on URLs per pattern |
| Session ids in the URL | One page under a new address for every visitor | Drop known session parameters, and let the content hash catch the rest |
| A soft 404 | A missing page answers 200 with an error message | Fetch a made-up URL on the host once, fingerprint the answer, and treat pages that match it as errors |
| Pages that need scripts | Almost no text in the HTML | A separate render stage with its own budget |
The pattern cap deserves a sentence. Replace every run of digits and every query value in a URL with a placeholder, count the URLs seen for each pattern on each host, and stop taking new ones once a pattern passes its limit. A calendar collapses to /calendar/#/# and is capped after the first thousand URLs. The cap is crude, because a large honest catalogue also yields one pattern with a million URLs, so let priority and the duplicate detector say whether the pages behind a busy pattern are worth having.
JavaScript is a different cost, not only a bigger one. A headless browser loads a page's scripts, styles and images, runs them and waits, which takes far more time and memory than a fetch, and every resource it loads is another request to that host or a third party. So rendering is a second stage: decide from the raw HTML which pages need it, give the stage its own budget and workers, and apply the same per-host politeness to every request it makes.
| Case | What goes wrong | Handle it |
|---|---|---|
| robots.txt answers 5xx or times out | Crawling blind, or never crawling the host again | Treat it as disallow-all, pause the host, retry the file with backoff, and check the policy before every fetch |
| robots.txt is huge or malformed | The parser stalls or reads the rules wrong | Cap what is read (the standard asks parsers to handle at least 500 KiB), skip lines that do not parse, never let one bad line allow everything |
| A host is slow, hangs, or answers 429 or 503 | Workers pile up on it, or the crawler hammers a site that asked for relief | One connection at a time, timeouts, a gap that grows with latency and errors, Retry-After honoured, and a lower budget for the period |
| A spider trap, or one page under many URLs | One host's queue grows without end, and results repeat | Page, depth and pattern budgets, normalization, canonical links, content hashes and simhashes |
| Redirect loops, giant or endless responses | A loop, or memory and bandwidth burned on one URL | Follow at most five redirects, cap bytes read and bytes after decompression, accept listed content types only |
| DNS is slow or failing | Fetchers block on lookups | Asynchronous resolver, a cache per host with its time to live, negative caching, resolve early |
| A crawler node dies | Its hosts' queues are lost | Reassign the hosts, rebuild their queues from the URL table, lease again after expiry, and wait one gap before the first request |
| Two workers hold one host | Two requests at once | Lease by host with a deadline, one heap entry per host, and gaps measured on a monotonic clock |
| The Bloom filter fills up | The false-positive rate climbs and new URLs are skipped | Size it for the expected count, rebuild with a new seed, and send important URLs to an exact lookup |
| A site asks not to be crawled | A legal and trust problem | Honour it at once, with a global deny list that the frontier checks |
Interviewer follow-upL5How do you make sure the crawler does not overload a website?How to answer
One queue per host and a heap of the time each host may next be contacted, so a host sees at most one request per gap however many workers there are. Read its robots.txt first, say who you are in the User-Agent, and lengthen the gap when the host is slow or answers 429 or 503. In the simulation a shared queue sent 65% of its requests to a host less than a second after the last one and put up to 55 on one host at once, and per-host queues sent none.
Interviewer follow-upL5How do you avoid fetching the same URL twice?How to answer
Normalize first (lowercase the host, drop the default port and the fragment, resolve dot segments, sort and trim the parameters), then check a seen set. At web scale that is a Bloom filter at about 10 bits a URL, 12 GB for ten billion, partitioned by host like the frontier. It never forgets a URL and wrongly skips about 1% of new ones, so rebuild it with a new seed now and then and send important URLs through an exact lookup. In the test, 98,499 distinct spellings of 20,000 pages came to 20,000 after normalizing.
Interviewer follow-upL6A single site has 50 million pages. How do you crawl it?How to answer
Not all of it, and not fast. At one request a second the site takes about 580 days (50 million divided by 86,400 seconds in a day), so politeness sets the floor. Give the host a budget for each period and spend it by priority, use the sitemap and feeds to find what changed, send conditional requests on revisits, and ask whether the site offers a feed or a data dump. Raise the rate only with the owner's agreement.
Interviewer follow-upL6How do you detect duplicate pages?How to answer
Two layers. A hash of the extracted text catches exact copies. A 64-bit simhash of the main content catches near copies, which are pages within 3 bits. To avoid a full scan, cut the fingerprint into blocks and keep a table for each choice of the blocks that must match: four tables of 16-bit keys at small scale, about twenty of 32-bit keys at eight billion. Strip the boilerplate first, because a shared template makes different pages look alike. The near-duplicates lesson tests all of it.
Interviewer follow-upL6How do you decide how often to recrawl a page?How to answer
Estimate each page's change rate from its visit history, then give visits where they buy the most freshness, weighted by importance. A visit buys about one over the change rate in days, so the fastest pages get none and the middle ones the most. Visiting in proportion to the change rate is the trap: it left 9.9% of the test copy fresh, against 73.6% for visiting every page equally and 77.4% for marginal gain. Cap it by each host's budget, and use conditional requests so an unchanged page is cheap.
Interviewer follow-upL6How do you spread the crawl across machines?How to answer
By host. Everything that must agree about a host, its next allowed time, rules, budget, DNS answer and slice of the seen set, lives on one node, so politeness needs no coordination. Place hosts with consistent hashing, forward discovered links to the owner in batches, and balance by hosts and not pages, because politeness caps every host's rate. When a node dies its hosts move to others, which rebuild their queues from the URL table and wait one gap before the first request.
Interviewer follow-upL7How would you keep news fresh within minutes while everything else refreshes monthly?How to answer
Give news its own lane, with its own budget and workers so a backlog cannot starve it. Seed it from feeds, sitemaps and the home and section pages of news sites, which are visited every few minutes because they link to new articles, and fetch each new article once, soon after it appears. Use marginal gain with weights that favour recent and widely linked pages, and let the long tail follow the slow schedule. Watch discovery lag, the time between an article appearing and being fetched.
Interviewer follow-upL7How would you test a crawler before pointing it at the real web?How to answer
Against a simulated web: generated hosts with chosen latency, error rates, robots.txt files, redirects, calendars and duplicate pages, all on one machine. Assert the invariants on every run: no host contacted twice within its gap, nothing disallowed fetched, the frontier size bounded, each URL fetched at most once per period, and a killed node's hosts picked up by others. Then run at a low rate against a few sites you control, and only then widen it.
- Clarify: what the crawl is for, how big, how fresh, and what we promise sites.
- Estimate: about 390 pages a second, 80 Mbit/s, 120 fetches in flight, and the line that matters, one request a second per host.
- Draw it: frontier, fetchers, host store, parser, link filter and seen set, duplicate detector, refresh scheduler.
- Go deep on the frontier: priority in front, a queue per host and a heap of next-allowed times behind it, a budget per host, and why a shared queue is rude.
- Politeness and robots.txt: the gap, adaptive backoff, the rules by status code.
- Avoid repeats: normalize, a Bloom filter, exact duplicates by hash, near duplicates by simhash.
- Revisit: why proportional loses, marginal gain with weights, conditional requests.
- Scale and close: partition by host, rebuild from the URL table, then traps, a failing robots.txt and rendering as a second stage.
A web crawler is a scheduler that must be polite to every host and thrifty with every fetch, and politeness, not hardware, sets its speed: a shared queue ran at 1,000 pages a second and sent 65% of its requests to a host too soon, while per-host queues were polite but took 918 minutes because one host held 54,978 pages. The frontier therefore has priority in front and a queue per host behind it with a heap of next-allowed times, plus a budget per host, and past about 300 workers more workers change nothing. robots.txt is read by status first (404 means no rules, 5xx means stay away), then by the longest matching rule. URLs are normalized (98,499 spellings of 20,000 pages became 20,000) and checked in a Bloom filter that never forgets one but skips about 1% of new ones. Duplicate pages are found with a 64-bit simhash of the main content and block tables, and revisits go where a visit buys the most freshness, which skips the fastest pages (see near-duplicates and freshness). State is partitioned by host so politeness needs no coordination, traps are contained by budgets, and rendering is a separate budgeted stage.
Try answering out loud before you reveal each answer.
QuestionWhy does a shared queue of URLs make a crawler rude, and what replaces it?Reveal answer
Links from everywhere arrive mixed, so a free worker takes whichever URL is next and several workers can reach one host together. In the test 65% of requests came less than a second after another to the same host, and up to 55 were in flight to one host at once. A queue per host with a heap of the time each host may next be contacted fixes it: a worker takes the host that is due, so no host sees two requests closer than the gap, whatever the number of workers.
QuestionA site has ten million pages and allows one request a second. How long does it take, and what do you do?Reveal answer
Ten million divided by 86,400 seconds in a day is about 116 days, however many workers there are. So the host gets a budget, its pages are crawled by priority and not arrival, the sitemap and conditional requests find what changed, and the crawler accepts that it will not have every page. In the test a budget of 2,000 pages a host turned a 918-minute crawl into 35 minutes.
QuestionA site's robots.txt answers 404 on one visit and 503 on the next. What does the crawler do each time?Reveal answer
A 404 means the file is unavailable, so there are no rules and the crawler may fetch. A 503 means the file is unreachable, so the crawler assumes everything is disallowed, pauses the host and retries the file with backoff. When the file does parse, the group for the crawler's own name applies, else the * group, the longest matching rule wins and allow wins a tie. The policy is kept for about a day and checked before every fetch, not only when a link is found.
QuestionWhy normalize URLs before checking the seen set, and what does the Bloom filter get wrong?Reveal answer
Without normalizing, one page under several spellings is fetched several times: in the test 98,499 distinct strings were 20,000 pages. A Bloom filter at about 10 bits a URL never forgets a URL it was given, but it wrongly calls about 1% of new URLs seen, and since bits are never cleared those URLs stay skipped. Rebuild it with a new seed now and then, and send seeds, sitemap entries and high-priority URLs to an exact lookup.
- Allan Heydon and Marc Najork, Mercator: A Scalable, Extensible Web Crawler, World Wide Web 2(4), 1999: the frontier with a queue per host.
- Christopher Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval, chapter 20, and its section on the URL frontier (opens in a new tab): front queues for priority, back queues for politeness, and the heap.
- RFC 9309, Robots Exclusion Protocol (opens in a new tab) (2022): groups, the longest match, and what each status code means.
- Hsin-Tsang Lee, Derek Leonard, Xiaoming Wang and Dmitri Loguinov, IRLbot: Scaling to 6 Billion Pages and Beyond, WWW 2008: a crawler built around disk-based duplicate checks and per-domain budgets.
- Google Search Central, Reduce the Googlebot crawl rate (opens in a new tab): 500, 503 and 429 responses with
Retry-Afteras the signal to slow a crawler down. - The Sitemaps protocol (opens in a new tab):
lastmod, and the limits of 50,000 URLs and 50 MB for a file. - Alex Xu, System Design Interview (ByteByteGo, 2020), the web crawler chapter.
- The papers behind simhash and the refresh policies (Charikar; Manku, Jain and Das Sarma; Cho and Garcia-Molina) are listed with near-duplicates and freshness.