AlgoViz

Design a URL crawler

hard 60 min

Start from a few addresses, download pages, find links, and repeat a billion times a month.

Deep dives

Compare the options before you open them, then say which you would pick.

Deep dive 1

The frontier

How is the next URL chosen?

BreaksOne priority queue for all URLs
How
Workers pop the best URL.
Limit
The best thousand URLs share a few hosts. Either workers flood them or they all sleep.
Choose when
Fetching from hosts you own.
WorksShared queue and a Redis limit for each host
How
Pop a URL, take a token for its host, put it back if there is none.
Limit
When hosts are busy, most pops are put back. Every fetch needs the shared counter.
Choose when
A modest crawl with thousands of hosts and few pages each.
StrongFront queues by value, back queues by host
How
Eight front queues by value feed back queues that hold one host each. A heap orders hosts by next allowed time.
Limit
Own code, and state to rebuild after failure. A back queue must be refilled when empty.
Choose when
A web crawl. It serves both rules at once.

From a new link to a fetch

How it works

  1. 1

    Score

    For example 0.4 × link value + 0.3 × freshness need + 0.2 × change rate + 0.1 × host value. The weights are ours to tune. New URLs get a small boost.

  2. 2

    Front

    Eight levels. Higher ones are drawn from more often, so low ones are slow but never starve. Useful results move a host's links up, errors move them down.

  3. 3

    Back

    One queue for each host in use, first in, first out. Keep about three times as many as there are connections.

  4. 4

    Heap

    Hosts by next allowed time. Take the earliest. If it is in the future, sleep until then.

  5. 5

    Finish

    Set the next time, return the host. If its queue is empty, refill from the front queues.

Keep it, and keep it balanced

ProblemAnswer
MemoryOnly the next URLs of each host are in memory. The rest is in RocksDB on local disk
CrashChanges go to Kafka; a snapshot every 30 seconds shortens the replay. Work after it is redone, never lost
Pure memoryFast and simple, but a crash forgets months of discovery
A host with millions of URLsDisk, and a limit of 10,000 waiting; the rest stay in the URL table
Uneven shardsMany more virtual shards than machines; move some
Many hosts on one IP addressAlso limit by address, or a shared server feels all of them
Keep one key. If the frontier is split by URL in one place and by host in another, politeness is nobody's job.

Moving a shard without breaking the pace

The number is a fencing token: whoever holds an older one is ignored.

The two-level frontier was described for the Mercator crawler, listed in the sources.

Deep dive 2

Have we seen this URL?

How do you check 93,000 links a second against 10 billion?

BreaksAsk the database each time
How
Insert if absent.
Limit
93,000 reads a second, of which 95% say yes.
Choose when
Up to a few hundred pages a second in total.
WorksExact 64-bit hashes in memory
How
80 GB over ten shards, 8 GB each before table overhead.
Limit
Four times the memory or more. A pair or two may still collide by chance.
Choose when
Every page must be found, as in an archive of chosen sites.
StrongBloom filter on the host's owner, exact check when it matters
How
14.4 bits for each URL and 10 hash functions. Seeds, sitemaps and top links also check the table.
Limit
0.1% of unknown links are skipped, always the same ones. Cannot delete. Must be sized ahead.
Choose when
Broad crawls with more links than budget.

Sizing a Bloom filter

mn=−ln⁡p(ln⁡2)2=6.910.480≈14.4 bitsk=mnln⁡2≈10\frac{m}{n} = \frac{-\ln p}{(\ln 2)^2} = \frac{6.91}{0.480} \approx 14.4\ \text{bits} \qquad k = \frac{m}{n}\ln 2 \approx 10
For p = 0.001. At 1% it is 9.6 bits and 7 hashes: 12 GB for ten billion.

Save the filter every hour. On a cold start, rebuild it from the URL table, or load the last copy and add the rows written since. If it fills past its size the error rate climbs, so start a second filter and check both.

Normalise before you hash

StepExampleSafe?
Lower case scheme and hostHTTP://Example.COM becomes http://example.comYes
Drop the default port:443 on httpsYes
Resolve dots in the path/a/../b becomes /bYes
Drop the fragment#topYes, for plain HTML
Drop tracking parametersutm_sourceUsually; keep a list
Sort parameters?b=2&a=1Usually; some sites care
Join www and bare hostwww.example.comOnly after seeing a redirect

Deep dive 3

Have we seen this page?

A hash of the bytes finds exact copies. One changed date breaks it. SimHash gives similar texts similar 64-bit numbers: hash each word or short phrase, add +1 or -1 for every bit position, keep the signs. A Google paper from 2007 on crawling found that a difference of at most 3 bits works well for 8 billion pages.

Finding a number within 3 bits, among 10 billion

WayTablesCandidates in eachCost
Compare with all010 billionImpossible
4 blocks of 16 bits, one must match410B ÷ 65,536 ≈ 153,000Slow, 4 copies
Split the other 48 bits by 4 again1610B ÷ 2^28 ≈ 37Fast, 16 copies (1.3 TB)
Three changed bits can spoil at most three of four blocks, so one block always agrees.

Two kinds of duplicate

Same URLSame content
WhenBefore fetchingAfter fetching
SavesA requestStorage and index space
ToolNormalise, Bloom filterHash, then SimHash
Size for 10B18 GB80 GB to 1.3 TB
Mistake meansA page is missedA different page is taken for a copy
Check timeMicrosecondsMilliseconds

Deep dive 4

Being a good guest

How is the pace kept with many fetchers?

