Monitoring Websites for Changes at Scale

Matt George

Fractional CTO · Founder of Injuria.ai

Detecting when a website changes is a foundational capability for competitive analysis, data intelligence, and compliance monitoring. A system that tracks price changes on an e-commerce site, monitors regulatory updates on a government portal, or verifies content on a partner's page is performing change detection. While a simple script can check a single page, building a system to monitor thousands or millions of pages reliably requires a thoughtful approach to architecture, state management, and execution. This is a problem of scaling a process that is simple in the singular but complex in the aggregate.

The core of any web change monitoring system is a simple, four-stage loop: fetch, parse, compare, and notify. Understanding this loop is the first step. Scaling it is the primary engineering challenge. This involves moving from a single process to a distributed system that can handle network failures, anti-bot countermeasures, and the sheer volume of data and requests required.

The Core Mechanism: Fetch, Parse, Compare, Notify

At its heart, every change monitoring system performs the same fundamental sequence of operations on a recurring schedule. The sophistication lies in how each step is implemented and managed at scale.

Fetch

The first step is to retrieve the content of the web page. This is almost always done by making an HTTP GET request[1] to the target URL. The response is typically a block of text, usually HTML[2]. The fetcher must act like a standard web browser to a certain degree, sending appropriate HTTP headers. The User-Agent header is particularly important, as it identifies the client to the server. While some systems use a generic agent like curl, a more considerate or stealthy system might identify itself with a custom agent or mimic a popular browser. Respecting the Robot Exclusion Standard[3] by checking the robots.txt file is a common practice for ethical crawlers.

Parse

Raw HTML is a stream of characters. To be useful, it must be parsed into a structured format. The universal standard for representing a document's structure is the Document Object Model (DOM)[4], a tree-like structure where each node represents a part of the document. Libraries like lxml or BeautifulSoup in Python, or Cheerio in Node.js, are designed to parse potentially malformed HTML and provide an API to navigate this tree. The goal of parsing is to make the content addressable. Instead of dealing with a wall of text, you can now ask for specific elements, like "the <div> with an id of 'price'".

Compare

This is the crucial step where a change is actually detected. The most naive approach is to compute a cryptographic hash (like SHA-256) of the entire fetched page and compare it to the hash from the previous check. This method is simple but extremely sensitive. A change in a timestamp, a session ID, or an advertisement would trigger a false positive. A more robust system compares specific, meaningful parts of the page.

This is achieved by targeting elements using selectors. Both CSS selectors[5] and XPath[6] are query languages designed to select nodes from an XML or HTML document. For instance, a CSS selector like #main-content .product-price can precisely target a product's price, ignoring everything else on the page. The system stores the content of this selected element. On the next check, it fetches the page, selects the same element, and compares the new content to the stored content. If they differ, a change has occurred.

Notify

Once a significant change is confirmed, the system must act. This action, or notification, can take many forms. It could be sending an email to a user, posting a message to a Slack channel, or calling a webhook to trigger another automated process. In more sophisticated systems, the change data (what changed, from what, to what) is pushed into a message queue like RabbitMQ[7] or AWS Simple Queue Service (SQS)[8]. This decouples the detection system from the action system, allowing for more flexible and scalable architectures. For example, one consumer might log the change to a database, while another triggers a real-time pricing alert.

A Concrete Example: Tracking a Product Price

Let's make this concrete with a Python example. This script will use the requests library to fetch a page and BeautifulSoup to parse it. It simulates a persistent store with a simple dictionary to hold the last seen price. In a real system, this would be a database or a key-value store.

import requests
from bs4 import BeautifulSoup
import hashlib

# In a real application, this would be a database (e.g., Redis, PostgreSQL).
STATE_STORAGE = {}

def check_product_price(url, selector):
 """ 
 Fetches a URL, extracts content from a CSS selector, and checks for changes.
 """
 try:
 headers = {
 'User-Agent': 'MyChangeMonitor/1.0 (https://mybot.example.com)'
 }
 response = requests.get(url, headers=headers, timeout=10)
 response.raise_for_status() # Raises an exception for bad status codes (4xx or 5xx)

 soup = BeautifulSoup(response.text, 'html.parser')
 price_element = soup.select_one(selector)

 if not price_element:
 print(f"Selector '{selector}' not found on {url}")
 return

 current_price_text = price_element.get_text(strip=True)
 
 # Use a hash of the URL as a unique key for storage.
 url_key = hashlib.md5(url.encode()).hexdigest()

 last_price_text = STATE_STORAGE.get(url_key)

 print(f"Checking {url}... Current price: {current_price_text}")

 if last_price_text and last_price_text != current_price_text:
 print(f"!!! CHANGE DETECTED on {url} !!!")
 print(f" Old price: {last_price_text}")
 print(f" New price: {current_price_text}")
 # Here you would trigger a notification (email, webhook, etc.)
 
 # Update the state for the next check.
 STATE_STORAGE[url_key] = current_price_text

 except requests.exceptions.RequestException as e:
 print(f"Could not fetch {url}: {e}")

