Sub topic 14
Recrawling and keeping the index fresh
A search index is a snapshot. The moment a crawler stores a page, the live page can change, move, or disappear. This chapter covers how crawlers decide when to revisit a URL, how they check cheaply for changes, and how a site owner can speed up or slow down that process.
It assumes you know HTTP status codes and headers, and that you have read the earlier chapters on fetching, politeness and crawl budget. You should be able to read short Python snippets.
Why freshness is a scheduling problem
A crawler cannot revisit every URL constantly. Every revisit uses fetch capacity that is also needed to discover new pages, and it puts load on the site. Two goals pull against each other:
- Freshness: the stored copy should match the live page.
- Coverage: new and unseen pages should get fetched at all.
The same crawl budget pays for both. Recrawl scheduling is the policy that splits it.
The cost of staleness is also uneven. A stale news front page misleads users within hours. A stale "About us" page rarely matters for months. A good scheduler therefore ranks pages by how likely they are to have changed, multiplied by how much a stale copy would hurt.
Signals that drive the schedule
A crawler estimates each URL's change rate from what it has observed, plus a few hints.
| Signal | What it tells the crawler | Reliability |
|---|---|---|
| Observed change history | How often the content differed across past fetches | High, but needs several visits |
| Page importance | How many links point to it, how often users reach it | Medium |
| Section or site pattern | Pages under `/news/` change faster than `/docs/archive/` | Medium |
| Sitemap `lastmod` | The site claims the page changed on this date | Only as good as the site's accuracy |
| `ETag` and `Last-Modified` headers | Validators for cheap change checks | High when the server implements them correctly |
| `Cache-Control` and `Expires` | The server's own freshness lifetime | Treated as a weak hint |
| Inbound link churn | New links to a page can mean new content | Low to medium |
Observed history is the strongest signal. Hints from the site help most when the crawler has little history, for example on a new URL.
Cheap change detection with conditional requests
A full fetch downloads the whole body. A conditional request asks the server to send the body only if it differs from a version the client already holds. The crawler stores the ETag and Last-Modified values from the previous response. It sends them back as If-None-Match and If-Modified-Since. If nothing changed, the server replies 304 Not Modified with no body.
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def conditional_fetch(url, etag=None, last_modified=None):
headers = {}
if etag:
headers["If-None-Match"] = etag
if last_modified:
headers["If-Modified-Since"] = last_modified
request = Request(url, headers=headers)
try:
with urlopen(request, timeout=10) as resp:
body = resp.read()
return resp.status, body, resp.headers.get("ETag"), resp.headers.get("Last-Modified")
except HTTPError as err:
if err.code == 304:
return 304, None, etag, last_modified
raiseurllib raises HTTPError for any non-success status, including 304, so the function catches it and returns the stored validators unchanged. Everything else is re-raised.
A 304 saves bandwidth for both sides. It does not save the request itself, so it still counts against rate limits. Some crawlers count a 304 as a cheaper request in their budget accounting, but you cannot rely on that.
Conditional requests fail in predictable ways:
- Unstable ETags. Servers behind a load balancer sometimes generate a different
ETagper node. Every check looks like a change. - Dynamic pages with a fresh timestamp. If the server sets
Last-Modifiedto the current time, the page always appears modified. - Ignored validators. Many dynamic apps return
200with the full body regardless. The crawler then has to compare content itself, for example with a hash of the extracted text.
An adaptive recrawl scheduler
A simple policy: when a fetch finds a change, shorten the interval. When it finds none, lengthen it. Clamp the interval between a minimum and a maximum. The following runs offline using simulated pages that change at fixed periods.
import heapq
HOUR = 3600
MIN_INTERVAL = HOUR
MAX_INTERVAL = 32 * 24 * HOUR
def next_interval(current, changed):
if changed:
return max(MIN_INTERVAL, current // 2)
return min(MAX_INTERVAL, current * 2)
# Simulated pages: each one changes once per `period` seconds.
pages = {
"https://example.com/news": 6 * HOUR,
"https://example.com/about": 90 * 24 * HOUR,
}
def version(url, now):
return now // pages[url]
last_seen = {}
fetches = {url: 0 for url in pages}
queue = []
for url in pages:
heapq.heappush(queue, (0, url, 24 * HOUR))
horizon = 60 * 24 * HOUR
while queue:
when, url, interval = heapq.heappop(queue)
if when > horizon:
break
current = version(url, when)
changed = url in last_seen and last_seen[url] != current
last_seen[url] = current
fetches[url] += 1
new_interval = next_interval(interval, changed)
heapq.heappush(queue, (when + new_interval, url, new_interval))
print(fetches)The priority queue is ordered by the next due time, so the scheduler always handles the most overdue URL first. The about page is revisited at growing gaps. The news page settles at short gaps.
Real schedulers refine this in several ways. They estimate a change probability instead of doubling and halving. They weight by page importance. They ignore trivial changes such as a rotating ad or a "last updated" footer, usually by comparing extracted main text rather than raw HTML.
What a recrawl does with each response
The result of a revisit determines what happens to the index entry.
| Response | Typical effect on the index |
|---|---|
| 200 with changed content | Re-extract text, update the index entry, shorten the interval |
| 200 or 304 with no change | Keep the entry, lengthen the interval |
| 301 or 308 | Treat the target as the new location and move the entry over. The old URL is dropped after the redirect is seen consistently |
| 302 or 307 | Usually keep the original URL indexed and follow the target for content |
| 404 | Mark as missing. Remove after the error persists over several visits |
| 410 | A stronger removal signal, and often removed sooner |
| 429 or 5xx | Treat as temporary. Retry later with backoff, and slow down for the whole host |
| robots.txt now disallows | Stop fetching. Existing index entries may remain for a while without a snapshot |
Persistent 5xx errors across a whole site are a special case. Crawlers lower the host's fetch rate to protect it, and the effect on freshness can last well after the outage ends.
The robots.txt file itself is recrawled on a schedule, and crawlers commonly cache it for up to about a day. A rule change therefore takes effect with some delay.
Pages that disappear: soft 404s
A server may answer 200 for a page that says "Not found" or shows an empty template. Crawlers try to detect these soft 404s from content patterns and treat them as errors. If detection fails, the dead URL stays in the index and keeps being revisited. Returning a real 404 or 410 is more reliable.
Helping the crawler as a site owner
You can improve how quickly changes get picked up without changing the crawler.
- Serve correct validators. Stable
ETagor an accurateLast-Modified. - Keep sitemap
lastmodhonest. Update it only when the main content changes. If every URL shows today's date, the crawler learns to ignore it. - Link new content from frequently crawled pages. A link from the home page is often discovered sooner than a sitemap entry.
- Use redirects correctly. A permanent move should be a 301 or 308, not a 302.
- Keep the server fast and stable. Slow responses reduce the crawl rate the crawler allows itself.
Search engines also offer tools to ask for a specific URL to be reconsidered. These submit a request. They do not guarantee a revisit time, and they are meant for a few important URLs, not for bulk use.
Where the schedule fits in the pipeline
The index update is a separate step from the fetch. A page can be recrawled and still show an old snippet in results for some time, because the index and the serving layer refresh on their own cycles.
Common mistakes
- Treating "I changed the page" as "the index changed." There is a delay at every stage.
- Blocking a URL in robots.txt and expecting it to be removed. The crawler can no longer fetch the page, so it never sees a
noindextag or a 404. - Redirecting an old URL with a 302 and expecting the new URL to replace it in the index.
- Updating
lastmodon every deploy. - Returning
200with an error message for missing pages.
Exercise
A news site lists a story in its sitemap with a current lastmod, and its server always returns 200 with a fresh Last-Modified header set to the request time. Give two ways this hurts the crawler's freshness decisions, and one fix.
Show answer
First, every conditional request looks like a change, so the crawler cannot tell real updates from no change and wastes budget re-processing unchanged pages. Second, once the crawler learns that lastmod and Last-Modified are always "now", it discounts them, so genuine updates lose their signal. The fix is to set Last-Modified and lastmod from the content's real modification time, and ideally to add a stable ETag.
Exercise
In the scheduler above, what happens to the interval of a page that is fetched with no change over and over? What bounds it?
Show answer
Each unchanged fetch doubles the interval, so revisits become less frequent. The growth stops at MAX_INTERVAL, which is 32 days in the code. A later change halves the interval, never below MIN_INTERVAL, which is one hour.