SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Web Crawler

Visit billions of pages politely: a frontier of URLs, duplicate detection and traps.

⏱ 32 min readMedium case studyIntermediate23 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

β€œDesign a web crawler.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Turning a vague prompt into a scopeA crawler for a search engine, for price tracking and for a one-off scrape are three different systems. A strong candidate asks which one, and how fresh the data must be.
Politeness as a design constraintThe hard part is not fetching pages. It is fetching them without hammering any single site. That shapes the whole queue design.
Avoiding repeated workThe web links to itself in loops. URL de-duplication, content de-duplication and traps decide whether the crawl finishes or wastes its budget.
Estimation that drives decisionsPages per second, bytes per month, and the size of the seen-URL set tell you how many machines you need and whether a Bloom filter is worth it.
Scaling and failure handlingFetchers die, sites time out and the frontier is huge. You must say what is checkpointed, what is retried and why re-doing work is safe.

TL;DRThe whole design in 60 seconds

A crawler is a loop: take a URL from the frontier, fetch the page, store it, pull out its links, throw away the ones already seen, and put the new ones back in the frontier. The design is about making that loop polite, duplicate-free and restartable at billions of pages.

  • Scale: about 1 billion pages a month is roughly 400 pages a second on average and 800 at peak. At 100 KB a page that is about 100 TB of raw content a month.
  • Frontier: front queues sort URLs by priority, and back queues hold one queue per host, so each site is hit at most once every few seconds.
  • Fetchers: about 40 machines doing asynchronous I/O, using a local DNS cache and a cached robots.txt for each host.
  • De-duplication: normalise each URL, check a Bloom filter (about 6 GB for 5 billion URLs), then fingerprint the content (hash for exact copies, SimHash for near copies).
  • Traps and freshness: cap depth and URLs per host, recrawl pages that change often sooner, and use conditional GET so unchanged pages cost almost nothing.
  • Storage and recovery: raw pages go to object storage, the frontier is checkpointed, and every step is safe to repeat.
πŸ’‘How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
8
16
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Purpose, scale, freshness, content types. Say what you will not crawl (JavaScript-heavy pages).
2. Estimate3Pages per second, storage per month, URL set size, fetcher count.
3. API and data4Internal contracts (frontier, fetch result) and the URL record. There is no public API.
4. High-level design8Seeds, frontier, DNS, fetchers, parser, de-duplication, storage, recrawl scheduler.
5. Deep dives16The frontier and politeness, de-duplication, traps, then freshness and fault tolerance.
6. Scale and failures7Hot hosts, DNS, dead fetchers, monitoring, being blocked.
7. Wrap up3Recap, trade-offs, what you would add next.

Step 1Clarify requirementsabout 4 min

πŸ€”
Pause. Try it yourself first
You have 60 seconds. Write down five questions that would change the design. Hint: think about why we crawl, how many pages, how fresh they must be, and what kind of pages (plain HTML, or pages that need JavaScript).

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
What is the crawler for: a search index, price tracking, or a one-off data grab?A search crawler runs forever over the whole web. A one-off scrape is small and can be much simpler.Feeding a search engine. It runs continuously.We need a persistent frontier, recrawl scheduling, and a lot of attention to politeness.
How many pages, and how fast?Sets the number of fetchers, the storage size and whether one machine could do it.About 1 billion pages a month.About 400 pages per second, so tens of fetcher machines and a partitioned frontier.
How fresh must the data be? Do we recrawl?Recrawling is a second job that competes with discovering new pages.Yes. News pages within hours, most pages within weeks.Per-page recrawl intervals based on how often a page changes, plus conditional GET.
What content do we fetch: HTML only, or images, PDFs and JavaScript-rendered pages?Rendering JavaScript needs a headless browser, which is many times more expensive than a plain fetch.HTML first. Other types and JavaScript rendering later.A simple async HTTP fetcher now. A separate, small rendering pool is an extension.
Do we obey robots.txt and a crawl delay?Politeness decides the queue design. Ignoring it gets you blocked.Yes. Respect robots.txt and never overload a site.A cached robots.txt per host and a per-host queue with a minimum gap between requests.
Do we store the raw page or only the extracted text?Raw HTML is big. Keeping it lets you re-parse later.Store the raw page, compressed, and send extracted text on to the indexer.Object storage for pages, about 25 TB a month after compression.
How do we treat duplicate and near-duplicate pages?Mirrors and copied articles waste storage and pollute search results.Skip exact duplicates. Detect near-duplicates and keep one.A content hash for exact copies and SimHash or MinHash for near copies.
What are we allowed to crawl: one language, one country, or the whole web?A narrow crawl is far smaller and may allow a depth limit.The public web, any language.No topic filter. We still cap depth and URLs per host to avoid traps.
Is the crawl run from one data centre?Multiple regions change how the frontier is partitioned and how bandwidth is bought.One region first.Partition by host across machines in one region. Multi-region is a later phase.

Write the scope on the board