# --- Simulation ---
# Imagine this function is called by a scheduler (e.g., cron, Celery) periodically.

# A mock HTML page for demonstration.
# In a real scenario, you would find the correct selector by inspecting the live website.
# For this example, we'll pretend 'https://example.com/product/123' has this selector.

if __name__ == '__main__':
 # This is a mock server response; we won't actually make a request.
 # We'll inject the logic directly for the example.
 
 # First check: The price is $99.99
 print("--- First Check ---")
 STATE_STORAGE['mock_key'] = None # Reset state
 price_text = "$99.99"
 last_price = STATE_STORAGE.get('mock_key')
 if last_price != price_text:
 STATE_STORAGE['mock_key'] = price_text
 print(f"Initial price set to: {price_text}")

 # Second check: Price is the same.
 print("\n--- Second Check ---")
 price_text = "$99.99"
 last_price = STATE_STORAGE.get('mock_key')
 if last_price and last_price != price_text:
 print("Change detected!")
 else:
 print("No change detected.")

 # Third check: The price has changed to $89.99
 print("\n--- Third Check ---")
 price_text = "$89.99"
 last_price = STATE_STORAGE.get('mock_key')
 if last_price and last_price != price_text:
 print(f"!!! CHANGE DETECTED !!!")
 print(f" Old price: {last_price}")
 print(f" New price: {price_text}")
 STATE_STORAGE['mock_key'] = price_text
 else:
 print("No change detected.")

This simple script illustrates the logic but hides the complexities that arise with scale.

Scaling the System: From Cron Job to Distributed Architecture

Running the above script in a cron[9] job works for a handful of URLs. Monitoring thousands or millions of pages at varying frequencies requires a distributed system.

Scheduling and Orchestration

Cron is not a scalable scheduler. It has no built-in retry logic, no easy way to manage concurrency, and poor visibility into failures. A large-scale system uses a task queue or workflow orchestrator. A task queue like Celery[10] is excellent for managing a high volume of independent fetch jobs. A workflow orchestrator like Apache Airflow[11] is better for complex, multi-step processes. These tools provide parallelism, automated retries, error handling, and a centralized dashboard for monitoring the health of the entire system.

Execution Environment

A single machine can only make so many concurrent HTTP requests. A scalable system distributes the fetching workload across a fleet of machines. Serverless compute platforms like AWS Lambda[12] or Google Cloud Functions[13] are a natural fit. Each URL check can be a separate, stateless function invocation. This model offers immense parallelism and a pay-per-use cost structure. For more complex jobs, such as those requiring a headless browser, container orchestration systems like Kubernetes[14] provide the flexibility to run and scale resource-intensive applications.

Proxy Management and Identity

Aggressively fetching from a single IP address is the fastest way to get blocked. Websites employ rate limiting and anti-bot systems to protect their infrastructure. To operate at scale, a monitoring system must distribute its requests across many different IP addresses using proxies. These proxies can be from data centers or, for harder targets, residential or mobile networks. Effective proxy management involves rotating IPs, handling proxy failures, and matching proxy geography to the target site's audience. Beyond IP addresses, systems must also manage their identity by rotating User-Agent strings[15], managing cookies, and maintaining sessions to appear as a legitimate user.

Data Storage and State Management

Storing the "last seen" state for millions of pages requires a fast and scalable storage layer. A simple file or a single SQL database will not suffice. A common pattern is to use a high-performance key-value store like Redis[16] to store the current state (e.g., URL_hash -> content_hash). Redis provides millisecond latency for the frequent read/write operations needed during the comparison step. For historical data and metadata about the checks (timestamps, success/failure status), a more traditional relational database like PostgreSQL[17] is often used. The full HTML content of each fetched page, if needed for auditing or deeper analysis, is best stored in a cheaper object storage service like Amazon S3[18] or Google Cloud Storage.

The Nuances of Change Detection

Detecting that bits have flipped is easy. Understanding if the change matters is hard.

Defining "Significant" Change

Modern web pages are filled with dynamic, non-essential content: rotating banner ads, personalized recommendations, view counters, and security tokens. A naive hash-based comparison will generate constant noise. A robust system must filter this noise to find significant changes.

