Design a web crawler: BFS frontier, politeness, dedup
A billion pages a month, each fetched without angering its host, stored for five years, and revisited when it changes. Almost every hard decision in this design lives inside one component — the queue that decides what to fetch next, and when.
400 /sSustained download rate, from 1B pages a month (§1)
29%Of pages are duplicates. The dedup gate pays for itself (§2)
10–200 msDNS resolution per lookup — the biggest fetch stall (§5)
30 PBFive years of HTML at 500 KB per page (§1)
Key points
Plain BFS floods one host, because most links on a page point back to the same host. That is not a tuning problem — it reads as a denial-of-service attack and gets you blocked.
The fix is structural rather than advisory: one host maps to exactly one queue, and one queue feeds one worker one page at a time. A burst becomes unrepresentable, not merely discouraged.
Two separate “seen?” gates, in a specific order. Content dedup runs before link extraction so duplicates cost nothing; URL dedup runs after filtering so junk never enters the visited set.
Outcomes
01Derive crawl load and storage from a monthly page target.
02Explain why BFS floods one host and how per-host queues make that impossible.
03Place both dedup gates correctly and justify the ordering.
04Name the highest-leverage fetch optimisation and defend the choice with numbers.
01
Scope first: 1 billion pages a month
The clarifying questions remove entire design branches. Purpose is search-engine indexing, not archiving. Volume is 1 billion pages per month. Content is HTML only, which deletes the image and video pipelines. Freshness is required, so recrawls are part of the load rather than an afterthought. HTML is kept for five years. Duplicate content is ignored, which mandates a dedup structure.
A good crawler then earns four adjectives, each of which maps to a numbered requirement: (1) scalable through parallel downloads, (2) robust against traps and crashes, (3) polite to the servers it fetches from, (4) extensible to new content types without a redesign.
Sustained download rate400 /s
Peak download rate800 /s
Storage per month500 TB
Storage over five years30 PB
📏 Log scale. 1B ÷ 30 days ÷ 86,400 s ≈ 400/s, doubled to 800 at peak. At 500 KB per page that is 500 TB a month, and 60 months of retention gives 30 PB.
Two conclusions follow immediately. First, a frontier holding hundreds of millions of URLs cannot live purely in memory, which forces the hybrid disk-plus-buffer design in §4. Second, freshness recrawls ride on top of this intake, so every efficiency number below understates the real load.
02
The pipeline: eleven boxes, one loop
The basic algorithm is three lines: download the URLs, extract new URLs from the pages, repeat. At 400 pages per second that loop needs eleven components — and the order matters more than the count.
How to read: The top row is the fetch path, the bottom row is the link-harvest path running right to left, and the curved arrow closes the loop. The two amber diamonds are the dedup gates.
Eleven boxes, but only two decisions: have I seen this content? and have I seen this URL? Everything else is plumbing around those two questions.
03
Why plain BFS hammers one host
The web is a directed graph — pages are nodes, links are edges — so crawling is graph traversal. Depth-first dives down one branch and buries the crawler in one corner of the web, so crawlers use breadth-first with a FIFO queue. But plain BFS has two failures, and both are visible at scale.
Option A
DFS — deep, narrow, trappable
Stays inside one site for a very long time.
Finds deep pages fast but starves the breadth a search index needs.
Depth can run away entirely on calendar pages and similar traps.
Option B
BFS — broad, fair, impolite
Dequeues in arrival order, keeping coverage broad and fresh.
Most links on a page point back to the same host, so the queue fills with runs of same-host URLs.
Treats every URL as equal, so the Apple homepage waits behind a forum post.
How to read: Each tick is one HTTP request to wikipedia.org. Same crawler, same throughput, two queue designs.
Politeness costs you nothing in aggregate. It only constrains how much of your throughput any single host absorbs.
Try it: press Run, let it settle, then press Switch design. Total crawler throughput barely changes — watch instead where those fetches land, and how quickly a host blocks you in shared mode.
tick 0design: one shared FIFOpages fetched: 0hosts blocking us: 0
Host
Queued
Fetched this tick
Their view of us
wikipedia.org
0
0
nytimes.com
0
0
blog.io
0
0
shop.com
0
0
The crawler does the same amount of work in both modes. Politeness does not cost throughput — it only constrains how much of your throughput any single host absorbs.
The priority failure is quieter but just as real: with no notion of importance, recrawl budget spreads evenly instead of favouring pages that change often or rank highly. Both failures live in the queue, so both fixes live there too. That queue has a name.
04
The frontier: front queues pick what, back queues pick when
The frontier splits into two halves with one job each, and the split is the central idea of this whole design.
How to read: Step through it. Left half is prioritisation, right half is politeness. They are deliberately separate, because “which page matters most” and “which server can take a request right now” are unrelated questions.
The selector between the halves is also where freshness policy lives: recrawls re-enter the front queues with a priority, so the same machinery that ordered the first crawl orders every recrawl.
Storage: neither memory nor disk alone
Hundreds of millions of frontier URLs fit neither purely in memory, which is not durable at that scale, nor purely on disk, which bottlenecks every enqueue. The frontier is therefore hybrid: the bulk lives on disk, with in-memory enqueue and dequeue buffers that batch transfers, so the disk cost is amortised over many queue operations.
05
Fetch fast without getting banned
Before any fetch, read the host's robots.txt — the Robots Exclusion Protocol, which states which paths you may request. Cache it per host, or you re-download it on every page.
Then four optimisations, each aimed at a measured bottleneck:
Optimisation
Bottleneck it removes
Why it is worth it
DNS cache
Resolution costs 10–200 ms per lookup and blocks the calling thread
At 400 pages/s, even 10 ms per fetch is 4 seconds of thread time per second. This is the single highest-leverage change
Geographic locality
Round-trip distance on every download
Crawl servers near the hosts they fetch. Day 3's 150 ms Atlantic crossing, removed
Short timeouts
One dead host holding a worker indefinitely
A worker blocked on a hung server is a worker not crawling. Cap it and move on
Distribution
One machine's throughput ceiling
Split crawl jobs across servers and threads, each owning a slice of URL space
The Bloom filter has relatives, and a crawler needs two of them
Structure
Answers
Where a crawler needs it
Bloom filter
“Have I seen this?” — no false negatives, some false positives.
URL seen. Billions of URLs in a few GB.
Counting Bloom / cuckoo filter
The same, but deletable. A counting Bloom replaces each bit with a small counter; a cuckoo filter stores fingerprints and can be resized.
The plain Bloom filter cannot delete and cannot grow — so if you ever need to forget a URL (a site asks for removal, or a page 404s permanently) you would otherwise have to rebuild the whole filter. Cuckoo filters are also more space-efficient below about a 3% error rate.
HyperLogLog
“How many distinct things have I seen?” — to within ~2%, in about 12 KB regardless of the count.
“How many unique hosts have we crawled this month?” An exact answer means holding every host; HLL answers it in constant memory, and sketches from different crawl servers merge, so you get a fleet-wide figure without shipping any data.
Count-Min Sketch
“How often has this appeared?” — never undercounts, sometimes overcounts.
Finding heavy hitters: which hosts are consuming most of the crawl budget, which URL patterns look like a spider trap. Exact counting needs a counter per key; the sketch is fixed-size.
The shared idea: trade a bounded, one-sided error for constant memory. The skill is being able to say which direction the error runs — Bloom filters over-claim membership, Count-Min over-claims frequency, and HyperLogLog is symmetric but approximate. Get the direction wrong and you will reason your way to the opposite conclusion.
Interview tip
Asked for the single highest-leverage optimisation, say the DNS cache, and justify it with arithmetic: every fetch starts with a lookup, and 10–200 ms × 400 pages/s dominates every other fetch cost in the system. Naming a number is what separates this from a list of good practices.
Assigning URL slices across servers
Distribution has a failure mode of its own: if slices are assigned naively with hash(host) % N, adding or removing a crawl server reshuffles everything — and every reshuffled host loses its politeness state and its robots.txt cache. Use consistent hashing (Day 6) so a membership change moves only a few shards. Note what is on the ring here: hosts, not URLs, because all URLs for one host must stay with one server for politeness to hold.
The hostile web
Redundant content. 29% of pages are duplicates. Compare hashes, not characters — character-by-character comparison cannot survive billions of pages.
Spider traps. Infinite directory chains, calendars with a “next month” link forever. No universal detector exists, so contain them with maximum URL length and depth limits, plus manual exclusion of offending sites.
Data noise. Ads, spam URLs, tracking parameters. Filter before they spend storage.
Crashes. Persist crawl state so a restart resumes instead of starting over. At 400 pages/s, losing a day's progress is 34 million pages.
A polite frontier in fifty linespython
import time
from collections import defaultdict, deque
class PoliteFrontier:
def __init__(self, politeness_s=1.0):
self.queues = defaultdict(deque)# one FIFO per host: politeness lives hereself.last_fetch = {}# host -> timestamp of last download
self.politeness_s = politeness_s
self.seen = set()# URL Seen: kills loops and refloods
def add(self, url, priority=0):
if url in self.seen:
return False # already queued or fetched: drop it
self.seen.add(url)
host = url.split('/')[2]
if priority > 0:
self.queues[host].appendleft(url) # front-queue behaviour: important first
else:
self.queues[host].append(url)
return True
def next(self, host, now=None):
now = time.time() if now is None else now
if now - self.last_fetch.get(host, 0) < self.politeness_s:
return None # too soon: this host gets a breather
if not self.queues[host]:
return None
self.last_fetch[host] = now
return self.queues[host].popleft()
f = PoliteFrontier(politeness_s=10.0)
for u in ['http://a.com/1', 'http://a.com/2', 'http://b.com/1', 'http://a.com/1']:
print(u, 'accepted:', f.add(u)) # the repeat is refused
print('first a.com:', f.next('a.com', now=100.0)) # served
print('retry at +1s:', f.next('a.com', now=101.0)) # None — polite wait
print('retry at +11s:',f.next('a.com', now=111.0)) # served after the gap
The lines that matter are the per-host queues, the last-fetch timestamps, and the seen set. One FIFO per host plus a politeness gap makes bursts unrepresentable. Priority insertion at the left puts important URLs first. The seen set rejects a URL the second time it appears, which kills both duplicate work and crawler loops in one line.
Q&A
Check yourself
Q1Your crawler respects a 1-second-per-host delay and still gets blocked by a large news site. Their logs show steady, well-spaced requests. What is the most likely cause?
The delay is too short; raise it to 5 seconds
You are running several crawl servers and each independently holds a 1-second delay for that host
Their rate limiter is misconfigured
✓ Several crawl servers, each politely spacing its own requests. Politeness state is per-process. With ten crawl servers that each wait a second, the host receives ten requests per second and sees nothing polite about it. This is exactly why hosts — not URLs — go on the consistent hashing ring: all URLs for a host must route to one server so there is a single place holding last_fetch for it. Raising the delay papers over the bug and wastes nine-tenths of your capacity.
Q2Your URL-seen set is a Bloom filter. A colleague points out Bloom filters have false positives. What does that actually mean for the crawler, and is it acceptable?
Unacceptable — you would crawl pages twice
A false positive means a new URL is wrongly reported as seen, so you silently skip it. Acceptable at a low rate, and tunable
False positives only affect memory usage
✓ You silently skip a page you have never crawled. Bloom filters never report “not seen” for something already added, so you will never re-crawl — the error is in the other direction, and it is a coverage loss, not a correctness loss. At a 1% false-positive rate you miss roughly 1% of the web, which is a reasonable trade for fitting billions of URLs in a few gigabytes instead of hundreds. Tune the bit array and hash count to the rate you can accept, and note that the filter cannot be resized — size it for the final corpus, or shard it. Interviewers like this one because it tests whether you know which direction the error runs.
Q3An increasing share of pages render their links with JavaScript, so your extractor finds nothing. What are your options and what do they cost?
Use a regex to find URLs in the JavaScript source
Render pages in a headless browser — correct but one to two orders of magnitude more expensive per page
Skip JavaScript-heavy sites entirely
✓ Headless rendering, applied selectively. Executing the page in a headless browser is the only reliable way to see client-rendered links, and it costs roughly 100× the CPU and memory of a plain fetch — at 400 pages/s that is not something you do for everything. The practical design is a two-tier fetcher: plain HTTP by default, and route to a smaller render pool only when a page looks client-rendered (near-empty <body>, a known SPA framework, or a site-level flag). Many crawlers also look for sitemap.xml and server-side rendered variants first, because those are free. Regex over JavaScript source finds some URLs and invents others; it is a stopgap, not an answer.
Q4How do you decide when to recrawl a page you already have, given a fixed crawl budget?
Recrawl everything on a fixed schedule, say weekly
Estimate each page's change rate from its own history and spend budget where change is likely and the page matters
Recrawl only pages that received traffic
✓ Estimate per-page change rate, weighted by importance. A fixed schedule spends the same budget on a news homepage that changes hourly and an archived PDF that has not changed in a decade — wasting most of it while still serving stale news. The standard approach tracks whether content changed on each visit and adapts the interval per page (back off on no-change, tighten on change), then multiplies by an importance signal so high-value pages get a shorter floor. This is also why the same front-queue machinery handles recrawls: a recrawl is just a URL with a priority. Crucially, a recrawl that finds no change still costs a fetch — which is why conditional requests with If-Modified-Since and ETag matter, since a 304 response costs almost nothing.
Q5You are asked to extend the crawler to also download images. What in the design has to change?
Nearly everything — the pipeline is built for HTML
Very little: add a downloader module for the new type. The frontier, politeness and dedup are content-agnostic
Only the storage layer
✓ Very little — and that is requirement (4) being tested. The frontier does not care what is at the end of a URL; politeness is about hosts; URL-seen is about strings; content-seen is about hashes. A new content type is a plug-in downloader and a storage target. The things that do change are capacity assumptions: images are far larger than 500 KB of HTML, so your storage estimate and bandwidth budget both move, and image URLs often sit on CDN hosts where per-host politeness is unnecessarily strict. The interviewer is checking whether your design has a seam there, or whether “HTML” is baked into the middle of it.
In practiceWhat production adds, and the questions that come next optional
This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
Queues vs logs
Broker-managed queue (SQS, RabbitMQ) vs. partitioned log (Kafka): consumption model difference
Replay and time travel: why a log gives it and a queue generally does not
Probabilistic structures
Reservoir sampling and t-digest/quantile sketches for percentile estimation
Terms used
URL frontier
The queue of URLs waiting to be crawled. Holds both the prioritisation and the politeness logic.
Front queue
Priority-ranked queue deciding what to crawl next.
Back queue
Per-host queue deciding when. One host, one queue, one worker.
Politeness delay
The minimum gap between two requests to the same host.
robots.txt
The Robots Exclusion Protocol file stating which paths a crawler may request. Cache it per host.
Spider trap
A site structure generating infinite URLs. Contained by depth and length limits, not detected automatically.
Content seen
Dedup by hashing the page body, before link extraction.
URL seen
Dedup by URL, after filtering. Usually a Bloom filter at this scale.
Bloom filter
Compact probabilistic set. Here, false positives mean silently skipping a page.
Conditional request
If-Modified-Since or ETag, letting a server answer 304 Not Modified cheaply.
What breaks next. A crawler pulls work toward itself at a pace it controls. Day 11 is the opposite situation: work arrives on someone else's schedule, delivery depends on companies you do not control, and the requirement is that nothing is ever lost — which turns out to be impossible to combine with “nothing is ever duplicated.”
Source: System Design Interview, Ch. 9 — Design a web crawler (pp. 132–150). The politeness-timeline and frontier diagrams are purpose-built here; the JavaScript-rendering, Bloom-filter-direction and recrawl-scheduling questions are common follow-ups added for the quiz.