Functional (must do)
  • β€’Start from seed URLs and follow links to new pages
  • β€’Fetch pages over HTTP and HTTPS and store them
  • β€’Extract links and add new URLs to the frontier
  • β€’Respect robots.txt and a polite delay per host
  • β€’Skip URLs and pages already seen
  • β€’Recrawl pages on a schedule based on how often they change
Non-functional (how well)
  • β€’Scalable: about 1 billion pages a month, 400 pages per second on average
  • β€’Polite: no site gets more than one request every few seconds
  • β€’Robust: survives bad HTML, slow sites, redirects loops and traps
  • β€’Fault tolerant: a dead fetcher loses almost no work, and re-fetching is safe
  • β€’Extensible: new content types can be added later
Out of scope (say it)
  • β€’Rendering JavaScript-heavy pages (a later headless-browser pool)
  • β€’Building the search index and ranking
  • β€’Logging in to sites or crawling the deep web behind forms
  • β€’Multi-region crawling
🎀
Say it out loud
β€œLet me confirm the scope. We are crawling the public web for a search engine, about a billion pages a month. That is roughly 400 pages a second, and we store the raw page compressed. We obey robots.txt, we never hit one site too often, and we recrawl pages based on how often they change. Plain HTML first, no JavaScript rendering, one region. Does that match what you have in mind?”

Step 2Estimate the scaleabout 3 min

πŸ€”
Pause. Try it yourself first
On paper: how many pages a second is a billion a month? How many bytes a month? How big is the set of URLs we have seen, and how many machines fetch?

Assumptions (say them first)

AssumptionValue
Pages crawled1 billion a month
Average page size100 KB of HTML
Compression for storageabout 4 to 1
Peak factor2 times the average
Links per pageabout 50
URLs known (crawled and queued)about 5 billion, five times the monthly crawl
Fetcher speedabout 20 pages per second per machine (about 1 second a page, 20 in flight)
Politeness gapone request per host every 2 seconds
DNS cache miss rateabout 5%

The arithmetic, line by line

WhatMathsResult
Seconds in a month30 Γ— 86,400about 2.6 million
Pages per second, average1 billion Γ· 2.6 millionabout 390, call it 400
Pages per second, peak400 Γ— 2800
Raw content per month1 billion Γ— 100 KB100 TB
Stored per month (compressed)100 TB Γ· 425 TB
Stored for a year, with erasure coding25 TB Γ— 12 = 300 TB; Γ— 1.5about 450 TB
Download bandwidth400 Γ— 100 KB = 40 MB/s; Γ— 8about 320 Mbit/s (640 at peak)
Links found per second400 pages Γ— 50 links20,000 (40,000 at peak)
URL records5 billion Γ— 200 bytesabout 1 TB
Seen-URL Bloom filter5 billion Γ— 10 bits Γ· 8about 6.25 GB (about 0.8% false positives)
Fetcher machines800 pages/s Γ· 20 per machine40 machines at peak
Hosts active at once800 pages/s Γ— 2 s gapat least 1,600 hosts, or we run out of polite work
DNS lookups that miss the cache400 Γ— 5%about 20 per second
What the numbers tell us about the design
  • β€’400 pages a second is easy for a fleet and impossible for one process. We need tens of fetchers and a frontier shared between them.
  • β€’20,000 new links a second means the duplicate check is on the hot path. It must be a memory check (Bloom filter), not a database query per link.
  • β€’A 6 GB Bloom filter fits in memory on one machine, but a 1 TB URL table does not. So the filter answers fast and the table answers when it matters.
  • β€’To keep 800 pages a second going at one request per host every 2 seconds, we need at least 1,600 different hosts with work waiting. Politeness, not CPU, is the limit.
  • β€’100 TB a month raw is an object-storage job. Compress it, and keep only metadata in a database.
🎀
Say it out loud
β€œA billion pages a month is about 400 a second, 800 at peak. At 100 KB a page that is 100 TB a month raw, about 25 TB compressed, so we store pages in object storage. Each page has about 50 links, so we check about 20,000 URLs a second against what we have seen. That needs an in-memory filter: for 5 billion URLs at 10 bits each, about 6 GB. At 20 pages a second per machine we need about 40 fetchers. And because we wait 2 seconds between hits on a host, we need at least 1,600 hosts with work waiting. These are assumptions, but they show where the pressure is: politeness and de-duplication.”

Step 3Define the API and the data modelabout 4 min

πŸ€”
Pause. Try it yourself first
There is no public API here. Write the internal calls: how does a fetcher ask for work, and what does it report back? Then sketch the record you keep for every URL.

Endpoints

