Sub topic 13
Storing pages and checkpointing crawl state
This chapter assumes you have read the earlier chapters on the URL frontier and the seen set. You should be comfortable with Python, SQLite basics, and the idea that a process can be killed at any moment. The crawler so far keeps everything in memory. If it stops after six hours, you lose the downloaded pages, the frontier, and the seen set. This chapter fixes that.
What to store
A fetched page is more than its HTML. Keep enough to re-parse it later without fetching again, and to explain what happened during the fetch.
- The requested URL and the final URL after redirects.
- The HTTP status code and the response headers you care about, such as
Content-Type,ETag, andLast-Modified. - The fetch time.
- The body, compressed.
- A hash of the body, which the content deduplication chapter uses.
Storing raw bodies separately from derived data (extracted text, links) lets you improve your parser and re-run it over saved pages. That is much cheaper than re-crawling.
Choosing a storage format
| Option | Strength | Weakness |
|---|---|---|
| One file per page | Trivial to write and inspect | Millions of small files exhaust inodes and make directory listings slow |
| Append-only archive files such as WARC | Standard format, fast sequential writes, good for bulk processing | No random lookup without a separate index |
| SQLite | Transactions, indexed lookup by URL, one file | One writer at a time, so it fits a single machine |
| Object store plus a key-value index | Scales across machines | More moving parts and more failure modes |
For a single-machine crawler, SQLite is a good default. The deciding advantage is that you can write a page and update the URL's state in one transaction. The rest of this chapter relies on that.
What crawl state must survive a restart
The state to persist is smaller than the page data.
- The seen set, so you do not refetch URLs.
- The set of URLs that are queued but not yet fetched. This is the frontier's contents.
- Retry counts, so a permanently failing URL does not loop forever.
- Optionally, the robots.txt cache, which is cheap to rebuild.
Some state should not be saved. The frontier from the earlier chapter keeps next_time values from time.monotonic(). A monotonic clock has an arbitrary starting point that resets when the machine restarts, so saved values are meaningless afterwards. On restore, start every host with no pending delay. Politeness is preserved because the first request to each host is the first request in the new process.
One table for state, one for pages
Instead of periodically snapshotting an in-memory frontier, you can make the database the source of truth. Each URL gets a row with a state. A URL is "seen" if it has a row. It is "pending" if its state is queued.
import gzip
import hashlib
import sqlite3
import tempfile
import time
from pathlib import Path
SCHEMA = """
CREATE TABLE IF NOT EXISTS urls (
url TEXT PRIMARY KEY,
state TEXT NOT NULL DEFAULT 'queued',
attempts INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS pages (
url TEXT PRIMARY KEY,
final_url TEXT NOT NULL,
status INTEGER NOT NULL,
fetched_at REAL NOT NULL,
content_hash TEXT NOT NULL,
body BLOB NOT NULL
);
"""
class CrawlStore:
def __init__(self, path):
self.conn = sqlite3.connect(path)
self.conn.execute('PRAGMA journal_mode=WAL')
self.conn.executescript(SCHEMA)
def add_urls(self, urls):
with self.conn:
self.conn.executemany(
'INSERT OR IGNORE INTO urls (url) VALUES (?)',
[(u,) for u in urls])
def save_page(self, url, final_url, status, html):
digest = hashlib.sha256(html.encode('utf-8')).hexdigest()
body = gzip.compress(html.encode('utf-8'))
with self.conn: # one transaction: both changes or neither
self.conn.execute(
'INSERT OR REPLACE INTO pages VALUES (?, ?, ?, ?, ?, ?)',
(url, final_url, status, time.time(), digest, body))
self.conn.execute(
"UPDATE urls SET state = 'done' WHERE url = ?", (url,))
def mark_failed(self, url):
with self.conn:
self.conn.execute(
"UPDATE urls SET state = 'failed', attempts = attempts + 1 "
"WHERE url = ?", (url,))
def pending(self):
rows = self.conn.execute(
"SELECT url FROM urls WHERE state = 'queued' ORDER BY rowid")
return [r[0] for r in rows]
def load_page(self, url):
row = self.conn.execute(
'SELECT body FROM pages WHERE url = ?', (url,)).fetchone()
return gzip.decompress(row[0]).decode('utf-8') if row else None
def close(self):
self.conn.close()
with tempfile.TemporaryDirectory() as tmp:
db = str(Path(tmp) / 'crawl.db')
store = CrawlStore(db)
store.add_urls(['https://example.com/', 'https://example.com/b'])
store.save_page('https://example.com/', 'https://example.com/', 200,
'<html>hello</html>')
store.close()
# Simulate a restart: reopen the same file.
store = CrawlStore(db)
print(store.pending()) # ['https://example.com/b']
print(store.load_page('https://example.com/')) # <html>hello</html>
store.close()After a restart, pending() gives you the URLs to push into the frontier with frontier.add. The frontier's own seen set can be rebuilt from every URL in the urls table, so add ignores anything already known.
Why one transaction matters
A crash can land between any two statements. Consider two separate commits: first save the page, then mark the URL done.
- If the crash lands between them, the page is stored but the URL is still
queued. After restart the crawler fetches it again. That is wasted work, but nothing is lost, becauseINSERT OR REPLACEmakes the second save harmless. - If you did it in the opposite order, a crash would leave the URL marked
donewith no page. That loses data silently.
Putting both statements in one transaction removes the window. Even so, design the crawler for at-least-once processing. A URL can be fetched twice, for example if the process dies after the download but before the commit. Storage keyed by URL makes repeated writes idempotent, meaning that writing twice gives the same result as writing once.
Snapshots as an alternative
If you keep the frontier in memory for speed, you can instead write periodic snapshots. The key rule is atomic replacement. Write the new snapshot to a temporary file, flush it to disk, then rename it over the old one. A rename within one filesystem is atomic, so a reader sees either the old complete file or the new complete file, never a half-written one.
import json
import os
def write_atomic(path, data):
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
write_atomic('checkpoint.json', {'queued': ['https://example.com/b'], 'seen': 2})
with open('checkpoint.json', encoding='utf-8') as f:
print(json.load(f))A snapshot only captures one moment. Work done after the snapshot is repeated after a restart. To shrink that gap, append each event (URL added, URL done) to a log file between snapshots, and replay the log on startup. This pairing of snapshot plus log is the same idea databases use internally.
Gotchas and edge cases
- Durability settings. In WAL mode with
synchronous=NORMAL, a killed process loses nothing, but a power failure can roll back the last few commits. For a crawler that is usually acceptable, since lost work is simply refetched. Setsynchronous=FULLif it is not. - Commit frequency. One commit per page is simple and safe. At high rates, commits become the bottleneck, so batch several pages per transaction and accept that a crash repeats that batch.
- Database growth. Compressed HTML is often a quarter of its original size, but a large crawl still produces gigabytes. Consider storing bodies in separate files and keeping only a path and offset in the database.
- In-flight URLs. A URL being fetched when the crawler dies is still
queuedin the database, so it returns on restart. If a URL crashes the process every time, such as a pathological page that exhausts memory, count attempts and give up after a limit. - Redirects. Store both the requested and final URLs. The requested URL is what the seen set knows. The final URL is what you may want to normalize and deduplicate.
Exercise
In save_page, suppose the page insert and the UPDATE urls SET state = 'done' were committed as two separate transactions, and the process was killed between them. What happens after restart, and why does the page table stay correct?
Show answer
The page row exists but the URL is still queued, so the crawler fetches it again. The second save_page uses INSERT OR REPLACE keyed by URL, so it overwrites the existing row instead of creating a duplicate. The cost is one wasted fetch. Using a single transaction removes even that.
Exercise
Why should a saved checkpoint not include the frontier's next_time values from time.monotonic(), and what should the restored frontier do instead?
Show answer
A monotonic clock's zero point is arbitrary and resets when the machine reboots, so saved values do not compare correctly with the new clock. The restored frontier should treat every host as having no pending delay, which means setting next_time to empty. The first fetch to each host after the restart then respects the per-host delay going forward.