30 Mins

2. Data Extraction Patterns

Core Extraction Strategies: Full vs. Incremental

Full Load vs. Incremental Load

In data engineering, the extraction phase serves as the foundation for the entire pipeline. A full load pattern involves extracting the entire dataset from the source system to the target destination, which is simple but fails to scale as data volume $V$ grows linearly over time. For massive production databases, this approach is often unsustainable due to source system latency and resource contention.

Incremental loading, or delta loading, focuses on processing only the data that has changed since the last successful extraction. This is typically implemented via a high-watermark pattern, where a timestamp or an auto-incrementing integer key tracks the last processed record. The efficiency gains are significant, as we only move the subset of data $\Delta D$ representing the change, reducing the pipeline runtime by a factor proportional to the total dataset size.

Operator Note: Always ensure your watermark column is properly indexed in the source database to prevent full table scans during the extraction.
SQL
-- High-Watermark Incremental Query
-- Assuming a table 'orders' with 'updated_at' column
-- This query fetches records modified since the last successful pipeline run

SELECT id, customer_id, total_amount, updated_at
FROM orders
WHERE updated_at > (SELECT last_sync_time FROM pipeline_metadata WHERE table_name = 'orders');

Advanced Change Data Capture (CDC)

Database Log Replication

Change Data Capture (CDC) moves beyond simple query-based watermarks by reading the database's transaction log (e.g., binlog in MySQL or WAL in PostgreSQL). This allows for capturing deletes, which standard watermark approaches often ignore. By tailing logs, the ETL system operates asynchronously, minimizing the performance impact on the operational source database.

Implementing log-based CDC provides an audit-perfect stream of events, including 'before' and 'after' images of data rows. This is critical for systems requiring high-fidelity replication where the sequence of operations matters. Tools like Debezium leverage these native database features to convert raw log events into formatted messages for streaming platforms like Apache Kafka.

Operator Note: Log-based CDC can significantly increase storage usage on the source database because logs must be retained longer for the extractor to process them.
Python 3
# Conceptual CDC Event Handler using a log-tailing pattern
import json

def process_cdc_event(log_entry):
    # Simulate parsing a database transaction log event
    change = json.loads(log_entry)
    if change['op'] == 'u':
        # Process Update: Only applying changes to the warehouse
        update_warehouse(change['after']['id'], change['after']['data'])
    elif change['op'] == 'd':
        # Process Delete: Hard or soft delete in destination
        delete_from_warehouse(change['before']['id'])

# process_cdc_event(raw_event_stream)

API Resilience and Authentication

Handling Rate Limits and Paging

API-based extraction requires robust logic to handle transient failures and service limitations. Most modern REST APIs employ rate limiting (e.g., 429 Too Many Requests) and paginated responses to manage server load. A mature architecture implements an exponential backoff strategy, which calculates a wait time $t = initial\_delay \times 2^{n}$ to ensure the system gracefully recovers when hitting threshold limits.

Token management is equally vital. When dealing with OAuth2, extraction services must proactively monitor the 'expires_in' field of the access token. Rather than waiting for a 401 Unauthorized response, a best practice is to trigger a token refresh if the current time is within a safe buffer of the expiration timestamp, ensuring the pipeline remains uninterrupted during extended batch processes.

Operator Note: Always log the 'X-RateLimit-Reset' header provided by APIs to dynamically adjust your extraction schedule.
Python 3
import time
import requests

def fetch_with_retry(url, headers):
    # Simple backoff logic for rate limits
    for attempt in range(3):
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.json()
        elif response.status_code == 429:
            time.sleep(2 ** attempt) # Exponential backoff
        else:
            raise Exception("Extraction failed")

Knowledge Check

Ready to test your understanding of 2. Data Extraction Patterns?

Back