Sub topic 14
Recrawling and keeping content fresh
A crawl that runs once produces a snapshot. Pages change, appear, and disappear, so the snapshot ages. This chapter covers how a crawler decides when to revisit a page, how it checks cheaply whether the page changed, and how it spends a limited fetch budget.
It assumes you have read the chapters on the URL frontier, per-host politeness, and content deduplication. You should be comfortable with HTTP headers and status codes, and with heaps.
Freshness is a budget problem
A crawler can fetch only so many pages per day, limited by bandwidth, politeness delays, and cost. If you recrawl everything as often as possible, you spend most of the budget on pages that never change. If you recrawl too rarely, your copy goes stale.
Two measures make the trade-off concrete:
- Freshness is the fraction of your stored pages that still match the live page right now.
- Age is how long a stored copy has been out of date. A page that changed an hour ago and has not been refetched has an age of one hour.
Freshness counts stale pages equally. Age penalizes a copy more the longer it stays wrong. Both measures lead to the same working goal: revisit each page often enough that the expected staleness stays acceptable, and no more often than that.
Pages differ widely in how fast they change:
| Page type | Typical change rate | Sensible recrawl interval |
|---|---|---|
| News front page | Minutes | Minutes to an hour |
| Forum thread listing | Hours | Hours |
| Product page | Days | Daily to weekly |
| Documentation page | Weeks to months | Weekly to monthly |
| Archived article | Almost never | Monthly or less |
A single global interval is therefore a poor design. Each URL needs its own schedule.
The recrawl loop
Recrawling adds a second source of work to the frontier. Until now, every URL entered the frontier once and left it. In a recrawling system, a fetched URL is scheduled to come back.
The per-host politeness rules from earlier chapters still apply. A recrawl fetch passes through the same per-host queues as a first visit.
Cheap change detection with conditional requests
The cheapest way to learn that a page did not change is to ask the server. HTTP supports this with validators.
- The server may send an
ETagheader, an opaque version identifier, and aLast-Modifiedheader with a timestamp. - On the next request, the crawler sends
If-None-Matchwith the stored ETag,If-Modified-Sincewith the stored timestamp, or both. - If the page is unchanged, the server answers
304 Not Modifiedwith no body. You save bandwidth and parsing time. - If the page changed, the server answers
200 OKwith the new body and new validators.
import urllib.error
import urllib.request
AGENT = 'MyCrawler'
def conditional_fetch(url, etag=None, last_modified=None,
timeout=10, max_bytes=2_000_000):
"""Return (status, body, etag, last_modified).
body is None when the server answers 304.
"""
headers = {'User-Agent': AGENT}
if etag:
headers['If-None-Match'] = etag
if last_modified:
headers['If-Modified-Since'] = last_modified
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
body = resp.read(max_bytes)
return (resp.status, body,
resp.headers.get('ETag'),
resp.headers.get('Last-Modified'))
except urllib.error.HTTPError as err:
if err.code == 304:
return 304, None, etag, last_modified
raiseurllib raises HTTPError for 304 because it is not a 2xx status, so the code catches it and treats it as a normal result. Other errors propagate to the retry logic from the error-handling chapter.
Validators have limits you must plan for:
- Many servers send no validators, especially for dynamically generated pages.
- Some servers send a fresh
Last-Modifiedon every request, set to the current time. A conditional request then always returns 200. - Some servers send an ETag that changes with every response, for example because the page embeds a timestamp or a CSRF token.
Because of these cases, treat a 304 as reliable evidence of no change, but never treat a 200 as proof of change. After a 200, compare a hash of the body with the stored hash. The content-deduplication chapter covers hashing. For recrawling, you often want to hash only the meaningful part of the page, with navigation bars, ads, and timestamps removed. Otherwise a page looks changed on every visit.
Adapting the interval
You rarely know a page's change rate in advance, so estimate it from observations. A simple, effective policy is multiplicative adjustment:
- If the page changed since the last visit, shorten the interval, for example by halving it.
- If it did not change, lengthen it, for example by multiplying by 1.5.
- Clamp the result between a minimum and a maximum.
import hashlib
import heapq
import time
MIN_INTERVAL = 3600 # one hour
MAX_INTERVAL = 30 * 86400 # thirty days
def next_interval(interval, changed):
if changed:
interval = interval / 2
else:
interval = interval * 1.5
return max(MIN_INTERVAL, min(MAX_INTERVAL, interval))
def content_hash(body):
return hashlib.sha256(body).hexdigest()
class RecrawlScheduler:
def __init__(self):
self.due = [] # heap of (next_fetch_time, url)
self.state = {} # url -> dict of interval, etag, last_modified, hash
def add(self, url, now=None):
now = time.time() if now is None else now
self.state[url] = {'interval': 86400, 'etag': None,
'last_modified': None, 'hash': None}
heapq.heappush(self.due, (now, url))
def pop_due(self, now=None):
now = time.time() if now is None else now
if self.due and self.due[0][0] <= now:
return heapq.heappop(self.due)[1]
return None
def record(self, url, status, body, etag, last_modified, now=None):
now = time.time() if now is None else now
st = self.state[url]
if status == 304:
changed = False
else:
new_hash = content_hash(body)
changed = new_hash != st['hash']
st['hash'] = new_hash
st['etag'], st['last_modified'] = etag, last_modified
st['interval'] = next_interval(st['interval'], changed)
heapq.heappush(self.due, (now + st['interval'], url))
return changed
# Simulate a page that never changes: the interval grows toward the cap.
sched = RecrawlScheduler()
sched.add('https://example.com/', now=0)
sched.pop_due(now=0)
sched.record('https://example.com/', 200, b'hello', None, None, now=0)
for day in range(1, 6):
now = sched.due[0][0]
url = sched.pop_due(now=now)
sched.record(url, 304, None, None, None, now=now)
print(day, round(sched.state[url]['interval'] / 3600, 1), 'hours')The first visit counts as a change because the stored hash is None. After that, an unchanged page backs off from 12 hours to 18, 27, 40.5 hours, and so on. A page that changes on every visit drops to the one-hour floor. The MIN_INTERVAL floor protects both the site and your budget from a page that changes constantly.
The scheduler is a heap ordered by due time. It plays the same role as the per-host heap in the frontier, but it orders by when a URL should be revisited rather than when a host may be contacted again. In a full crawler, URLs popped from this heap are handed to the frontier so politeness still applies.
Prioritizing under a fixed budget
When more URLs are due than you can fetch, you must choose. Useful signals for ranking due URLs:
- Observed change rate. Frequently changing pages lose value faster.
- Page importance. Pages with many inbound links, or high traffic in your product, deserve earlier revisits.
- Age since last fetch. Among otherwise equal pages, fetch the one that has waited longest.
- Server hints.
Cache-Control: max-ageandExpiresstate how long the site expects the copy to remain valid. Sitemaps may list alastmodvalue. Treat these as hints, because they are often wrong.
Optimizing plain freshness has a counterintuitive consequence. A page that changes faster than you can ever refetch it is always stale, so spending budget on it gains almost nothing. Under a tight budget, it is often better to skip such pages and spend the fetches on pages of moderate change rate.
Edge cases
- Deletions. A 404 or 410 on a recrawl means the page may be gone. Do not delete on the first 404, because transient misconfigurations happen. Require several consecutive failures across a few days, then mark the page removed and lengthen its interval sharply.
- Redirect changes. A page that starts redirecting elsewhere should have its new target added to the frontier. The old URL stays in your state with the redirect recorded.
- New pages. Recrawling existing pages is how you find new links. Recrawl hub pages such as indexes and feeds more often than leaf pages, because a hub's changes reveal new URLs.
- Clock skew. Use your own clock for scheduling. Pass the server's
Last-Modifiedstring back unchanged rather than parsing and reformatting it. - Crash recovery. Persist the due queue and per-URL state with the checkpointing approach from the storage chapter. Losing the schedule resets every interval, and the crawler floods the sites it just learned to visit gently.
Exercise
A page returns 200 on every conditional request, and its ETag differs each time. Its body hash is the same on the last ten fetches. What should the scheduler conclude about the page, and what should happen to its interval?
Show answer
The page is not changing. The server's validators are unreliable, so the crawler should trust the body hash instead of the 200 status or the ETag. Each of the ten visits counts as unchanged, so the interval grows by a factor of 1.5 each time until it reaches the maximum. The crawler still downloads the full body each time, so you may also decide to stop sending the unreliable validators for this host.
Exercise
Your crawler has budget for 1,000 fetches per day and 10,000 URLs due. One URL changes every few seconds. Should it get a daily fetch slot?
Show answer
Usually no. Even at the one-hour floor, a copy of that page is stale almost all the time, so each fetch adds little freshness. The slots are better spent on pages whose change rate is low enough that a fetch leaves the copy fresh for a meaningful time.