AlgoViz

Design a URL crawler

hard 60 min

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

API and data

The contract first, then the data that serves it.

Interface

Messages more than endpoints

Readers never call a crawler. There is a small HTTP interface for operators and an internal one between parts. Inside, remote calls carry the pulling of work, and a log carries what happened. See RPC and pub/sub.

For operators

RequestDoesAnswer
POST /v1/seedsURLs, priority, depthAccepted, duplicates, ids
GET /v1/seeds, DELETE /v1/seeds/{id}List, remove200, 204
GET /v1/hosts/{host}Status and statisticsFound, fetched, pending, errors, robots state, delay
PUT /v1/hosts/{host}/configPace, budget, priority200
POST /v1/hosts/{host}/blockStop now204
POST /v1/hosts/{host}/recrawlAll, changed or new, with a reason202 and a job id
GET /v1/stats, /v1/frontier/depth, /v1/workers, /v1/errorsWatch the system200
A recrawl of 15,423 pages on one host takes 4 hours and 17 minutes at one a second. Say that in the answer.

Between services

CallCarriesNote
Frontier.LeaseHostsWorker, region, how manyReturns hosts with a few URLs each and a lease time
Frontier.SubmitNew links with a sourceDeduplicated by the host's owner
Frontier.ReportResult, status, time, next delayEnds the lease
Robots.IsAllowedURLAllowed, delay, when the file was read
Dns.ResolveHostAddresses, time to live, from cache or not
Pages.Store, Pages.GetCompressed body, headersKey is file and offset
Pages.CheckFingerprint64 bitsKnown copy or not
protobuf
message LeaseHostsRequest { string worker_id = 1; string region = 2; int32 max_hosts = 3; }message HostLease {  string host = 1;  int64  lease_until_ms = 2;  int32  delay_ms = 3;              // at least this long between requests  repeated UrlToFetch urls = 4;     // best first}message UrlToFetch {  string url = 1;  int64  last_fetched_at = 2;       // 0 = never  string etag = 3;                  // for a conditional request  int32  retry_count = 4;}
A lease hands out a host, with its own short list. The worker waits between requests; nobody else can touch the host.

Events in Kafka

TopicKeySaysRead by
url-discoveredHostURL, source, link text, hint of valueFrontier
page-fetchedHostStatus, size, type, duration, where the body isParsers
page-parsedHostChanged or not, fingerprint, linksIndex team, recrawl planner
fetch-failedHostError, attempt, next attemptFrontier, alerts
All keyed by host, so one host's messages stay in order. Bodies travel as references when they are large.

Data

The URL record

SQL
CREATE TABLE urls (  host text, bucket int,          -- bucket = hash(url) % 64  url_hash blob,                  -- 128-bit  url text,  status text,                    -- pending, ok, gone, error, blocked  http_status int,  last_fetched_at timestamp,  next_fetch_at timestamp,  etag text, last_modified text,  content_hash blob, simhash bigint,  file text, file_offset bigint,  -- where the body is  visits int, changes int, retry_count int,  discovered_at timestamp, discovered_from text,  PRIMARY KEY ((host, bucket), url_hash));CREATE TABLE due (                -- what to fetch in a given hour  hour timestamp, shard int,  next_fetch_at timestamp, url_hash blob, host text,  PRIMARY KEY ((hour, shard), next_fetch_at, url_hash));
Cassandra. The partition key is the host plus a small bucket number, so a host can be read together without one huge partition.

Where each kind of data lives

DataStoreBecause
URL recordsCassandraAbout 2,000 writes a second, by key, easy to split
Visit historyCassandra, 90 daysAppend only, read by one URL
PagesObject storage, packedCheap, written once, read in bulk
FrontierMemory and RocksDB on the owner, log in KafkaLocal decisions, survives a restart
Seen setMemory on the owner90,000 checks a second
robots, DNS, paceMemory on the ownerBelongs to the host
Operator searchElasticsearchFind by host, status or error; may be late
One owner holds everything about a host. A shared Redis would work as well, at the price of a network call for each check.

Consistency by query

QueryLevelWhy
State of one URLQuorum read and writeThe schedule depends on it
History, statisticsOneApproximate is fine
Due listQuorum write, duplicates allowedA second entry only costs a check
Deleting after a takedownAll stores, then verifyMust really be gone

Counters for each host are kept by its owner and written once a minute. Cassandra counters are not safe to repeat after a timeout, and a little error here would mislead the budget.