BreaksEach fetcher limits itself
How
Every process waits a second between its own requests to a host.
Limit
Eight fetchers make eight requests a second.
Choose when
One process only.
WorksA token bucket in Redis
How
Take a token for the host before each fetch.
Limit
A call for every fetch, and a burst size above 1 breaks the rule. Redis down means stop.
Choose when
Hosts cannot be given owners, as with short-lived workers.
StrongOne owner leases the host
How
The shard that owns a host gives it to one fetcher, which makes one request at a time.
Limit
Ownership needs leases, and moves must pause.
Choose when
Any crawl with its own frontier.

robots.txt, by the standard

SituationRFC 9309 says
Group for our nameFollow it; otherwise the group for *
404 or another 4xxMay crawl everything
500 or no answerMust assume all is disallowed
RedirectsFollow at least five
CacheShould not use a copy older than 24 hours, unless the file is unreachable
SizeMust parse at least 500 KiB
Crawl-delayNot in the standard, and Google does not support it; we honour it anyway
Is it permission?No. It is not a form of access authorization

Our own limits

  1. 1

    Pace

    Wait the larger of 1 second, any requested delay, and a few times the last answer's duration. A slow server gets more rest.

  2. 2

    Room

    One connection for each host. Agreed exceptions for large sites that invite more.

  3. 3

    Signals

    On 429 or 503 obey Retry-After, or double the delay. On refused connections leave the host for five minutes.

  4. 4

    Identity

    ExampleBot/1.0 with the address of a page that says who we are and how to opt out.

  5. 5

    Page wishes

    noindex means do not show; nofollow means do not use the links. They are read after fetching, in the page or in the X-Robots-Tag header.

  6. 6

    Brakes

    100 requests a second from one address, 5,000 in total, and a stop switch that works in seconds.

Deep dive 5

When to come back

How are returns planned?

BreaksEverything every week
How
One interval for all pages.
Limit
10B a week is 16,500 pages a second, mostly unchanged, and news is still days old.
Choose when
A small, even set of pages.
WorksBy kind of page
How
News hourly, shops weekly, the rest monthly.
Limit
Wrong for half the pages of any kind.
Choose when
No history yet. A good starting value.
StrongLearned from each page, within a budget
How
Wait one day divided by the share of visits with a change, times a factor for importance. Between 1 hour and 90 days.
Limit
We only see whether something changed, not how often, so fast pages are underestimated. Very fast pages must be capped.
Choose when
After a few visits. Until then use the kind.

The formula at work

PageChangedFactorNext visit
News front page10 of 100.524 h ÷ 1.0 × 0.5 = 12 h
Encyclopedia article1 of 20124 h ÷ 0.05 = 20 days
Product page3 of 10180 h, about 3.3 days
Never changed0 of 122The cap: 90 days
404gone-90 days, then forget
Twelve hours is too slow for news. The base interval for that group must be an hour, or a feed must tell us. A formula needs a check against the target.

A return visit

Details that count

  1. 1

    Do not scan

    Ten billion rows cannot be read each minute. A row sits in the bucket for its hour; the planner reads only this hour.

  2. 2

    Conditional

    If-None-Match with the ETag, or If-Modified-Since. A 304 has no body. A 200 with the same hash also counts as unchanged.

  3. 3

    Signals

    Last-Modified, sitemap dates, feeds, and links from pages that change. Trust them as far as they have been right.

  4. 4

    Very large hosts

    Visit a 10% sample. If little changed, leave the rest.

  5. 5

    Watch

    Average age, share within interval, share of visits that found a change. If that share is near zero we return too often; near one, too rarely.

Deep dive 6

Traps and other hostility

Edge cases

CaseProblemAnswer
No answerHolds a connection10 s to connect, 30 s in total, 3 tries, then lower the host
DNS failureTemporary or gone?Server failure: retry. No such name: remember for an hour
Refused or resetPerhaps we are unwantedLeave the host for 5 minutes, watch for patterns
Bad certificateWrong or expiredLog and skip. Never switch off checking
Calendar, countersLinks for everPage budget for a host, pattern check
Session in the URLNew URL on each visitDrop known parameters; compare content
Deep paths/a/b/a/b/a/bLength 2,000, depth 15, repeated parts
Many new URLs, one hostOver 1M uniqueFreeze and ask a person
Redirect loopA to B to A5 hops, remember the chain; robots for every new host
One byte a secondSlow on purposeBelow 1 KB/s for 10 s: stop
Huge or compressed bombMemory10 MB limit after decompression, streaming parser
Soft 404200 says not foundAsk for a random path and compare; classifier
Login, paywallNo contentRecord and stop. Never try to pass
JavaScript onlyEmpty textSide pool, if the host matters
Parked namesGenerated linksText to link ratio, same text on many hosts
Other content by regionDifferent pagesFetch from the host's region; sample from others
Prices, scoresStale at onceMark as live; accept it
Wrong encodingBroken textHeader, then meta tag, then detect
Clock differencesWrong due timesSynchronise clocks; compare dates from one server only
Internal addressesA link to our own networkRefuse private address ranges after DNS, on every redirect

At 386 fetches a second, a failure rate of 0.1% is 33,000 a day, and 0.01% is 100,000 a month. Rare cases are daily work here.

Failure drill: say it before you read it

  1. 1

    A fetcher dies

    Its leases end after a minute. The owners offer the hosts again. Some pages are fetched twice.

  2. 2

    A frontier shard dies

    The coordinator waits for its lease to end and gives it to another machine, which loads the snapshot and replays the log. Its hosts rest for a minute; others never notice.

  3. 3

    Object storage is slow

    Kafka fills: 8.7 GB for ten minutes. Past a threshold the fetchers slow down. Pages already fetched are kept.

  4. 4

    Parsers have a bug

    Fix it, set the Kafka position back, and parse again. Nothing needs to be fetched.

  5. 5

    Our pace rule breaks

    Alert on requests for each host seen at the exit. Press the stop switch, then look for two owners.