Design news sitemap TTL/freshness validator with alerts.
- User
Design news sitemap TTL/freshness validator with alerts.
Assistant
Design news sitemap TTL/freshness validator with alerts.
The user wants a design for a "news sitemap TTL/freshness validator with alerts". This is a specific technical component for SEO and publishing platforms. The goal is to ensure that a news sitemap (specifically Google News sitemaps) adheres to best practices regarding Time To Live (TTL - though usually sitemaps don't have a strict TTL like DNS, the concept applies to how long the sitemap is valid or how often it should be checked) and Freshness (articles shouldn't be too old).
1. Deconstruct the Request:
<news:news> extension in standard XML sitemaps).2. Identify Key Constraints & Rules (The "Why"):
3. Architectural Design:
High-Level Flow:
Detailed Component Design:
<news:publication_date>.now().<lastmod> tag (if exists).Cache-Control, Expires).lastmod is older than X hours but content is changing, it's stale.4. Selecting the Stack (Language/Tools):
5. Refining the Metrics (The "Validator" part):
sitemap_lastmod and newest_article_date.6. Drafting the Solution Structure: I will structure the response into:
7. Self-Correction/Review during drafting:
<lastmod>. Google doesn't strictly obey <lastmod> but checks HTTP headers. However, in the context of the prompt, "TTL" likely implies "Is this sitemap 'alive' and updated recently?" I will interpret TTL as "Sitemap Update Frequency/Last Modified".8. Final Polish:
(Self-Correction on TTL): I should clarify that while sitemaps don't have a hard "TTL", we are validating the freshness of the sitemap file itself. If the sitemap hasn't been regenerated in 24 hours, that's a system error (CMS pipeline broken), distinct from the articles inside being old.
9. Constructing the Output: (Proceeding to generate the response based on these steps). Here is a comprehensive design for a News Sitemap TTL & Freshness Validator.
This system monitors your news sitemap to ensure articles are being indexed quickly, removed when expired, and that the sitemap structure adheres to Google News guidelines (specifically the 48-hour freshness rule).
We will design this as a serverless microservice or a sidecar container that runs on a schedule (Cron).
graph TD
A[Scheduler (Cron/CloudWatch)] -->|Triggers every 15m| B(Validator Service)
B -->|HTTP GET| C[News Sitemap XML]
C --> B
B -->|Parse XML| D{Rule Engine}
D -->|Fail| E[Alert Dispatcher]
D -->|Pass| F[Metrics Store]
E -->|Webhook| G[Slack/PagerDuty]
E -->|Email| H[Dev Team]
Before coding, we must define what constitutes "Invalid" or "Stale."
Google News requires that URLs in a news sitemap be no older than 48 hours.
<news:publication_date> for every URL.CurrentTime - PublicationDate < 48 hours.The sitemap file itself must be dynamic.
<lastmod> tag of the <url> entries or the HTTP Last-Modified header of the sitemap file.<news:publication>, <news:title>, etc.).This script can be packaged into a Docker container or an AWS Lambda function.
import requests
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
import logging
# Configuration
SITEMAP_URL = "https://example.com/sitemap-news.xml"
MAX_ARTLE_AGE_HOURS = 48
ALERT_THRESHOLD_STALE = 40 # Warn if articles are approaching 48h
SITEMAP_UPDATE_FREQUENCY_MINS = 30
def get_sitemap(url):
resp = requests.get(url)
if resp.status_code != 200:
raise Exception(f"HTTP Error {resp.status_code}")
return resp.content
def parse_date(date_str):
# Standard ISO 8601 parsing
return datetime.fromisoformat(date_str.replace('Z', '+00:00'))
def validate_sitemap():
xml_content = get_sitemap(SITEMAP_URL)
root = ET.fromstring(xml_content)
# XML Namespaces are crucial for News Sitemaps
ns = {
'n': 'http://www.google.com/schemas/sitemap-news/0.9',
'x': 'http://www.sitemaps.org/schemas/sitemap/0.9'
}
now = datetime.now(timezone.utc)
errors = []
warnings = []
stats = {
'total_urls': 0,
'oldest_article_age_hours': 0,
'newest_article_age_hours': 0
}
for url in root.findall('x:url', ns):
stats['total_urls'] += 1
# Extract Publication Date
pub_date_node = url.find('n:news/n:publication_date', ns)
if pub_date_node is None:
errors.append(f"Missing publication date for {url.find('x:loc', ns).text}")
continue
pub_date = parse_date(pub_date_node.text)
age_hours = (now - pub_date).total_seconds() / 3600
# Check Freshness
if age_hours > MAX_ARTLE_AGE_HOURS:
errors.append(f"STALE: {url.find('x:loc', ns).text} is {age_hours:.1f} hours old.")
elif age_hours > ALERT_THRESHOLD_STALE:
warnings.append(f"AGING: {url.find('x:loc', ns).text} is {age_hours:.1f} hours old.")
return {
"errors": errors,
"warnings": warnings,
"stats": stats,
"status": "FAIL" if errors else "PASS"
}
# Mock Alert Function
def send_alerts(result):
if result['errors']:
print(f"🚨 CRITICAL ALERT: {len(result['errors'])} issues found.")
# Integration: Slack Webhook / SNS / PagerDuty
if result['warnings']:
print(f"⚠️ WARNING: {len(result['warnings'])} items aging out soon.")
Do not alert on every single stale article (alert fatigue). Use a Health Score approach.
Alert Type A: Pipeline Stalled (Urgent)
Total URLs in sitemap is 0 OR Last-Modified header of the file is > 2 hours old.Alert Type B: Stale Content (Warning)
Count(Age > 48h) > 10% of total sitemap size.To visualize the "TTL" (Time To Live) effectively, expose these metrics to Prometheus, Datadog, or CloudWatch:
| Metric Name | Type | Description |
|---|---|---|
sitemap_total_urls | Gauge | Current size of the news sitemap. |
sitemap_oldest_article_age | Gauge | Age of the oldest article in hours. |
sitemap_stale_url_count | Gauge | Count of URLs violating the 48h rule. |
sitemap_parse_status | Gauge | 1 for Success, 0 for Fail. |
Dashboard View:
sitemap_oldest_article_age. Ideally, this should look like a sawtooth wave (rising as articles age, then dropping when the sitemap flushes old articles).
For a robust, low-maintenance solution, deploy this as an AWS Lambda with a CloudWatch Event (EventBridge) trigger.