Several techniques help:

  1. Targeted Selection: As discussed, using specific CSS or XPath selectors is the primary method for isolating important content.
  2. Noise Removal: Before comparison, the system can programmatically remove known noise sources. This includes stripping out <script> and <style> tags, comments, and elements matching a predefined list of "ignore" selectors (e.g., #ads, .timestamp).
  3. Text-Only Comparison: For many use cases, only the visible text matters. By extracting just the text content of a selected element or the entire page and comparing that, changes to HTML attributes or structure that do not affect the text are ignored.
  4. Change Quantification: Instead of a binary changed/not-changed result, one can measure the degree of change. Algorithms like the Levenshtein distance[19] calculate the number of edits needed to transform one string into another, providing a quantitative score for the difference.

Handling JavaScript-Rendered Content

Many modern websites are single-page applications (SPAs) built with frameworks like React, Angular, or Vue. The initial HTML downloaded from the server is often just a minimal skeleton. The actual content is loaded and rendered dynamically in the browser using JavaScript and AJAX[20]. A simple GET request will not see this content.

To handle these sites, the monitoring system must use a headless browser. A headless browser is a real web browser, like Chromium[21], running without a graphical user interface. Tools like Puppeteer[22] (from Google) and Playwright[23] (from Microsoft) provide APIs to control these browsers programmatically. The monitoring system can instruct the browser to navigate to a URL, wait for the JavaScript to execute and render the page, and then extract the final HTML. This approach is powerful but comes at a significant cost. A headless browser consumes orders of magnitude more CPU, memory, and time per page compared to a simple HTTP request, which has major implications for the cost and throughput of the entire system.

Legal and Ethical Considerations

A technical leader must weigh the legal and ethical dimensions of web monitoring.

  • robots.txt: This file expresses a site owner's wishes about which parts of their site automated crawlers should not access. The protocol is voluntary and not technically enforced. While there is no universal legal requirement to obey it, most large-scale, legitimate crawlers (like Google's) do. Ignoring it can be seen as hostile and may increase the risk of being blocked or facing legal challenges.
  • Terms of Service (ToS): Many websites include clauses in their ToS that prohibit automated access or scraping. The enforceability of these terms is a complex legal question that varies by jurisdiction. The landmark hiQ Labs v. LinkedIn case suggested that scraping publicly accessible data may not violate the Computer Fraud and Abuse Act (CFAA)[24], but the legal landscape is still evolving. Violating a ToS is a business risk that requires careful consideration.
  • Being a Good Citizen: A well-behaved monitoring system should not harm the target website. This means throttling request rates to avoid overwhelming the server, identifying the bot clearly via its User-Agent, and stopping immediately if the system detects signs of distress from the server (like 5xx error codes).

Decision Lens: Building vs. Buying

For a business that needs web change data, the fundamental strategic decision is whether to build a custom system or use a commercial Software-as-a-Service (SaaS) provider.

When to Build

Building a system in-house is a major engineering investment. It makes sense under specific conditions:

  • Core Business Function: If web data acquisition and change detection is a central and strategic part of your business model, owning the technology can be a competitive advantage.
  • Unique Requirements: You have highly specialized needs, such as complex post-processing logic or integration with proprietary internal systems, that off-the-shelf tools cannot meet.
  • Extreme Scale: At a truly massive scale (billions of pages per month), the per-unit cost of an in-house system might eventually become lower than a SaaS subscription, though the total cost of ownership (including engineering salaries) is very high.
  • Available Talent: You have, or can hire, an engineering team with expertise in distributed systems, network protocols, and the cat-and-mouse game of anti-bot circumvention.

When to Buy

For most organizations, using a specialized service is the more pragmatic and cost-effective choice.

  • Focus on Core Product: Your engineering team's time is better spent on your core product rather than reinventing the complex infrastructure for web scraping.
  • Avoid Operational Overhead: You want to outsource the significant operational burden of managing proxy networks, handling different types of blocks, and running headless browsers at scale.
  • Speed to Market: You need change data now, not in the six to twelve months it might take to build a reliable system from scratch.
  • Moderate Scale: Your needs, while important, do not justify the cost of a dedicated engineering team for this specific problem.

The cost of building is not just infrastructure. It is the ongoing salary of engineers who must constantly adapt the system as target websites change their layouts and anti-bot technologies become more sophisticated. This is a perpetual maintenance cost that is often underestimated at the outset.

Sources (24)
  1. RFC 9112: HTTP/1.1
  2. HTML Standard
  3. The Robot Exclusion Standard
  4. DOM Standard
  5. Selectors Level 4
  6. XML Path Language (XPath) 3.1
  7. RabbitMQ
  8. Amazon Simple Queue Service (SQS)
  9. cron
  10. Celery
  11. Apache Airflow
  12. AWS Lambda
  13. Google Cloud Functions
  14. Kubernetes
  15. User-Agent - HTTP | MDN
  16. Redis
  17. PostgreSQL
  18. Amazon S3
  19. Levenshtein distance
  20. AJAX - Web APIs | MDN
  21. The Chromium Projects
  22. Puppeteer
  23. Playwright
  24. Computer Fraud and Abuse Act

Recommended reading