MethodPathRequestResponseNotes
POST/frontier/next{ fetcherId, max: 20 }200 { leases: [{ url, host, leaseId, expiresAt }] }Hands out URLs whose host is allowed now. Each is a lease, not a delete. If the fetcher dies, the lease expires and the URL goes back.
POST/frontier/done{ leaseId, status, contentHash, newLinks[], nextCrawl }204Idempotent. Marks the lease finished. A repeat with the same leaseId changes nothing.
POST/frontier/add{ urls[], sourceUrl, depth }202 { accepted }Called by the link extractor. Each URL is normalised, filtered and checked against the seen set before it is queued.
GET/robots/{host}none200 { rules, crawlDelay, fetchedAt }Served from a cache with a TTL (about 24 hours). A missing file means everything is allowed. A 5xx means treat the host as off limits for now.
PUT/seeds{ urls[], priority }202Operator call to add seed URLs or boost a site.

Data model

URL recordTypeNotes
url_hash64-bit hash of the normalised URLPrimary key. Keeps rows small and lookups fast.
urlstring, up to about 2 KBThe normalised form: lower-case host, no fragment, sorted query, tracking parameters removed.
hoststringPartition key for the frontier, so one host lives on one worker.
statenew, queued, fetching, done, errorMove through states with a lease so a crash returns the URL to queued.
priorityintegerFrom importance (links in, past rank), change rate and depth.
depthintegerHops from a seed. Capped to escape traps.
last_crawled / next_crawltimestampsRecrawl schedule.
content_hash / simhashbytes / 64-bitExact and near-duplicate detection.
etag / last_modifiedstringsUsed for conditional GET.
fail_countintegerBack off and finally drop URLs that keep failing.
Other stateHoldsWhere
Frontier queuesURLs waiting, grouped by priority and by hostIn memory with a disk-backed log on each frontier worker
Seen-URL filterA Bloom filter over every URL ever queuedMemory on each frontier worker (its share of hosts)
Page storeCompressed raw HTML, one object per page versionObject storage, in large files (WARC style)
Link graphEdges from a page to the pages it links toWide-column or batch store, used for ranking later
Robots and DNS cachesParsed rules and host to IP answers, with TTLsMemory on each fetcher, backed by a shared cache
What a fetcher reports after one page
POST /frontier/done
{
  "leaseId": "L-8f3a",
  "status": 200,
  "contentHash": "a41c...",
  "newLinks": ["https://example.org/a", "https://example.org/b?id=7"],
  "nextCrawl": "2026-12-11T06:00:00Z"   // sooner if the page changed since last time
}
πŸ“Which store, and why
Two kinds of data with opposite needs. URL records and the frontier are small, hot and updated constantly, so they live in a partitioned key-value store (or in memory with a log), keyed by host. Raw pages are big and written once, so they go to object storage in large batched files. Do not put page bodies in the URL table. The link graph is used in batch jobs, so a wide-column or batch store is fine.
🎀
Say it out loud
β€œThere is no public API, so I will describe the internal contracts. A fetcher asks the frontier for a batch of URLs and gets leases, not deletes, so if the fetcher dies the URLs come back. When it finishes it reports the status, a content hash, the links it found and when to recrawl, and that call is idempotent. Each URL has a record keyed by a hash of its normalised form, with its host, state, priority, depth and recrawl time. Pages themselves go to object storage, not the database.”

Step 4Draw the high-level designabout 8 min

πŸ€”
Pause. Try it yourself first
Draw the loop: seeds in, pages out. Where do URLs wait? Where do you check for duplicates, and what keeps one site from being hit too often?
Web crawler: high-level design
🌱Seed URLsoperators, sitemaps
→↓add
URL frontier
🎚️Front queuesby priority
↓
🧭Back queuesone per host, with a timer
→↓lease
Fetchers (about 40)
🌐Async fetchHTTP, timeouts, redirects
πŸ“–DNS and robots cacheslocal, with TTLs
🧾Parsertext, links, language
→↓content hash
🧬Content deduphash + SimHash
→↓keep
πŸ—„οΈPage storeobject storage, compressed
→↓new pages
πŸ“šIndexerout of scope
πŸ”—Link extractornormalise, filter
→↓candidate URLs
πŸ”Seen filterBloom + exact store
→↓new only, back to frontier
⏰Recrawl schedulerre-adds changed pages
URLs flow left to right and new links loop back into the frontier. Politeness is enforced in the frontier, so fetchers stay simple.
ComponentWhat it does
Seed URLsWhere the crawl starts: a hand-picked list of good sites, plus sitemaps. Seeds are also a quality lever.
URL frontierHolds every URL waiting to be fetched. Front queues sort by priority. Back queues give each host its own queue and a timer, which enforces politeness.
FetchersAsynchronous workers that download pages. They lease URLs, honour timeouts and redirect limits, and use cached DNS and robots.txt.
DNS and robots cachesAvoid a lookup for every page. A host’s robots.txt is fetched once and reused for about a day.
Parser and link extractorParse HTML (even broken HTML), pull out text and links, and normalise each link.
Seen-URL filterA Bloom filter says β€œdefinitely new” or β€œprobably seen”. An exact store can confirm. Stops the same URL entering the frontier twice.
Content de-duplicationA hash catches exact copies. SimHash or MinHash catches near copies, so mirrors are stored once.
Page storeCompressed raw pages in object storage, packed in big files. Metadata stays in the URL table.
Recrawl schedulerRe-adds a URL when it is due, sooner for pages that changed last time. Uses conditional GET to make repeat fetches cheap.
Write path (follow one request)
  1. An operator adds seed URLs. Each is normalised and put into the frontier with a high priority.
  2. A fetcher asks the frontier for work. The frontier picks a host whose timer has expired and hands out a URL as a lease.
  3. The fetcher checks the cached robots.txt for that host. If the URL is disallowed, it reports done with status β€œblocked”.
  4. It resolves the host from the DNS cache (or looks it up), fetches the page with a timeout, and follows a limited number of redirects.
  5. The parser extracts the text and the links. The content hash is checked: if the page is an exact or near copy, it is not stored again.
  6. The page is appended to a batch file for object storage, and the URL record is updated (state, hash, next crawl).
  7. Each link is normalised and checked against the seen filter. New ones go to the frontier with a priority and a depth one higher than their parent.
  8. The fetcher reports done, which releases the lease and starts the host’s timer again.
