Design a URL crawler
hard 60 minStart 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
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
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
Back
One queue for each host in use, first in, first out. Keep about three times as many as there are connections.
- 4
Heap
Hosts by next allowed time. Take the earliest. If it is in the future, sleep until then.
- 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
| Problem | Answer |
|---|---|
| Memory | Only the next URLs of each host are in memory. The rest is in RocksDB on local disk |
| Crash | Changes go to Kafka; a snapshot every 30 seconds shortens the replay. Work after it is redone, never lost |
| Pure memory | Fast and simple, but a crash forgets months of discovery |
| A host with millions of URLs | Disk, and a limit of 10,000 waiting; the rest stay in the URL table |
| Uneven shards | Many more virtual shards than machines; move some |
| Many hosts on one IP address | Also limit by address, or a shared server feels all of them |
Moving a shard without breaking the pace
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
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
| Step | Example | Safe? |
|---|---|---|
| Lower case scheme and host | HTTP://Example.COM becomes http://example.com | Yes |
| Drop the default port | :443 on https | Yes |
| Resolve dots in the path | /a/../b becomes /b | Yes |
| Drop the fragment | #top | Yes, for plain HTML |
| Drop tracking parameters | utm_source | Usually; keep a list |
| Sort parameters | ?b=2&a=1 | Usually; some sites care |
| Join www and bare host | www.example.com | Only 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
| Way | Tables | Candidates in each | Cost |
|---|---|---|---|
| Compare with all | 0 | 10 billion | Impossible |
| 4 blocks of 16 bits, one must match | 4 | 10B ÷ 65,536 ≈ 153,000 | Slow, 4 copies |
| Split the other 48 bits by 4 again | 16 | 10B ÷ 2^28 ≈ 37 | Fast, 16 copies (1.3 TB) |
Two kinds of duplicate
| Same URL | Same content | |
|---|---|---|
| When | Before fetching | After fetching |
| Saves | A request | Storage and index space |
| Tool | Normalise, Bloom filter | Hash, then SimHash |
| Size for 10B | 18 GB | 80 GB to 1.3 TB |
| Mistake means | A page is missed | A different page is taken for a copy |
| Check time | Microseconds | Milliseconds |
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
| Situation | RFC 9309 says |
|---|---|
| Group for our name | Follow it; otherwise the group for * |
| 404 or another 4xx | May crawl everything |
| 500 or no answer | Must assume all is disallowed |
| Redirects | Follow at least five |
| Cache | Should not use a copy older than 24 hours, unless the file is unreachable |
| Size | Must parse at least 500 KiB |
| Crawl-delay | Not 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
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
Room
One connection for each host. Agreed exceptions for large sites that invite more.
- 3
Signals
On 429 or 503 obey Retry-After, or double the delay. On refused connections leave the host for five minutes.
- 4
Identity
ExampleBot/1.0 with the address of a page that says who we are and how to opt out.
- 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
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
| Page | Changed | Factor | Next visit |
|---|---|---|---|
| News front page | 10 of 10 | 0.5 | 24 h ÷ 1.0 × 0.5 = 12 h |
| Encyclopedia article | 1 of 20 | 1 | 24 h ÷ 0.05 = 20 days |
| Product page | 3 of 10 | 1 | 80 h, about 3.3 days |
| Never changed | 0 of 12 | 2 | The cap: 90 days |
| 404 | gone | - | 90 days, then forget |
A return visit
Details that count
- 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
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
Signals
Last-Modified, sitemap dates, feeds, and links from pages that change. Trust them as far as they have been right.
- 4
Very large hosts
Visit a 10% sample. If little changed, leave the rest.
- 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
| Case | Problem | Answer |
|---|---|---|
| No answer | Holds a connection | 10 s to connect, 30 s in total, 3 tries, then lower the host |
| DNS failure | Temporary or gone? | Server failure: retry. No such name: remember for an hour |
| Refused or reset | Perhaps we are unwanted | Leave the host for 5 minutes, watch for patterns |
| Bad certificate | Wrong or expired | Log and skip. Never switch off checking |
| Calendar, counters | Links for ever | Page budget for a host, pattern check |
| Session in the URL | New URL on each visit | Drop known parameters; compare content |
| Deep paths | /a/b/a/b/a/b | Length 2,000, depth 15, repeated parts |
| Many new URLs, one host | Over 1M unique | Freeze and ask a person |
| Redirect loop | A to B to A | 5 hops, remember the chain; robots for every new host |
| One byte a second | Slow on purpose | Below 1 KB/s for 10 s: stop |
| Huge or compressed bomb | Memory | 10 MB limit after decompression, streaming parser |
| Soft 404 | 200 says not found | Ask for a random path and compare; classifier |
| Login, paywall | No content | Record and stop. Never try to pass |
| JavaScript only | Empty text | Side pool, if the host matters |
| Parked names | Generated links | Text to link ratio, same text on many hosts |
| Other content by region | Different pages | Fetch from the host's region; sample from others |
| Prices, scores | Stale at once | Mark as live; accept it |
| Wrong encoding | Broken text | Header, then meta tag, then detect |
| Clock differences | Wrong due times | Synchronise clocks; compare dates from one server only |
| Internal addresses | A link to our own network | Refuse 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
A fetcher dies
Its leases end after a minute. The owners offer the hosts again. Some pages are fetched twice.
- 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
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
Parsers have a bug
Fix it, set the Kafka position back, and parse again. Nothing needs to be fetched.
- 5
Our pace rule breaks
Alert on requests for each host seen at the exit. Press the stop switch, then look for two owners.