Sub topic 13
Storing Pages and Checkpointing Crawl State
This chapter assumes you have read the chapters on the URL frontier and URL deduplication. You should be comfortable with Python sets, queues, and files. A crawl can run for hours. If the process dies, you want to resume it, not start over. Two things make that possible: storing what you fetched, and saving enough state to continue.
What to store
A crawler produces two kinds of data:
- Page data: the response body, the final URL after redirects, the status code, headers, and a fetch timestamp. This is large and written once.
- Crawl state: the frontier (URLs waiting to be fetched) and the seen set (URLs already queued or fetched). This is small per entry but changes constantly.
Keep them apart. Page data is an append-only archive. Crawl state is something you rewrite or snapshot.
Storing pages
Writing one file per page works for a few hundred pages. At millions of pages, it exhausts the filesystem's inodes and makes backups slow. A common alternative is an append-only file of JSON lines, with one record per page.
import json
import time
def store_page(archive, url, status, html):
record = {
'url': url,
'status': status,
'fetched_at': time.time(),
'html': html,
}
archive.write(json.dumps(record) + '\n')
archive.flush()
with open('pages.jsonl', 'a', encoding='utf-8') as archive:
store_page(archive, 'https://example.com/', 200, '<html></html>')Opening in append mode means a restart adds to the file instead of overwriting it. For larger crawls, rotate files (for example, one per 10,000 pages) and compress them. Real systems often use the WARC format, which is designed for web archives.
Checkpointing crawl state
A checkpoint is a snapshot of the frontier and seen set. After a crash, you load the latest checkpoint and continue.
The risk is a crash in the middle of writing the checkpoint, which leaves a corrupt file. Avoid this by writing to a temporary file and then renaming it. A rename within one filesystem is atomic, so the checkpoint file is always either the old version or the new one.
import json
import os
def save_checkpoint(path, queued, seen):
tmp = path + '.tmp'
with open(tmp, 'w', encoding='utf-8') as f:
json.dump({'queued': queued, 'seen': sorted(seen)}, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
def load_checkpoint(path):
if not os.path.exists(path):
return [], set()
with open(path, encoding='utf-8') as f:
data = json.load(f)
return data['queued'], set(data['seen'])
save_checkpoint('state.json', ['https://example.com/a'], {'https://example.com/', 'https://example.com/a'})
queued, seen = load_checkpoint('state.json')
print(len(queued), len(seen)) # 1 2Common errors
- Checkpointing too rarely. You lose all work since the last snapshot. Checkpoint every N pages or every few minutes.
- Checkpointing the seen set but not the queue. URLs marked seen but never fetched are lost forever after a restart.
- Replaying pages. Pages fetched after the last checkpoint are fetched again on resume. Make storage idempotent, for example by keying records on the URL, and deduplicate when reading.
- Slow full snapshots. Rewriting a huge seen set every time becomes expensive. Larger crawls move to a database such as SQLite, or to a write-ahead log of changes.
Exercise
Your crawler saves a checkpoint by opening state.json in write mode and dumping JSON into it. The machine loses power during the write. What can go wrong, and how do you fix it?
Show answer
The file can be left truncated or half-written, so the crawler cannot load it on restart and the old checkpoint is already gone. Write to a temporary file, flush and fsync it, then use os.replace to swap it over state.json. The rename is atomic, so state.json is always a complete checkpoint.