Read path (follow one request)
  1. The recrawl scheduler wakes up and finds URLs whose next_crawl time has passed.
  2. It adds them back to the frontier, with higher priority for pages that changed last time.
  3. A fetcher leases the URL and sends a conditional GET with the saved ETag or Last-Modified value.
  4. If the site answers 304 Not Modified, nothing is downloaded. The crawler only moves next_crawl later.
  5. If the page changed, it is fetched in full, parsed and stored as a new version, and its recrawl interval gets shorter.
  6. The indexer reads new and changed pages from the page store. That part is out of scope here.
🎀
Say it out loud
β€œHere is the picture. Seeds go into a frontier. The frontier has priority queues in front, and one queue per host behind them, each with a timer, so no site is hit too often. Fetchers lease URLs, use cached DNS and robots.txt, and download pages. A parser pulls out text and links. Pages go through a content check and are stored in object storage. Every new link is normalised and checked against a Bloom filter before it re-enters the frontier. A scheduler re-adds pages for recrawl, using conditional GET so unchanged pages cost almost nothing.”

Step 5Deep dive into the hard partsabout 16 min

🧠The pattern for every deep dive
Problem β†’ options β†’ pick one β†’ say why β†’ say what it costs. Interviewers score the reasoning more than the choice.
5.1

The URL frontier and politeness

The problem: We have billions of URLs waiting. The next one to fetch must be important, and it must belong to a site we have not hit in the last few seconds. A plain queue gets one of these wrong.

OptionHow it worksGoodBad
One global FIFO queueTake URLs in the order they were found.Trivial. Breadth-first by accident.Pages link to their own site, so a burst of links from one host arrives together and that host is hammered. No priority at all.
Global queue, wait for the hostTake the head of the queue and wait if its host was hit recently.Polite.Head-of-line blocking: every free fetcher waits behind one resting host while other sites have work. Throughput collapses.
Front queues by priority, back queues per hostA router puts each URL in a priority queue, then moves it to the single back queue for its host. A heap holds the time each back queue may next be used.Polite, busy and priority-aware. This is the classic design (Mercator).More moving parts. The number of back queues must track the number of active hosts.
Per-host queues with a token bucket per hostEach host gets a queue and a rate limit. A scheduler picks any host that has a token.Easy to allow faster crawling of sites that ask for it.Needs a fair scheduler across millions of hosts, or it favours big sites.
Pick
Front queues by priority and back queues per host, with a ready-time heap

The frontier is two layers. Front queues are ordered by priority (how important the page is, how often it changes, how shallow it is). A router drains them into back queues, where each host has exactly one queue. A min-heap keyed by "the time this host may next be hit" tells the frontier which back queue is ready. A fetcher takes the ready queue at the top, pops one URL, and the host's timer is set to now plus the gap (or the Crawl-delay in robots.txt, whichever is larger).

This answers both problems. No host is ever hit early, because only ready hosts are eligible. No fetcher waits behind a resting host, because it simply takes the next ready one. The visualizer after the deep dives shows the three designs side by side. For the heap see Heap and Priority Queue.

LayerKeyed byJob
Front queues (say 3 to 5)PriorityMake sure important and fast-changing pages go first.
RouterHostMoves a URL from a front queue to the back queue of its host.
Back queues (one per active host)HostKeep each host’s URLs together, in order.
Ready heapNext allowed timeSays which back queue may be used now.
πŸ’‘Spread the frontier over machines
Partition by host with consistent hashing, so every URL of one host lives on one frontier worker. That worker alone owns that host's timer, so politeness needs no coordination. See Consistent Hashing.
🎀
Say it out loud
β€œA single queue fails twice: it hammers sites that arrive in bursts, and if I make it wait, one resting host blocks every fetcher. So I split the frontier. Front queues order URLs by priority. Behind them, every host has its own back queue and a timer, and a heap tells me which host is ready. A fetcher always takes a ready host. I partition by host hash, so one worker owns each host and politeness needs no locking.”
5.2

Not crawling the same thing twice

