Design an Up-To-Date Knowledge Base Page Crawler
System DesignModel answerLast updated
Design a distributed web crawler and storage architecture that guarantees every page in a target wiki is updated at least once every five days.
Design a large-scale crawling and storage system for a comprehensive online wiki. The primary objective is to maintain an accurate, historical store of all wiki pages while guaranteeing that no stored page is ever more than five days out of date relative to the live site.
Scope & Scale Assumptions
Clarify and state explicit capacity requirements before diving into architecture. For this problem, assume:
- Total Pages ($N$): 50 million distinct articles/pages.
- Average Page Size: 100 KB (including raw markup, HTML, and essential metadata; external media such as full-resolution images/videos are out of scope).
- Target Freshness Threshold ($T_{max}$): 5 days ($432,000$ seconds).
- Interface Availability: The system must rely on standard HTTP crawling and API endpoints (e.g., MediaWiki APIs or Change Feeds if available), while respecting site politeness guidelines.
Requirements & Key Aspects to Address
- Back-of-the-Envelope Calculations: Calculate the necessary throughput (pages/sec, bandwidth) and total storage required to meet the 5-day freshness SLA.
- System Architecture: Detail the pipeline components (URL discovery, scheduler/frontier, fetcher workers, change detector, storage engine).
- Freshness & Scheduling Strategy: Explain how the scheduler guarantees the 5-day SLA across all pages while prioritizing high-churn pages.
- Storage Architecture: Describe how page contents, versions, and crawl metadata are persisted and indexed efficiently.
- Politeness & Resilience: Address rate-limiting, error handling, retries, and SLA monitoring.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Requirements & Capacity Estimates
Functional Requirements
- Bounded Staleness: Every single stored page must reflect a state that is at most 5 days old relative to the live site.
- Content Storage: Store the latest text/HTML content and retain historical versions or snapshot diffs for auditing.
- Discovery: Automatically discover new pages linked from existing ones.
Non-Functional Requirements
- High Availability & Fault Tolerance: Worker failures or worker crashes must not result in SLA breaches.
- Politeness: Adhere to
robots.txtand cap requests per second (RPS) per domain/IP to prevent denial-of-service on the host.
Estimations & Sizing
- Total Pages ($N$): $50,000,000$ pages.
- Freshness SLA ($T$): 5 days = $5 \times 86,400 = 432,000$ seconds.
- Minimum Average Read Throughput: $$\text{Throughput} = \frac{50,000,000 \text{ pages}}{432,000 \text{ seconds}} \approx 116 \text{ pages/second}$$ To accommodate burstiness, retries, and high-priority recrawls, we design for $3\times$ capacity $\approx 350$ pages/sec.
- Bandwidth: $$350 \text{ pages/sec} \times 100 \text{ KB/page} = 35 \text{ MB/sec} = 280 \text{ Mbps}$$
- Raw Storage Requirements (1 Snapshot): $$50,000,000 \text{ pages} \times 100 \text{ KB} = 5 \text{ TB}$$ Assuming compressed diff storage adding ~20% growth per month, storing 1 year of history requires roughly $5\text{ TB} + (12 \times 1\text{ TB}) = 17\text{ TB}$.
2. Architecture Overview
The system consists of six primary subsystems operating in a decoupled pipeline:
+-----------------------+
| Wiki Event Feed / |
| RecentChanges API |
+-----------+-----------+
|
v
+------------------+ +--------------+ +-------------------+
| Politeness & |-->| Crawl |<--| Periodic SLA |
| Rate Limiter | | Frontier | | Sweeper Engine |
+------------------+ +------+-------+ +-------------------+
|
v
+---------------+
| Fetcher Pool |
+-------+-------+
|
v
+---------------+
| Change & Link |
| Processing |
+-------+-------+
|
+-------------------+-------------------+
| |
v v
+------------------+ +-------------------+
| Content Store | | URL & Metadata |
| (S3 / Blob Store)| | Database |
+------------------+ +-------------------+
- Crawl Frontier & Priority Queue: Manages and prioritizes page URLs pending fetch execution.
- Periodic Sweeper & Change Log Listener: Pushes URLs into the frontier via two paths: real-time updates and deterministic 5-day expiration sweeps.
- Fetcher Workers: Lightweight, highly concurrent async workers that pull URLs from host-polite queues, fetch content over HTTP, and handle conditional
GETrequests usingIf-Modified-SinceorETag. - Change & Parsing Service: Calculates content hashes (e.g., SHA-256), extracts outbound links, and identifies if the content actually changed.
- Storage Layer: Stores raw page content and version diffs in object storage, while metadata is maintained in a distributed relational/document store.
- SLA Monitor: Tracks fetch staleness distribution across all pages and alerts if any page approaches the 5-day deadline.
3. Crawl Scheduling & Freshness SLA
To guarantee that no page breaches the 5-day limit while efficiently utilizing network capacity, we employ a Dual-Trigger Scheduling System.
Primary Mechanism: Fixed Expiration Sweeper
- Every page record in the database contains a
last_crawled_attimestamp. - An index on
(last_crawled_at ASC)allows the Periodic Sweeper Engine to continuously query for URLs where: $$\text{Current Time} - \text{last_crawled_at} \ge 4.5 \text{ days}$$ - Using a 4.5-day trigger (108 hours) provides a 12-hour buffer zone for retries, queue backlogs, and rate-limiting throttling before reaching the hard 5-day deadline.
Secondary Mechanism: Adaptive / Event-Driven Boosting
- Change Log Polling: If the target wiki provides an API endpoint (such as MediaWiki’s
RecentChanges), an ingestion daemon continuously consumes this stream and pushes modified URLs into high-priority queues. - Adaptive Recrawl Frequency: Pages that undergo frequent edits are assigned a calculated
adaptive_interval(e.g., fetch every 6 hours). However, the absolute maximum scheduling interval is hard-capped at 4.5 days regardless of historic edit frequency.
Queue Structure & Politeness Control
To respect target server limits:
- Host Mapping: Each URL is hashed to a specific domain queue (
host_id). - Delay Enforcer: A Redis-backed token bucket or delay queue ensures a minimum delay (e.g., 200ms) between consecutive requests to the same
host_id. - Priority Levels:
- Priority 1 (High): Recent changes feed events.
- Priority 2 (Medium): Hard SLA expiration (pages reaching 4.5 days since last fetch).
- Priority 3 (Low): Newly discovered links / discovery crawl.
4. Data Storage & Schema Design
1. Metadata & State Store (e.g., PostgreSQL / CockroachDB)
Stores tracking data for scheduling and SLA verification.
pages Table Schema:
| Column | Type | Description |
|---|---|---|
page_id | UUID | Primary Key |
url | VARCHAR(2048) | Unique URL identifier |
host_id | VARCHAR(255) | Domain identifier for rate limiting |
last_crawled_at | TIMESTAMP | Timestamp of last successfully completed fetch |
last_modified_header | VARCHAR(255) | HTTP Last-Modified string |
etag | VARCHAR(255) | HTTP ETag string |
content_hash | CHAR(64) | SHA-256 of cleaned body content |
status | ENUM | ACTIVE, DELETED, REDIRECT |
Index Requirements: CREATE INDEX idx_staleness ON pages (last_crawled_at ASC);
2. Raw Content & Version Storage (e.g., S3 / Blob Storage)
- Raw HTML/markup files are stored in object storage:
s3://wiki-archive-bucket/{page_id}/{timestamp}.html.gz - Deduplication: When a fetcher receives HTTP 200, the hash of the body content is compared against
content_hashin the database.- If HTTP 304 (Not Modified) or content hash matches: Update
last_crawled_atin the database without writing a new object to S3. - If content hash differs: Save the object to S3 and add a new row in a
page_versionstracking table.
- If HTTP 304 (Not Modified) or content hash matches: Update
5. Politeness, Fault Handling & Edge Cases
Politeness & Rate Limits
- Robots.txt Engine: Parse and cache
robots.txtrules per domain for 24 hours. Reject unallowed paths before placing them in fetch queues. - Concurrency Limits: Cap max concurrent connections to 5-10 sockets per host IP.
HTTP Bandwidth Optimizations
- Conditional Headers: Always send
If-None-Match: <etag>andIf-Modified-Since: <last_modified_header>. This avoids transferring body payloads for non-updated pages, saving up to 80% of bandwidth during sweep fetches.
Error Handling & Edge Cases
- Server Errors (5xx) / Timeouts: Retried using exponential backoff with jitter (e.g., retry after 1m, 5m, 15m). If retries fail past 6 hours, log an alert to prevent silent SLA breach.
- Deleted Pages (404/410): Mark status as
DELETEDin the database. Do not purge historic S3 records, but reduce recrawl frequency or handle via specific deletion feeds. - Infinite Loops & Dynamic URLs: Canonicalize URLs (strip query params, normalize paths) and limit depth for newly discovered links.
6. Monitoring & SLA Verification
To guarantee compliance with the 5-day staleness invariant, monitor the following metrics:
- Max Staleness Gauge: $\max(\text{Now} - \text{last_crawled_at})$ across all records in the
pagestable. Trigger PagerDuty alerts if this value exceeds 4.8 days. - Staleness Distribution Histogram: Percentiles (p50, p95, p99, p100) of page ages.
- Queue Latency & Depth: Number of pending items in Priority 2 (SLA Expiration) queue.
- HTTP Status Ratio: Ratio of 200 OK vs 304 Not Modified vs 4xx/5xx responses.
Trade-offs & Alternatives
| Approach | Advantages | Disadvantages |
|---|---|---|
| Pure Periodic Recrawl | Simple to implement, deterministic. | Ignores change frequency; wastes bandwidth on static pages. |
| Pure Event-Driven (API) | Real-time updates, low network overhead. | Single point of failure; missed events permanently breach SLA. |
| Hybrid (Design Used) | Guarantees strict SLA ceiling via periodic fallback while keeping active pages updated rapidly. | Slightly higher architecture complexity (maintaining queues and sweeps). |