Sub topic 17
Monitoring crawl health and metrics
This chapter assumes you have read the earlier chapters on the URL frontier, politeness, error handling, and concurrent fetching. You should be comfortable reading short Python programs and know basic HTTP status codes. A crawler can run for hours and still be broken. It may fetch the same trap forever, get blocked by a host, or stall on a full queue. Monitoring tells you which of these is happening, and it does so while the crawl is still running.
Why a crawler needs monitoring
A crawler has no user waiting for a response, so nothing fails loudly. A crawl that returns only errors still prints output and still uses CPU. You find out days later that the data is empty.
Monitoring answers three questions:
- Is the crawl making progress?
- Is it behaving politely and within its limits?
- Is the data it collects useful?
The metrics below follow the components you have already built. Errors and concurrency feed monitoring directly, so those two are the best starting point.
What to measure
Group metrics by the part of the crawler they describe.
| Area | Metric | What it tells you |
|---|---|---|
| Throughput | Pages fetched per second | Whether the crawl is moving |
| Frontier | Queue size, number of hosts with queued URLs | Whether work is piling up or running out |
| Outcomes | Count by status class (2xx, 3xx, 4xx, 5xx) | Whether pages are being fetched successfully |
| Failures | Timeouts, connection errors, robots.txt blocks | Whether hosts or the network are failing |
| Latency | Fetch time per request (median and 95th percentile) | Whether hosts are slow or you are overloaded |
| Content | Non-HTML skips, oversized pages, duplicate pages | Whether the fetched data is worth keeping |
| Politeness | Delay actually applied per host | Whether the crawler respects its own limits |
Use counters for things that only grow, such as pages fetched or errors seen. Use gauges for values that go up and down, such as queue size. Use histograms or percentiles for latency, because an average hides slow outliers.
A minimal metrics collector
You do not need a monitoring service to start. A small in-process collector is enough for a single-machine crawler. This one counts outcomes, records latencies, and prints a summary line on a fixed interval.
import time
from collections import Counter
class CrawlMetrics:
def __init__(self):
self.started = time.monotonic()
self.counts = Counter()
self.latencies = []
def record(self, outcome, seconds=None):
self.counts[outcome] += 1
if seconds is not None:
self.latencies.append(seconds)
def percentile(self, p):
if not self.latencies:
return None
ordered = sorted(self.latencies)
index = min(len(ordered) - 1, int(len(ordered) * p / 100))
return ordered[index]
def summary(self, queue_size):
elapsed = max(time.monotonic() - self.started, 1e-9)
ok = self.counts['ok']
errors = sum(v for k, v in self.counts.items() if k != 'ok')
total = ok + errors
error_rate = errors / total if total else 0.0
p50 = self.percentile(50)
p95 = self.percentile(95)
return (f'pages/s={ok / elapsed:.2f} queue={queue_size} '
f'error_rate={error_rate:.0%} p50={p50} p95={p95}')
metrics = CrawlMetrics()
metrics.record('ok', 0.21)
metrics.record('ok', 0.35)
metrics.record('timeout', 10.0)
print(metrics.summary(queue_size=120))Call metrics.record in the crawl loop after each fetch, with an outcome label such as 'ok', 'timeout', 'http_5xx', or 'robots_blocked'. Keeping a list of every latency grows without bound in a long crawl. For a real run, keep a fixed-size window of recent values or use fixed buckets.
How the metrics connect to the crawler
Each component reports to the same collector, and a periodic reporter reads from it.
Keep the collector separate from the crawl logic. The fetcher should only say what happened. Deciding whether that is a problem belongs to the alert rules.
Reading the signals
A single number rarely explains a problem. Compare several together.
- Throughput drops, queue is large. The crawler is slow. Check latency and per-host delays. If a few hosts own most of the queue, politeness delays cap your speed, and adding workers will not help.
- Throughput drops, queue is empty. The crawl is running out of work. This is normal at the end of a bounded crawl. It is a problem if the seed list was large.
- Queue grows without limit. Links are discovered faster than they are fetched. Suspect a crawl trap, such as a calendar or a session-ID parameter that creates endless URLs. Look at the most common hosts and path patterns in the queue.
- Error rate jumps for one host. The host may be down or blocking you. A burst of 403 or 429 responses means you should slow down for that host.
- Timeouts rise everywhere. Your own network or machine is the likely cause, not the sites. Check CPU use and the number of open connections.
- Many duplicate pages. URL normalization is missing a case, or content deduplication is catching what URL deduplication should have caught.
Per-host metrics
Totals can look healthy while one host is in trouble. Track counts per host as well, but limit how many hosts you keep. A crawl across millions of hosts cannot hold a full set of counters for each one in memory.
A practical approach is to keep detailed counters only for the busiest hosts and for any host that has recently had errors. Evict hosts that have been quiet.
from collections import defaultdict, deque
class HostHealth:
def __init__(self, window=20):
self.window = window
self.recent = defaultdict(lambda: deque(maxlen=window))
def record(self, host, success):
self.recent[host].append(success)
def failure_rate(self, host):
results = self.recent[host]
if not results:
return 0.0
return 1 - sum(results) / len(results)
def unhealthy(self, threshold=0.5, min_samples=10):
return [h for h, r in self.recent.items()
if len(r) >= min_samples and 1 - sum(r) / len(r) >= threshold]
health = HostHealth()
for ok in [True] * 4 + [False] * 8:
health.record('slow.example.com', ok)
print(health.unhealthy()) # ['slow.example.com']A sliding window of the last N results reacts to recent changes. A lifetime counter would hide a host that failed only in the last minute. The min_samples check stops a host from being flagged after one bad request.
You can act on this signal. A host above the failure threshold can get a longer delay in the frontier, or it can be paused for a while and retried later. That ties monitoring back to politeness and retry logic.
Alerts and thresholds
An alert should lead to an action. Start with a few rules and adjust them after you see real crawls.
- No progress. Zero pages fetched for several minutes while the queue is not empty.
- High error rate. More than a set share of fetches failing over a recent window, for example 30 percent over five minutes.
- Queue growth. The queue grows faster than a set rate for a long time.
- Host blocking. A host returns repeated 403 or 429 responses.
- Resource limits. Memory, disk, or open file handles near their limits.
Compare a recent window against the rate, not against the lifetime total. A crawl that ran well for ten hours has a good lifetime average even if it has been failing for the last ten minutes.
Logging for debugging
Metrics say that something is wrong. Logs say why. Log one structured line per fetch with the URL, host, status, latency, size, and outcome. Keep logs at a level that you can afford to store, since a busy crawl writes millions of lines.
Include these items to make problems traceable:
- The final URL after redirects, as well as the requested URL.
- The number of retries used.
- The reason a URL was skipped, such as a robots.txt rule, a depth limit, or a non-HTML content type.
- The depth of the URL from its seed.
Sampling helps when volume is high. Log every failure but only a small share of successes.
Checking data quality
A crawl can run cleanly and still collect bad data. Add a few checks on the content itself:
- Share of pages with extractable text. A sudden drop may mean sites now require JavaScript rendering.
- Average number of links per page. A drop to zero suggests a parsing problem.
- Share of near-duplicate pages. A rise suggests a trap or a template-only site.
- Distribution of pages per host. One host holding most of the budget may mean a trap or a missing per-host limit.
Spot-check a few stored pages by hand during early runs. No metric replaces reading actual output.
Common mistakes
- Using lifetime averages only. They hide recent failures.
- Measuring only successes. Without failure counts, a stalled crawl looks quiet instead of broken.
- Unbounded metric storage. Per-URL or per-host data without eviction can exhaust memory.
- Mixing outcome labels. If
'error'covers timeouts, DNS failures, and 500 responses together, you cannot tell which one is rising. Use distinct labels. - Alerting on single events. This causes alert fatigue.
Exercise
Your crawler's queue size has grown for two hours, while pages fetched per second has stayed flat and the error rate is low. Name the most likely cause, one metric or log breakdown you would check to confirm it, and one action to take.
Show answer
The most likely cause is a crawl trap, or another source of URLs that are discovered faster than they are fetched. Confirm it by grouping the queued URLs by host and path pattern, and look for one host or pattern, such as a calendar or a session-ID parameter, that dominates. Then add a per-host page budget or depth limit, and add a normalization rule that strips the offending parameter.
Exercise
A crawl shows an overall error rate of 4 percent, which looks healthy. One host has returned 429 responses for the last 15 requests. Why did the overall number hide this, and what should the crawler do for that host?
Show answer
The overall rate is dominated by the many hosts that succeed, so one failing host barely changes it. Per-host sliding-window tracking exposes it. The crawler should slow down for that host, for example by raising its delay or honoring any Retry-After header, and pause it for a while before trying again.