The problem: The same page can be reached by many URLs, and the same text can live at many pages. With 20,000 new links a second, we must drop repeats cheaply, without losing pages we have not seen.

OptionHow it worksGoodBad
Exact set of every URLA database or hash set stores every URL ever seen.Never wrong.About 1 TB of records for 5 billion URLs, and a lookup for each of 20,000 links a second.
Bloom filter in memoryHash each URL into several bits of a bit array. All bits set means probably seen.About 6 GB for 5 billion URLs at 10 bits each. Microsecond checks. No false negatives.A false positive (about 0.8% here) says β€œseen” for a new URL, and that page is skipped. Cannot delete.
Bloom filter, then an exact checkUse the filter as a fast gate. Only ask the exact store when the filter says β€œseen”.No page lost to false positives. Most lookups still cost nothing.About 1% of lookups hit the slower store. Two systems.
Normalise first, then dedup contentCanonicalise the URL before any check. After fetching, fingerprint the content.Catches the same page under many URLs, and mirrors under different hosts.Content checks happen after the fetch, so the bandwidth is already spent.
Pick
Normalise, then a Bloom filter as a gate with an exact store behind it, then content fingerprints

Three layers, each cheap enough for its place. URL normalisation makes equal URLs look equal: lower-case the host, drop the fragment (#top), remove default ports, sort query parameters, strip tracking parameters, resolve /a/../b. The Bloom filter then rejects most known URLs without touching a disk. Content fingerprints catch what URLs cannot: a hash for exact copies, and SimHash (or MinHash) for near copies, where two pages are the same text with a different header or ad.

The Bloom filter trade-off is worth saying out loud. It has no false negatives, so we never re-crawl by accident. It has false positives, so with 10 bits per URL about 0.8% of new URLs look "seen" and are skipped. For a search crawl that is acceptable, because the page usually has other inbound links and gets another chance. If it is not, confirm "seen" in the exact store. See Bloom Filters and MinHash.

Bits per URLHashesFalse positivesMemory for 5 billion URLs
86about 2.2%5 GB
107about 0.8%6.25 GB
2014about 0.007%12.5 GB
Normalising a URL (the order matters)
https://Example.COM:443/a/../b/index.html?utm_source=x&id=7&a=1#top
  lower-case scheme and host        -> https://example.com:443/...
  drop default port                 -> https://example.com/...
  resolve dot segments              -> /b/index.html
  remove fragment                   -> (no #top)
  drop tracking parameters          -> ?id=7&a=1
  sort remaining parameters         -> ?a=1&id=7
result: https://example.com/b/index.html?a=1&id=7
🎀
Say it out loud
β€œI would stack three checks. First, normalise the URL so the same page does not look like two. Second, a Bloom filter in memory: about 6 GB for 5 billion URLs, with no false negatives, so we never re-crawl by accident. The cost is under 1% false positives, which skips a few new pages, and I can confirm a hit in an exact store if that matters. Third, after fetching, fingerprint the content: a hash for exact copies and SimHash for near copies, so mirrors are stored once.”
5.3

Crawler traps and bad pages

The problem: Some sites generate an endless supply of URLs: a calendar with a next-month link forever, session IDs in every link, filters that combine in millions of ways. A naive crawler follows them until its budget is gone.

OptionHow it worksGoodBad
Do nothingFollow every link.Simple.One trap site can eat most of the crawl and fill storage with junk.
Hard limitsCap the depth, the URL length, and the number of URLs per host.Simple and effective against most traps.A very large legitimate site is cut short. Limits need tuning.
Pattern detectionNotice repeated path segments or a growing parameter, and stop following that pattern.Catches the loops that hard limits miss.Heuristics can misfire. More code.
Quality score per hostTrack how many pages from a host are new, unique and useful. Lower the priority of hosts that give mostly duplicates.Adapts to traps nobody predicted.Needs content signals and time to learn.
Pick
Hard limits first, pattern rules for known traps, and a per-host quality score that lowers priority

Start with cheap limits that stop most damage: a maximum depth from the seed (say 15), a maximum URL length (say 2,000 characters), and a maximum number of URLs per host per day. Add rules for the known shapes: the same path segment repeated three times, a parameter that grows (?page=1001 and up), or session IDs, which normalisation strips. Then add feedback: if a host keeps returning duplicate or empty pages, its priority drops, so the crawl moves on.

The same section covers bad pages. Set timeouts on connect and on read, limit the page size (say 10 MB), limit redirect hops (say 5) and detect redirect loops, and treat malformed HTML as normal, because the web is full of it. Honour robots.txt, and treat a server error on that file as "do not crawl yet". Be careful with nofollow and with each site's terms.

Trap or problemLooks likeDefence
Infinite calendar/cal/2031/05, /cal/2031/06, and onDepth cap, per-host daily cap, pattern rule
Session IDs in links/page?sid=84f1, a new value every visitStrip known session parameters when normalising
Faceted filters/shop?color=red&size=m&sort=price&page=9Cap parameters per URL, quality score drops the host
Redirect loopA to B to AHop limit and loop detection
Huge or slow responseA 2 GB file, or a server that sends a byte a secondSize limit, total timeout
Spam link farmsThousands of generated pages linking to each otherQuality score, blocklist, lower priority
🎀
Say it out loud
β€œTraps come from sites that produce unlimited URLs, like a calendar or session IDs. My first line is cheap limits: a maximum depth, URL length and number of URLs per host. Then rules for known patterns, such as a repeated path segment or a growing page number. Then feedback: a host that keeps returning duplicates gets a lower priority. I also set timeouts, a size limit and a redirect limit on every fetch, and I always obey robots.txt.”
5.4

Freshness, scheduling and fault tolerance

The problem: A crawl that never revisits goes stale, and one that revisits everything blindly wastes its budget. We also have to survive machines dying in the middle of work.

OptionHow it worksGoodBad
Recrawl everything on a fixed cycleEvery page, every 30 days.Easy to reason about.Wastes work on pages that never change, and is too slow for news.
Adaptive intervalShorten a page’s interval when it changed since the last visit, and lengthen it when it did not.Spends effort where change happens.Needs a change signal (a hash) and a model. New pages start with a guess.
Priority by importanceMore important pages are revisited more often, whatever their change rate.Good for popular sites.Wastes effort on important but static pages.
Push signalsUse sitemaps, feeds and change pings to learn about updates.Cheapest and fastest when a site supports it.Many sites do not. A signal can be wrong.
Pick
Adaptive intervals combined with importance, conditional GET, and sitemap hints

Each URL has a next_crawl time. After a fetch, compare the new content hash to the old one. If it changed, halve the interval (down to a floor, say 1 hour for news). If it did not, double it (up to a cap, say 30 days). Multiply the urgency by importance so popular pages are checked more often. Use conditional GET (If-None-Match with the ETag, If-Modified-Since with the date), so a page that has not changed comes back as a tiny 304 reply instead of 100 KB. Sitemaps tell us about new URLs and last-modified times, so we can skip guessing.

For fault tolerance, nothing is deleted when handed out: a fetcher takes a lease with an expiry. If it dies, the lease runs out and the URL returns to the queue. Every step is safe to repeat: fetching twice stores the same content hash, and the done call is idempotent by lease ID. The frontier keeps a write-ahead log and periodic checkpoints, so a frontier worker that restarts rebuilds its queues, and its hosts can move to another worker through consistent hashing. See Idempotency and Handling Failures.

VisitPage changed?New interval
Startunknown24 hours (a guess)
1yes12 hours
2yes6 hours
3no (304)12 hours
4no (304)24 hours
5no (304)48 hours, and so on up to a cap
🎀
Say it out loud
β€œEach URL gets a next-crawl time. If the content hash changed since the last visit, I halve the interval, and if not, I double it, between a floor and a cap, scaled by importance. I use conditional GET with the ETag, so an unchanged page costs a tiny 304 reply. For failures, fetchers take leases, not deletes, so a dead fetcher's URLs come back when the lease expires. All steps are idempotent, and the frontier has a log and checkpoints, so a restart loses almost nothing.”
VisualizerWho gets hit, and who waits: three ways to pick the next URLSwitch between one global queue (rude), one queue that waits (idle fetchers) and a queue per host with priority. Move the gap and the fetcher count. Then size a Bloom filter for the seen-URL check.
How does a free fetcher pick the next URL?
news.example
priority 3 Β· 1 s per page
3
3
3
3
shop.example
priority 1 Β· 4 s per page
3
2
blog.example
priority 2 Β· 1 s per page
2
wiki.example
priority 2 Β· 2 s per page
2
2
Fetchers stuck
0 s15 s30 s
request started (a number means several at once)rude: too soon, or the last one was still runningfetchers with work in the queue but nothing they may take
Pages finished
34
of 34 queued, in 30 s
Rude requests
25
hit a site too soon
Idle fetcher-seconds
0
work waiting, none allowed
News pages done
14 / 14
the high-priority site
Fast, but rude. 25 requests hit a site sooner than its allowed gap (3 s), or while it was still answering the last one. news.example took the worst of it (11). A real site would slow you down or block you. 34 pages finished in 30 s.
Seen-URL filter: how big, and how many new pages get skipped by mistake?

A Bloom filter answers "have I seen this URL?" with a few bits per URL. It can say "seen" for a URL it has never seen (a false positive), and that page is then never crawled. It never says "new" for a seen URL.

Filter memory
1.3 GB
exact store β‰ˆ 100 GB
False positives
0.82%
new URL called β€˜seen’
Skipped per 1B new URLs
8.2 million
never crawled by mistake

Standard formula: k = bits Γ— ln 2 hashes, false-positive rate (1 βˆ’ e^(βˆ’k/bits))^k. The exact store assumes 100 bytes per URL (an assumption). Real crawlers often confirm a "seen" answer in an exact store when it matters.

A simplified model with fixed numbers (no random values): four sites, 34 URLs discovered in bursts, one request per site at a time, one second per tick. Latencies and priorities are illustrative.

Step 6Scale, bottlenecks and failuresabout 7 min

πŸ€”
Pause. Try it yourself first
Imagine the crawl at 10 times the size, and then imagine a bad day. What fills up first? What happens when a fetcher, a frontier worker or a whole site goes away?

What breaks first, and the fix

BottleneckFix
Politeness caps throughput (not enough different hosts with work)Seed broadly, keep many hosts active, and raise the rate only for hosts that allow it. Add fetchers last.
DNS lookups slow every fetchA local DNS cache on each fetcher, a shared resolver cache, and prefetching the host of queued URLs.
The seen-URL check at 20,000 links a secondA per-worker Bloom filter for the hosts that worker owns, so the check is local and needs no network call.
One huge host dominates a frontier workerSplit a very large host’s queue across several back queues that share one timer, or give it its own worker.
Page storage grows by 25 TB a monthWrite large batched files to object storage, compress, use lifecycle rules, and keep only the latest version of unchanged pages.
Parsing is CPU heavySeparate parser workers fed by a queue, so fetchers stay I/O bound and parsing scales on its own.
Outbound bandwidth peaks at 640 Mbit/sSpread fetchers across several network links, and throttle low-priority recrawls at peak.

What if a part fails?

FailureHow the design copes
A fetcher crashes mid-downloadIts leases expire and the URLs go back to the queue. Fetching again is safe because storing is idempotent.
A frontier worker diesIts hosts are reassigned by consistent hashing. It rebuilds from its log and last checkpoint. Some URLs are fetched twice, never lost.
A site is down or very slowTimeouts, then exponential back-off for that host, and the host is moved down in priority until it recovers.
robots.txt cannot be fetched (server error)Treat the host as off limits for a while, and retry later. Do not assume permission.
Object storage write failsRetry with the same object key. Do not mark the URL done until the page is stored.
A site blocks us or returns many 403 and 429 repliesSlow down at once, lengthen the gap, and honour Retry-After. Do not rotate addresses to get around a block.
What to monitor
  • β€’Pages fetched per second, by status code (200, 304, 404, 5xx, timeouts)
  • β€’Frontier size, and how many hosts have work waiting (the number that limits you)
  • β€’Age of the oldest URL due for recrawl (freshness lag)
  • β€’Duplicate rate: share of fetched pages that were exact or near copies
  • β€’Per-host request rate, so politeness breaches show up
  • β€’Fetcher lease expiries, which signal crashes and stuck fetches
Security and abuse
  • β€’Identify the crawler with a clear User-Agent and a contact page, so site owners can reach you
  • β€’Always obey robots.txt, crawl-delay and meta robots rules, and remove content on request
  • β€’Fetch from an isolated network so a malicious page cannot reach internal services (guard against SSRF and redirects to private addresses)
  • β€’Treat every page as hostile: limit sizes, parse in a sandbox, never execute scripts from fetched content
  • β€’Do not rotate addresses to avoid blocks, and respect each site’s terms and the law where you crawl

Step 7Wrap upabout 3 min

A crawler is a loop over a frontier. The frontier has priority queues in front and one queue per host behind them, so it is both important-first and polite. Fetchers lease URLs and use cached DNS and robots.txt. Every link is normalised and checked in a Bloom filter, and every page is fingerprinted for duplicates. Pages go to object storage. A scheduler recrawls pages on adaptive intervals using conditional GET. Everything is leased and idempotent, so failures only repeat work.

Trade-offs you made

DecisionWhat we gainWhat it costs
Back queues per host with a ready heapPolite and busy, with prioritiesMore complex than a single queue, and it needs a host-to-worker mapping
Bloom filter for seen URLsAbout 6 GB, microsecond checks, no repeatsUnder 1% of new URLs are skipped by mistake
HTML only, no JavaScript renderingCheap and fast, about 20 pages a second per machinePages built in the browser are missed or thin
Leases instead of deleting on hand-outA crash loses nothingSome pages are fetched twice, so every step must be idempotent
Adaptive recrawl intervalsEffort goes where pages changeA change model to maintain, and a bad guess for new pages
Partition the frontier by hostPoliteness needs no locksA very large host can overload one worker
If we had more time, we would…
  • β€’A small pool of headless browsers for JavaScript-heavy pages
  • β€’Smarter priorities: link-based importance and learned change rates
  • β€’Support for images, PDFs and other file types
  • β€’Multi-region crawling to be closer to the sites
  • β€’Better trap detection with host-level quality learning
🎀
Say it out loud
β€œTo recap: a frontier with priority queues and one polite queue per host, leased to a fleet of async fetchers; normalise and Bloom-filter every URL, fingerprint every page; store pages in object storage; recrawl on adaptive intervals with conditional GET. The trade-offs are a small chance of skipping a new page, no JavaScript rendering for now, and some repeated fetches after crashes, which idempotency makes safe. With more time I would add a rendering pool, learned priorities and multi-region crawling.”

Q&ACross-questions (23)

πŸ’‘How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

The frontier and politeness

The first thing most interviewers probe. Explain why a simple queue fails.

Duplicates, traps and content

Scale, storage and freshness

Failures, ethics and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Crawl only one site (or a few), not the whole webNo need for a Bloom filter or a partitioned frontier. One queue per host and a database for seen URLs is enough. Depth and politeness still apply.
Pages must be fresh within minutesA fast lane: feeds, sitemaps and push signals, a short recrawl interval for hubs, and a fixed share of the fetch budget reserved for it.
Most pages need JavaScript to renderA headless-browser pool becomes the main fetch path. Cost per page rises many times, so the crawl rate falls or the fleet grows, and caching of rendered output matters.
Crawl images and video tooA separate pipeline by content type, a bigger store, different size limits, and a thumbnail or hash step. Usually done by a second crawler fed from page links.
Crawl from several regionsOne frontier per region, each owning the hosts nearest to it. Shared seen-URL information is synchronised in the background, and the page store is replicated or kept per region.
Must obey a legal takedown quicklyA deny list consulted by the frontier and the indexer, a way to find and delete stored copies by URL, and an audit log of removals.
The target is a private or login-protected siteOut of scope here. It needs credentials, session handling and permission from the owner, and a much more careful rate.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing without asking what the crawler is for.Asks scale, freshness and content types, and states robots.txt.Ties each answer to a design choice, and rules out JavaScript rendering with a reason.
EstimationNo numbers, or a machine count with no basis.Pages per second, storage per month, and fetcher count.Also sizes the seen-URL filter, link rate and active hosts needed, and says what each number means.
Frontier and politenessOne FIFO queue.Per-host queues and a delay.Front and back queues with a ready heap, host partitioning, and an explanation of head-of-line blocking.
De-duplicationA visited list in a database.Normalisation and a Bloom filter.Quantifies the false-positive trade-off, adds an exact check, and covers near-duplicates with SimHash.
Traps and robustnessDoes not mention loops or bad pages.Depth and size limits, timeouts, robots.txt.Adds pattern detection, a host quality score and redirect handling, with the reasoning.
Failures and ethicsAssumes nothing fails.Leases, retries and idempotent steps.Adds checkpoints, recovery of frontier workers, and a clear stance on blocking and the law.

AvoidCommon mistakes on this question

MistakeDo this instead
Using one global queue and ignoring politenessGive each host its own queue and timer, and say why a single queue hammers sites or blocks fetchers.
Checking seen URLs with a database query per linkUse an in-memory Bloom filter at 20,000 links a second, with an exact store behind it when needed.
Not normalising URLsCanonicalise first, or the same page enters the frontier under many forms.
Forgetting trapsName the calendar and session-ID cases, and add depth, length and per-host caps.
Handing out URLs by deleting themUse leases with an expiry, so a crash does not lose work.
Rendering JavaScript for every pageFetch plain HTML first, and use a small headless-browser pool only where needed.
Ignoring robots.txt and legal limitsObey robots.txt, crawl-delay and takedowns, and say you would involve legal counsel.
Adding fetchers when throughput is lowCheck the number of active hosts first. Politeness is usually the limit, not machines.

Revise60-second revision sheet

  • βœ”Scale: 1B pages a month is about 400 a second, 800 at peak. 100 KB a page is 100 TB raw, about 25 TB compressed.
  • βœ”Loop: frontier, fetch, parse, store, extract links, de-duplicate, back to the frontier.
  • βœ”Frontier: front queues by priority, one back queue per host, a ready heap. Partition by host hash.
  • βœ”Politeness: robots.txt cached, a gap per host (2 seconds or Crawl-delay), back off on 429 and 5xx.
  • βœ”Seen URLs: normalise, then a Bloom filter. 10 bits per URL gives about 0.8% false positives, 6.25 GB for 5B URLs.
  • βœ”Duplicate pages: a content hash for exact copies, SimHash or MinHash for near copies.
  • βœ”Traps: depth, URL length and per-host caps, pattern rules, a host quality score.
  • βœ”Freshness: halve the interval if it changed, double it if not. Conditional GET makes a recheck about 0.5% of the cost.
  • βœ”Failures: leases, idempotent steps, a frontier log and checkpoints. A crash repeats work and never loses it.
  • βœ”One line: β€œA polite, restartable loop: one queue per site, a filter for what we have seen, and a lease for everything we hand out.”

Read these topics next

Bloom Filters→

The in-memory seen-URL check and its false-positive trade-off.

MinHash→

Near-duplicate detection for page content.

Heap and Priority Queue→

The ready heap that picks the next polite host.

Consistent Hashing→

Partitioning the frontier by host across workers.

DNS→

Why lookups are a bottleneck and need caching.

Object Storage→

Where the compressed raw pages live.

Rate Limiting→

The same idea as a per-host politeness gap.

Back Pressure→

What to do when the parser cannot keep up with the fetchers.

← Previous
Design a Notification System
Next β†’
Design Search Autocomplete