This is a comprehensive request for building an ETL pipeline with advanced features. I'll provide a detailed implementation using both Airflow and Prefect, with a focus on:
- Backfilling past dates
- Dead letter queue (DLQ) for schema validation failures
- S3 storage for failed records
- Robust error handling
- Batch processing with continuation after failures
Let me create a complete solution with:
- Data models and validation
- DLQ implementation
- ETL pipeline logic
- Both Airflow and Prefect versions
- Comprehensive examples
- Testing utilities
I'll make it production-ready with proper logging, error handling, and configuration management.
Production-Ready ETL Pipeline with Backfilling & Dead Letter Queue
I'll provide a comprehensive implementation with both Airflow and Prefect, including schema validation, DLQ handling, and S3 integration.
1. Core Data Models & Validation
# src/models.py
from dataclasses import dataclass, asdict, field
from datetime import datetime
from typing import Any, Dict, List, Optional
from enum import Enum
import json
from abc import ABC, abstractmethod
import pandas as pd
from pydantic import BaseModel, ValidationError, field_validator
class RecordStatus(str, Enum):
"""Status of records in the pipeline."""
VALID = "valid"
INVALID = "invalid"
PROCESSED = "processed"
FAILED = "failed"
class DataSchema(BaseModel):
"""Schema definition for data validation."""
user_id: int
name: str
email: str
age: int
signup_date: datetime
revenue: float
is_active: bool
@field_validator('age')
@classmethod
def validate_age(cls, v):
if not 0 <= v <= 150:
raise ValueError('Age must be between 0 and 150')
return v
@field_validator('email')
@classmethod
def validate_email(cls, v):
if '@' not in v:
raise ValueError('Invalid email format')
return v
@dataclass
class ValidationResult:
"""Result of record validation."""
is_valid: bool
record: Dict[str, Any]
errors: List[str] = field(default_factory=list)
original_record: Dict[str, Any] = field(default_factory=dict)
timestamp: datetime = field(default_factory=datetime.utcnow)
def to_dict(self) -> Dict[str, Any]:
return {
'is_valid': self.is_valid,
'record': self.record,
'errors': self.errors,
'original_record': self.original_record,
'timestamp': self.timestamp.isoformat()
}
@dataclass
class BatchResult:
"""Result of batch processing."""
total_records: int
valid_records: int
invalid_records: int
processed_records: int
failed_records: int
dlq_records: List[ValidationResult] = field(default_factory=list)
errors: List[str] = field(default_factory=list)
processing_time_seconds: float = 0.0
batch_id: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
'total_records': self.total_records,
'valid_records': self.valid_records,
'invalid_records': self.invalid_records,
'processed_records': self.processed_records,
'failed_records': self.failed_records,
'dlq_records_count': len(self.dlq_records),
'errors': self.errors,
'processing_time_seconds': self.processing_time_seconds,
'batch_id': self.batch_id
}
class Validator(ABC):
"""Abstract validator for different data sources."""
@abstractmethod
def validate(self, record: Dict[str, Any]) -> ValidationResult:
"""Validate a single record."""
pass
@abstractmethod
def validate_batch(self, records: List[Dict[str, Any]]) -> tuple:
"""Validate a batch of records. Returns (valid, invalid)."""
pass
class PydanticValidator(Validator):
"""Validator using Pydantic models."""
def __init__(self, schema_class: type):
self.schema_class = schema_class
def validate(self, record: Dict[str, Any]) -> ValidationResult:
"""Validate a single record against schema."""
try:
validated = self.schema_class(**record)
return ValidationResult(
is_valid=True,
record=validated.model_dump(),
original_record=record
)
except ValidationError as e:
errors = [
f"{error['loc'][0]}: {error['msg']}"
for error in e.errors()
]
return ValidationResult(
is_valid=False,
record=record,
original_record=record,
errors=errors
)
def validate_batch(self, records: List[Dict[str, Any]]) -> tuple:
"""Validate batch and separate valid/invalid records."""
valid_records = []
invalid_records = []
for record in records:
result = self.validate(record)
if result.is_valid:
valid_records.append(result.record)
else:
invalid_records.append(result)
return valid_records, invalid_records
2. Dead Letter Queue & S3 Integration
# src/dlq.py
import logging
import json
from datetime import datetime
from typing import List, Dict, Any
from io import BytesIO
import gzip
import boto3
from botocore.exceptions import ClientError
from models import ValidationResult, BatchResult
logger = logging.getLogger(__name__)
class DeadLetterQueue:
"""Manages failed records in S3."""
def __init__(
self,
bucket_name: str,
prefix: str = "dlq",
aws_profile: Optional[str] = None,
region: str = "us-east-1"
):
self.bucket_name = bucket_name
self.prefix = prefix
if aws_profile:
session = boto3.Session(profile_name=aws_profile)
self.s3_client = session.client('s3', region_name=region)
else:
self.s3_client = boto3.client('s3', region_name=region)
def save_invalid_record(
self,
validation_result: ValidationResult,
batch_id: str,
date_partition: datetime
) -> str:
"""Save a single invalid record to DLQ."""
key = self._generate_key(batch_id, date_partition, "single")
data = {
'record': validation_result.original_record,
'validation_results': validation_result.to_dict(),
'saved_at': datetime.utcnow().isoformat()
}
return self._upload_to_s3(key, data)
def save_batch(
self,
invalid_records: List[ValidationResult],
batch_id: str,
date_partition: datetime
) -> str:
"""Save batch of invalid records to DLQ."""
if not invalid_records:
return None
key = self._generate_key(batch_id, date_partition, "batch")
data = {
'batch_id': batch_id,
'record_count': len(invalid_records),
'records': [r.to_dict() for r in invalid_records],
'saved_at': datetime.utcnow().isoformat()
}
return self._upload_to_s3(key, data)
def save_processing_failure(
self,
records: List[Dict[str, Any]],
error: str,
batch_id: str,
date_partition: datetime
) -> str:
"""Save records that failed during processing."""
key = self._generate_key(batch_id, date_partition, "processing-failure")
data = {
'batch_id': batch_id,
'record_count': len(records),
'error': str(error),
'records': records,
'failed_at': datetime.utcnow().isoformat()
}
return self._upload_to_s3(key, data)
def save_batch_metadata(
self,
batch_result: BatchResult,
date_partition: datetime
) -> str:
"""Save batch processing metadata."""
key = self._generate_key(
batch_result.batch_id,
date_partition,
"metadata"
)
data = {
**batch_result.to_dict(),
'saved_at': datetime.utcnow().isoformat()
}
return self._upload_to_s3(key, data)
def _generate_key(
self,
batch_id: str,
date_partition: datetime,
record_type: str
) -> str:
"""Generate S3 key with date partitioning."""
return (
f"{self.prefix}/"
f"year={date_partition.year}/"
f"month={date_partition.month:02d}/"
f"day={date_partition.day:02d}/"
f"{batch_id}_{record_type}_{datetime.utcnow().timestamp()}.json.gz"
)
def _upload_to_s3(self, key: str, data: Dict[str, Any]) -> str:
"""Upload data to S3 with gzip compression."""
try:
json_data = json.dumps(data, default=str)
compressed = self._compress_data(json_data.encode('utf-8'))
self.s3_client.put_object(
Bucket=self.bucket_name,
Key=key,
Body=compressed,
ContentType='application/json',
ContentEncoding='gzip'
)
logger.info(f"Uploaded DLQ record to s3://{self.bucket_name}/{key}")
return f"s3://{self.bucket_name}/{key}"
except ClientError as e:
logger.error(
f"Failed to upload DLQ record to S3: {e}",
extra={'key': key, 'error': str(e)}
)
raise
@staticmethod
def _compress_data(data: bytes) -> bytes:
"""Compress data using gzip."""
with BytesIO() as buf:
with gzip.GzipFile(fileobj=buf, mode='wb') as gz_file:
gz_file.write(data)
return buf.getvalue()
def retrieve_dlq_records(
self,
batch_id: str,
date_partition: datetime,
record_type: str = "batch"
) -> List[Dict[str, Any]]:
"""Retrieve records from DLQ for inspection."""
key = self._generate_key(batch_id, date_partition, record_type)
try:
response = self.s3_client.get_object(
Bucket=self.bucket_name,
Key=key
)
compressed_data = response['Body'].read()
decompressed = gzip.decompress(compressed_data)
data = json.loads(decompressed.decode('utf-8'))
return data
except ClientError as e:
logger.error(
f"Failed to retrieve DLQ records: {e}",
extra={'key': key}
)
return []
def query_dlq_for_date(
self,
date_partition: datetime
) -> List[Dict[str, Any]]:
"""Query all DLQ records for a specific date."""
prefix = (
f"{self.prefix}/"
f"year={date_partition.year}/"
f"month={date_partition.month:02d}/"
f"day={date_partition.day:02d}/"
)
try:
response = self.s3_client.list_objects_v2(
Bucket=self.bucket_name,
Prefix=prefix
)
keys = [obj['Key'] for obj in response.get('Contents', [])]
all_records = []
for key in keys:
record = self._get_object(key)
if record:
all_records.append(record)
logger.info(
f"Retrieved {len(all_records)} DLQ entries for {date_partition.date()}"
)
return all_records
except ClientError as e:
logger.error(f"Failed to query DLQ: {e}")
return []
def _get_object(self, key: str) -> Dict[str, Any]:
"""Get a single object from S3."""
try:
response = self.s3_client.get_object(
Bucket=self.bucket_name,
Key=key
)
compressed = response['Body'].read()
decompressed = gzip.decompress(compressed)
return json.loads(decompressed.decode('utf-8'))
except Exception as e:
logger.error(f"Failed to get object {key}: {e}")
return None
3. ETL Pipeline Core
# src/etl_pipeline.py
import logging
import time
import uuid
from datetime import datetime, timedelta
from typing import List, Dict, Any, Callable, Optional
from abc import ABC, abstractmethod
import pandas as pd
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
from models import DataSchema, Validator, PydanticValidator, BatchResult, ValidationResult
from dlq import DeadLetterQueue
logger = logging.getLogger(__name__)
class DataSource(ABC):
"""Abstract data source."""
@abstractmethod
def fetch_data(self, date: datetime, **kwargs) -> List[Dict[str, Any]]:
"""Fetch data for a specific date."""
pass
class CSVDataSource(DataSource):
"""CSV file data source."""
def __init__(self, file_path: str):
self.file_path = file_path
def fetch_data(self, date: datetime, **kwargs) -> List[Dict[str, Any]]:
"""Fetch data from CSV."""
try:
df = pd.read_csv(self.file_path)
records = df.to_dict('records')
logger.info(f"Fetched {len(records)} records from {self.file_path}")
return records
except Exception as e:
logger.error(f"Failed to fetch data from CSV: {e}")
return []
class DatabaseDataSource(DataSource):
"""Database data source for backfilling."""
def __init__(self, connection_string: str, query_template: str):
self.engine = create_engine(connection_string)
self.query_template = query_template
def fetch_data(self, date: datetime, **kwargs) -> List[Dict[str, Any]]:
"""Fetch data from database for a specific date."""
try:
query = self.query_template.format(
date=date.date(),
**kwargs
)
with self.engine.connect() as conn:
result = conn.execute(text(query))
columns = result.keys()
records = [
dict(zip(columns, row))
for row in result.fetchall()
]
logger.info(
f"Fetched {len(records)} records from database for {date.date()}"
)
return records
except SQLAlchemyError as e:
logger.error(f"Database error: {e}")
return []
class DataDestination(ABC):
"""Abstract data destination."""
@abstractmethod
def write_data(
self,
records: List[Dict[str, Any]],
batch_id: str,
date: datetime
) -> bool:
"""Write processed data to destination."""
pass
class DatabaseDestination(DataDestination):
"""Write to database."""
def __init__(self, connection_string: str, table_name: str, if_exists: str = "append"):
self.engine = create_engine(connection_string)
self.table_name = table_name
self.if_exists = if_exists
def write_data(
self,
records: List[Dict[str, Any]],
batch_id: str,
date: datetime
) -> bool:
"""Write records to database."""
if not records:
logger.info("No records to write")
return True
try:
df = pd.DataFrame(records)
df['batch_id'] = batch_id
df['processed_date'] = datetime.utcnow()
df.to_sql(
self.table_name,
self.engine,
if_exists=self.if_exists,
index=False
)
logger.info(
f"Successfully wrote {len(records)} records to {self.table_name}"
)
return True
except Exception as e:
logger.error(f"Failed to write data to database: {e}")
return False
class S3Destination(DataDestination):
"""Write to S3."""
def __init__(self, bucket_name: str, prefix: str, aws_profile: Optional[str] = None):
import boto3
self.bucket_name = bucket_name
self.prefix = prefix
if aws_profile:
session = boto3.Session(profile_name=aws_profile)
self.s3_client = session.client('s3')
else:
self.s3_client = boto3.client('s3')
def write_data(
self,
records: List[Dict[str, Any]],
batch_id: str,
date: datetime
) -> bool:
"""Write records to S3."""
if not records:
logger.info("No records to write")
return True
try:
key = (
f"{self.prefix}/"
f"year={date.year}/"
f"month={date.month:02d}/"
f"day={date.day:02d}/"
f"{batch_id}.parquet"
)
df = pd.DataFrame(records)
df['batch_id'] = batch_id
df['processed_date'] = datetime.utcnow()
parquet_buffer = df.to_parquet(index=False)
self.s3_client.put_object(
Bucket=self.bucket_name,
Key=key,
Body=parquet_buffer
)
logger.info(
f"Successfully wrote {len(records)} records to s3://{self.bucket_name}/{key}"
)
return True
except Exception as e:
logger.error(f"Failed to write data to S3: {e}")
return False
class ETLPipeline:
"""Main ETL pipeline with backfilling and DLQ support."""
def __init__(
self,
source: DataSource,
destination: DataDestination,
validator: Validator,
dlq: DeadLetterQueue
):
self.source = source
self.destination = destination
self.validator = validator
self.dlq = dlq
self.transformers: List[Callable] = []
def add_transformer(self, transformer: Callable) -> 'ETLPipeline':
"""Add a transformation function to the pipeline."""
self.transformers.append(transformer)
return self
def process_batch(
self,
records: List[Dict[str, Any]],
batch_id: str,
date: datetime
) -> BatchResult:
"""Process a batch of records."""
start_time = time.time()
batch_result = BatchResult(
total_records=len(records),
batch_id=batch_id
)
# Step 1: Validate
logger.info(f"Validating {len(records)} records for batch {batch_id}")
valid_records, invalid_records = self.validator.validate_batch(records)
batch_result.valid_records = len(valid_records)
batch_result.invalid_records = len(invalid_records)
batch_result.dlq_records = invalid_records
# Save invalid records to DLQ
if invalid_records:
try:
dlq_key = self.dlq.save_batch(invalid_records, batch_id, date)
logger.info(f"Saved {len(invalid_records)} invalid records to DLQ: {dlq_key}")
except Exception as e:
logger.error(f"Failed to save invalid records to DLQ: {e}")
batch_result.errors.append(str(e))
# Step 2: Transform valid records
logger.info(f"Transforming {len(valid_records)} valid records")
try:
for transformer in self.transformers:
valid_records = [transformer(record) for record in valid_records]
except Exception as e:
logger.error(f"Transformation failed: {e}")
batch_result.errors.append(str(e))
# Save records that failed transformation
try:
self.dlq.save_processing_failure(
valid_records,
e,
batch_id,
date
)
except Exception as dlq_error:
logger.error(f"Failed to save processing failure to DLQ: {dlq_error}")
# Continue with remaining records by returning early
batch_result.valid_records = 0
batch_result.failed_records = len(valid_records)
# Step 3: Write to destination
if valid_records:
logger.info(f"Writing {len(valid_records)} records to destination")
try:
if self.destination.write_data(valid_records, batch_id, date):
batch_result.processed_records = len(valid_records)
else:
batch_result.failed_records = len(valid_records)
try:
self.dlq.save_processing_failure(
valid_records,
"Destination write failed",
batch_id,
date
)
except Exception as dlq_error:
logger.error(f"Failed to save to DLQ: {dlq_error}")
except Exception as e:
logger.error(f"Failed to write to destination: {e}")
batch_result.errors.append(str(e))
batch_result.failed_records = len(valid_records)
# Save metadata
try:
self.dlq.save_batch_metadata(batch_result, date)
except Exception as e:
logger.error(f"Failed to save batch metadata: {e}")
batch_result.processing_time_seconds = time.time() - start_time
return batch_result
def backfill(
self,
start_date: datetime,
end_date: datetime,
batch_size: int = 100,
**fetch_kwargs
) -> List[BatchResult]:
"""Backfill data for a date range."""
logger.info(f"Starting backfill from {start_date.date()} to {end_date.date()}")
results = []
current_date = start_date
while current_date <= end_date:
logger.info(f"Processing date: {current_date.date()}")
try:
# Fetch data for the date
records = self.source.fetch_data(current_date, **fetch_kwargs)
if not records:
logger.info(f"No records found for {current_date.date()}")
current_date += timedelta(days=1)
continue
# Process in batches
for i in range(0, len(records), batch_size):
batch = records[i:i + batch_size]
batch_id = f"{current_date.date()}_{uuid.uuid4().hex[:8]}"
result = self.process_batch(batch, batch_id, current_date)
results.append(result)
logger.info(
f"Batch {batch_id}: "
f"valid={result.valid_records}, "
f"invalid={result.invalid_records}, "
f"processed={result.processed_records}"
)
except Exception as e:
logger.error(f"Error processing {current_date.date()}: {e}")
results.append(BatchResult(
total_records=0,
errors=[str(e)],
batch_id=f"{current_date.date()}_error"
))
current_date += timedelta(days=1)
return results
def run_incremental(
self,
date: datetime,
batch_size: int = 100,
**fetch_kwargs
) -> List[BatchResult]:
"""Run incremental ETL for a single date."""
logger.info(f"Running incremental ETL for {date.date()}")
results = []
try:
records = self.source.fetch_data(date, **fetch_kwargs)
if not records:
logger.info(f"No records found for {date.date()}")
return results
# Process in batches
for i in range(0, len(records), batch_size):
batch = records[i:i + batch_size]
batch_id = f"{date.date()}_{uuid.uuid4().hex[:8]}"
result = self.process_batch(batch, batch_id, date)
results.append(result)
except Exception as e:
logger.error(f"Error in incremental run: {e}")
results.append(BatchResult(
total_records=0,
errors=[str(e)],
batch_id=f"{date.date()}_error"
))
return results
4. Airflow Implementation
# dags/etl_pipeline_dag.py
from datetime import datetime, timedelta
from typing import Dict, Any
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.operators.dummy import DummyOperator
from airflow.utils.task_group import TaskGroup
from airflow.models import Variable
from airflow.exceptions import AirflowException
import logging
from src.etl_pipeline import (
ETLPipeline,
DatabaseDataSource,
DatabaseDestination,
CSVDataSource,
S3Destination
)
from src.models import PydanticValidator, DataSchema
from src.dlq import DeadLetterQueue
logger = logging.getLogger(__name__)
# Configuration from Airflow Variables
DEFAULT_ARGS = {
'owner': 'data-engineering',
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': ['data-team@example.com'],
'email_on_failure': True,
'email_on_retry': False,
}
DAG_ID = 'etl_pipeline_backfill'
def get_pipeline(**context):
"""Initialize and return ETL pipeline."""
db_conn = Variable.get("DB_CONNECTION_STRING")
s3_bucket = Variable.get("S3_BUCKET_NAME")
aws_profile = Variable.get("AWS_PROFILE", default_var=None)
query_template = """
SELECT user_id, name, email, age, signup_date, revenue, is_active
FROM users
WHERE DATE(created_at) = '{date}'
"""
source = DatabaseDataSource(db_conn, query_template)
destination = S3Destination(s3_bucket, "processed_users", aws_profile)
validator = PydanticValidator(DataSchema)
dlq = DeadLetterQueue(s3_bucket, "dlq", aws_profile)
pipeline = ETLPipeline(source, destination, validator, dlq)
# Add transformers
pipeline.add_transformer(lambda r: {**r, 'name': r['name'].upper()})
pipeline.add_transformer(lambda r: {**r, 'email': r['email'].lower()})
return pipeline
def process_batch(**context):
"""Process a single batch of data."""
pipeline = get_pipeline(**context)
execution_date = context['execution_date']
results = pipeline.run_incremental(execution_date, batch_size=500)
if not results:
raise AirflowException("No results from pipeline")
# Store metrics in XCom
metrics = {
'total_records': sum(r.total_records for r in results),
'valid_records': sum(r.valid_records for r in results),
'invalid_records': sum(r.invalid_records for r in results),
'processed_records': sum(r.processed_records for r in results),
'dlq_count': sum(len(r.dlq_records) for r in results),
}
logger.info(f"Pipeline metrics: {metrics}")
context['task_instance'].xcom_push(key='metrics', value=metrics)
return metrics
def backfill_task(**context):
"""Backfill data for a date range."""
pipeline = get_pipeline(**context)
# Get backfill parameters from Airflow variables or DAG config
start_date_str = Variable.get("BACKFILL_START_DATE", "2024-01-01")
end_date_str = Variable.get("BACKFILL_END_DATE", "2024-01-31")
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
logger.info(f"Starting backfill from {start_date} to {end_date}")
results = pipeline.backfill(start_date, end_date, batch_size=500)
# Aggregate results
metrics = {
'total_batches': len(results),
'total_records': sum(r.total_records for r in results),
'total_valid': sum(r.valid_records for r in results),
'total_invalid': sum(r.invalid_records for r in results),
'total_processed': sum(r.processed_records for r in results),
'total_failed': sum(r.failed_records for r in results),
'total_dlq': sum(len(r.dlq_records) for r in results),
'errors': [e for r in results for e in r.errors],
'total_time_seconds': sum(r.processing_time_seconds for r in results),
}
logger.info(f"Backfill metrics: {metrics}")
context['task_instance'].xcom_push(key='backfill_metrics', value=metrics)
if metrics['errors']:
logger.warning(f"Backfill completed with {len(metrics['errors'])} errors")
return metrics
def validate_results(**context):
"""Validate ETL results."""
task_instance = context['task_instance']
metrics = task_instance.xcom_pull(task_ids='process_batch', key='metrics')
if not metrics:
raise AirflowException("No metrics found")
logger.info(f"Validating results: {metrics}")
failure_rate = (
metrics['invalid_records'] / metrics['total_records']
if metrics['total_records'] > 0 else 0
)
# Alert if failure rate is too high
if failure_rate > 0.1: # 10% threshold
raise AirflowException(
f"High invalid record rate: {failure_rate:.2%}. "
f"Check DLQ for details."
)
return metrics
def inspect_dlq_task(**context):
"""Retrieve and log DLQ records."""
execution_date = context['execution_date']
s3_bucket = Variable.get("S3_BUCKET_NAME")
aws_profile = Variable.get("AWS_PROFILE", default_var=None)
dlq = DeadLetterQueue(s3_bucket, "dlq", aws_profile)
dlq_records = dlq.query_dlq_for_date(execution_date)
if dlq_records:
logger.warning(
f"Found {len(dlq_records)} DLQ records for {execution_date.date()}"
)
for record in dlq_records[:5]: # Log first 5
logger.warning(f"DLQ Record: {record}")
context['task_instance'].xcom_push(key='dlq_records', value=dlq_records)
return len(dlq_records)
# DAG Definition
with DAG(
dag_id=DAG_ID,
description='ETL pipeline with backfilling and DLQ',
default_args=DEFAULT_ARGS,
schedule_interval='@daily',
start_date=datetime(2024, 1, 1),
catchup=True,
tags=['etl', 'data-pipeline'],
max_active_runs=2,
) as dag:
start = DummyOperator(task_id='start')
# Incremental processing
with TaskGroup('incremental_processing') as incremental_tg:
process = PythonOperator(
task_id='process_batch',
python_callable=process_batch,
provide_context=True,
)
validate = PythonOperator(
task_id='validate_results',
python_callable=validate_results,
provide_context=True,
)
inspect_dlq = PythonOperator(
task_id='inspect_dlq',
python_callable=inspect_dlq_task,
provide_context=True,
trigger_rule='none_failed_or_skipped',
)
process >> validate >> inspect_dlq
# Backfill processing (run with different trigger)
backfill = PythonOperator(
task_id='backfill_task',
python_callable=backfill_task,
provide_context=True,
trigger_rule='none_failed_or_skipped',
)
# Use this to trigger backfill on-demand:
# airflow dags trigger --arg='{"backfill": true}' etl_pipeline_backfill
end = DummyOperator(task_id='end', trigger_rule='none_failed_or_skipped')
start >> incremental_tg >> end
5. Prefect Implementation
# src/flows.py
from prefect import flow, task, get_run_context
from prefect.task_runs import wait_for_task_run
from typing import List, Dict, Any
from datetime import datetime, timedelta
import logging
from src.etl_pipeline import (
ETLPipeline,
DatabaseDataSource,
DatabaseDestination,
CSVDataSource,
S3Destination
)
from src.models import PydanticValidator, DataSchema, BatchResult
from src.dlq import DeadLetterQueue
logger = logging.getLogger(__name__)
@task(
name="Initialize Pipeline",
description="Set up ETL pipeline with validators and destinations"
)
def initialize_pipeline(
db_connection: str,
s3_bucket: str,
aws_profile: str = None
) -> ETLPipeline:
"""Initialize ETL pipeline."""
query_template = """
SELECT user_id, name, email, age, signup_date, revenue, is_active
FROM users
WHERE DATE(created_at) = '{date}'
"""
source = DatabaseDataSource(db_connection, query_template)
destination = S3Destination(s3_bucket, "processed_users", aws_profile)
validator = PydanticValidator(DataSchema)
dlq = DeadLetterQueue(s3_bucket, "dlq", aws_profile)
pipeline = ETLPipeline(source, destination, validator, dlq)
# Add transformers
pipeline.add_transformer(lambda r: {**r, 'name': r['name'].upper()})
pipeline.add_transformer(lambda r: {**r, 'email': r['email'].lower()})
logger.info("Pipeline initialized successfully")
return pipeline
@task(
name="Fetch Data",
description="Fetch data from source for a specific date",
retries=2,
retry_delay_seconds=60
)
def fetch_data_task(
pipeline: ETLPipeline,
execution_date: datetime
) -> List[Dict[str, Any]]:
"""Fetch data from source."""
records = pipeline.source.fetch_data(execution_date)
logger.info(f"Fetched {len(records)} records for {execution_date.date()}")
return records
@task(
name="Validate Records",
description="Validate records against schema"
)
def validate_records_task(
records: List[Dict[str, Any]],
validator
) -> tuple:
"""Validate records."""
valid_records, invalid_records = validator.validate_batch(records)
logger.info(
f"Validation complete: {len(valid_records)} valid, "
f"{len(invalid_records)} invalid"
)
return valid_records, invalid_records
@task(
name="Save Invalid Records to DLQ",
description="Save validation failures to DLQ"
)
def save_to_dlq_task(
dlq: DeadLetterQueue,
invalid_records: List,
batch_id: str,
execution_date: datetime
) -> str:
"""Save invalid records to DLQ."""
if invalid_records:
dlq_key = dlq.save_batch(invalid_records, batch_id, execution_date)
logger.info(
f"Saved {len(invalid_records)} records to DLQ: {dlq_key}"
)
return dlq_key
return None
@task(
name="Transform Records",
description="Apply transformations to valid records"
)
def transform_records_task(
records: List[Dict[str, Any]],
transformers: List
) -> List[Dict[str, Any]]:
"""Transform records."""
try:
for transformer in transformers:
records = [transformer(record) for record in records]
logger.info(f"Transformed {len(records)} records")
return records
except Exception as e:
logger.error(f"Transformation failed: {e}")
raise
@task(
name="Write to Destination",
description="Write processed records to destination"
)
def write_to_destination_task(
destination,
records: List[Dict[str, Any]],
batch_id: str,
execution_date: datetime
) -> bool:
"""Write records to destination."""
if not records:
logger.info("No records to write")
return True
success = destination.write_data(records, batch_id, execution_date)
if success:
logger.info(f"Successfully wrote {len(records)} records")
else:
logger.error("Failed to write records")
return success
@task(
name="Generate Metrics",
description="Generate pipeline metrics"
)
def generate_metrics_task(
total: int,
valid: int,
invalid: int,
processed: int,
failed: int
) -> Dict[str, Any]:
"""Generate pipeline metrics."""
metrics = {
'total_records': total,
'valid_records': valid,
'invalid_records': invalid,
'processed_records': processed,
'failed_records': failed,
'failure_rate': (invalid / total * 100) if total > 0 else 0,
'success_rate': (processed / total * 100) if total > 0 else 0,
}
logger.info(f"Pipeline Metrics: {metrics}")
return metrics
@flow(
name="ETL Incremental Flow",
description="Process data for a single date"
)
def etl_incremental_flow(
execution_date: datetime,
db_connection: str,
s3_bucket: str,
aws_profile: str = None,
batch_size: int = 500
) -> Dict[str, Any]:
"""Incremental ETL flow."""
import uuid
logger.info(f"Starting incremental ETL for {execution_date.date()}")
# Initialize
pipeline = initialize_pipeline(db_connection, s3_bucket, aws_profile)
# Fetch
records = fetch_data_task(pipeline, execution_date)
if not records:
logger.info("No records to process")
return {'status': 'no_data', 'records_processed': 0}
# Process in batches
total_valid = 0
total_invalid = 0
total_processed = 0
total_failed = 0
for i in range(0, len(records), batch_size):
batch = records[i:i + batch_size]
batch_id = f"{execution_date.date()}_{uuid.uuid4().hex[:8]}"
# Validate
valid_records, invalid_records = validate_records_task(
batch,
pipeline.validator
)
# Save to DLQ
if invalid_records:
save_to_dlq_task(
pipeline.dlq,
invalid_records,
batch_id,
execution_date
)
# Transform
if valid_records:
transformed = transform_records_task(
valid_records,
pipeline.transformers
)
# Write
success = write_to_destination_task(
pipeline.destination,
transformed,
batch_id,
execution_date
)
if success:
total_processed += len(transformed)
else:
total_failed += len(transformed)
total_valid += len(valid_records)
total_invalid += len(invalid_records)
# Generate metrics
metrics = generate_metrics_task(
total=len(records),
valid=total_valid,
invalid=total_invalid,
processed=total_processed,
failed=total_failed
)
return metrics
@flow(
name="ETL Backfill Flow",
description="Backfill data for a date range"
)
def etl_backfill_flow(
start_date: datetime,
end_date: datetime,
db_connection: str,
s3_bucket: str,
aws_profile: str = None,
batch_size: int = 500
) -> Dict[str, Any]:
"""Backfill ETL flow."""
logger.info(f"Starting backfill from {start_date.date()} to {end_date.date()}")
# Initialize
pipeline = initialize_pipeline(db_connection, s3_bucket, aws_profile)
# Prepare date range
current_date = start_date
all_results = []
while current_date <= end_date:
logger.info(f"Processing date: {current_date.date()}")
# Run incremental flow for each date
result = etl_incremental_flow(
execution_date=current_date,
db_connection=db_connection,
s3_bucket=s3_bucket,
aws_profile=aws_profile,
batch_size=batch_size
)
all_results.append(result)
current_date += timedelta(days=1)
# Aggregate results
total_records = sum(
r.get('total_records', 0) for r in all_results if r.get('status') != 'no_data'
)
total_processed = sum(
r.get('processed_records', 0) for r in all_results if r.get('status') != 'no_data'
)
summary = {
'backfill_start': start_date.isoformat(),
'backfill_end': end_date.isoformat(),
'total_days_processed': len(all_results),
'total_records': total_records,
'total_processed': total_processed,
'total_results': all_results,
}
logger.info(f"Backfill Summary: {summary}")
return summary
@flow(
name="ETL Pipeline with Error Handling",
description="Full ETL pipeline with comprehensive error handling"
)
def etl_with_error_handling_flow(
execution_date: datetime,
db_connection: str,
s3_bucket: str,
aws_profile: str = None
):
"""ETL flow with error handling and DLQ management."""
try:
result = etl_incremental_flow(
execution_date=execution_date,
db_connection=db_connection,
s3_bucket=s3_bucket,
aws_profile=aws_profile
)
# Check failure rate
failure_rate = result.get('failure_rate', 0)
if failure_rate > 10: # 10% threshold
logger.warning(
f"High failure rate: {failure_rate:.2f}%. "
f"Review DLQ records."
)
return result
except Exception as e:
logger.error(f"ETL flow failed: {e}")
raise
6. Testing Suite
# tests/test_etl_pipeline.py
import pytest
from datetime import datetime
from typing import List, Dict, Any
from src.models import DataSchema, PydanticValidator, ValidationResult
from src.etl_pipeline import (
ETLPipeline,
CSVDataSource,
S3Destination,
DatabaseDestination
)
from src.dlq import DeadLetterQueue
@pytest.fixture
def sample_records():
"""Sample data for testing."""
return [
{
'user_id': 1,
'name': 'John Doe',
'email': 'john@example.com',
'age': 30,
'signup_date': datetime(2024, 1, 1),
'revenue': 100.50,
'is_active': True
},
{
'user_id': 2,
'name': 'Jane Smith',
'email': 'jane@example.com',
'age': 25,
'signup_date': datetime(2024, 1, 2),
'revenue': 200.75,
'is_active': False
}
]
@pytest.fixture
def invalid_records():
"""Invalid sample data."""
return [
{
'user_id': 'invalid', # Should be int
'name': 'John',
'email': 'john@example.com',
'age': 30,
'signup_date': datetime(2024, 1, 1),
'revenue': 100.50,
'is_active': True
},
{
'user_id': 2,
'name': 'Jane',
'email': 'invalid-email', # Missing @
'age': 200, # Too old
'signup_date': datetime(2024, 1, 2),
'revenue': 200.75,
'is_active': False
}
]
@pytest.fixture
def validator():
"""Create validator."""
return PydanticValidator(DataSchema)
class TestValidator:
"""Test validation logic."""
def test_validate_valid_record(self, validator, sample_records):
"""Test validating a valid record."""
result = validator.validate(sample_records[0])
assert result.is_valid
assert len(result.errors) == 0
def test_validate_invalid_record(self, validator, invalid_records):
"""Test validating an invalid record."""
result = validator.validate(invalid_records[0])
assert not result.is_valid
assert len(result.errors) > 0
def test_validate_batch(self, validator, sample_records, invalid_records):
"""Test batch validation."""
records = sample_records + invalid_records
valid, invalid = validator.validate_batch(records)
assert len(valid) == 2
assert len(invalid) == 2
class TestDeadLetterQueue:
"""Test DLQ functionality."""
@pytest.mark.skip(reason="Requires AWS credentials")
def test_save_invalid_record(self, validator, invalid_records):
"""Test saving invalid record to DLQ."""
dlq = DeadLetterQueue('test-bucket', 'dlq')
result = validator.validate(invalid_records[0])
key = dlq.save_invalid_record(
result,
'batch_123',
datetime(2024, 1, 1)
)
assert key is not None
assert 'dlq' in key
@pytest.mark.skip(reason="Requires AWS credentials")
def test_save_batch_to_dlq(self, validator, invalid_records):
"""Test saving batch to DLQ."""
dlq = DeadLetterQueue('test-bucket', 'dlq')
_, invalid = validator.validate_batch(invalid_records)
key = dlq.save_batch(
invalid,
'batch_123',
datetime(2024, 1, 1)
)
assert key is not None
class TestETLPipeline:
"""Test ETL pipeline."""
def test_add_transformer(self, sample_records):
"""Test adding transformers."""
class MockSource:
def fetch_data(self, date, **kwargs):
return sample_records
class MockDestination:
def write_data(self, records, batch_id, date):
return True
validator = PydanticValidator(DataSchema)
dlq = None # Mock DLQ
pipeline = ETLPipeline(
MockSource(),
MockDestination(),
validator,
dlq
)
pipeline.add_transformer(lambda r: {**r, 'revenue': r['revenue'] * 2})
assert len(pipeline.transformers) == 1
def test_transformer_chain(self):
"""Test multiple transformers in sequence."""
record = {'value': 1}
transformers = [
lambda r: {**r, 'value': r['value'] * 2},
lambda r: {**r, 'value': r['value'] + 10},
]
for transformer in transformers:
record = transformer(record)
assert record['value'] == 12 # (1 * 2) + 10
class TestBatchProcessing:
"""Test batch processing scenarios."""
def test_partial_batch_failure(self, validator):
"""Test that pipeline continues with valid records when some fail."""
records = [
{
'user_id': 1,
'name': 'John',
'email': 'john@example.com',
'age': 30,
'signup_date': datetime(2024, 1, 1),
'revenue': 100.0,
'is_active': True
},
{
'user_id': 2,
'name': 'Jane',
'email': 'invalid', # Invalid
'age': 200, # Invalid
'signup_date': datetime(2024, 1, 2),
'revenue': 200.0,
'is_active': False
}
]
valid, invalid = validator.validate_batch(records)
# Should have 1 valid and 1 invalid
assert len(valid) == 1
assert len(invalid) == 1
if __name__ == '__main__':
pytest.main([__file__, '-v'])
7. Configuration & Deployment
# config.py
from pydantic_settings import BaseSettings
from typing import Optional
class Settings(BaseSettings):
"""Application settings."""
# Database
db_connection_string: str = "postgresql://user:pass@localhost/dbname"
# S3
s3_bucket_name: str = "etl-pipeline-bucket"
s3_dlq_prefix: str = "dlq"
s3_processed_prefix: str = "processed_data"
aws_profile: Optional[str] = None
aws_region: str = "us-east-1"
# Pipeline
batch_size: int = 500
backfill_start_date: str = "2024-01-01"
backfill_end_date: str = "2024-12-31"
# Logging
log_level: str = "INFO"
log_format: str = "json"
# Monitoring
datadog_enabled: bool = False
datadog_api_key: Optional[str] = None
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
# .env example
DB_CONNECTION_STRING=postgresql://user:password@localhost:5432/etl_db
S3_BUCKET_NAME=my-etl-bucket
S3_DLQ_PREFIX=dlq
AWS_PROFILE=production
BATCH_SIZE=1000
LOG_LEVEL=INFO
# docker-compose.yml
version: '3.8'
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_USER: etl_user
POSTGRES_PASSWORD: etl_password
POSTGRES_DB: etl_pipeline
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
airflow:
image: apache/airflow:2.8.1
environment:
AIRFLOW__CORE__DAGS_FOLDER: /opt/airflow/dags
AIRFLOW__CORE__LOAD_EXAMPLES: 'false'
AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: postgresql+psycopg2://etl_user:etl_password@postgres:5432/airflow
ports:
- "8080:8080"
volumes:
- ./dags:/opt/airflow/dags
- ./src:/opt/airflow/src
depends_on:
- postgres
command: bash -c "airflow db init && airflow webserver"
prefect:
image: prefecthq/prefect:2-latest
environment:
PREFECT_API_URL: http://localhost:4200/api
ports:
- "4200:4200"
volumes:
- ./src:/root/src
command: prefect server start
volumes:
postgres_data:
# scripts/run_backfill.py
#!/usr/bin/env python
"""Script to run backfill process."""
import argparse
from datetime import datetime
import logging
from dotenv import load_dotenv
import os
from src.etl_pipeline import ETLPipeline, DatabaseDataSource, S3Destination
from src.models import PydanticValidator, DataSchema
from src.dlq import DeadLetterQueue
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(description='Run ETL backfill')
parser.add_argument('--start-date', required=True, help='Start date (YYYY-MM-DD)')
parser.add_argument('--end-date', required=True, help='End date (YYYY-MM-DD)')
parser.add_argument('--batch-size', type=int, default=500)
args = parser.parse_args()
load_dotenv()
db_conn = os.getenv('DB_CONNECTION_STRING')
s3_bucket = os.getenv('S3_BUCKET_NAME')
aws_profile = os.getenv('AWS_PROFILE')
query_template = """
SELECT user_id, name, email, age, signup_date, revenue, is_active
FROM users
WHERE DATE(created_at) = '{date}'
"""
source = DatabaseDataSource(db_conn, query_template)
destination = S3Destination(s3_bucket, "processed_users", aws_profile)
validator = PydanticValidator(DataSchema)
dlq = DeadLetterQueue(s3_bucket, "dlq", aws_profile)
pipeline = ETLPipeline(source, destination, validator, dlq)
start_date = datetime.strptime(args.start_date, '%Y-%m-%d')
end_date = datetime.strptime(args.end_date, '%Y-%m-%d')
results = pipeline.backfill(start_date, end_date, args.batch_size)
# Print summary
total_valid = sum(r.valid_records for r in results)
total_invalid = sum(r.invalid_records for r in results)
total_processed = sum(r.processed_records for r in results)
logger.info(f"Backfill completed:")
logger.info(f" Total batches: {len(results)}")
logger.info(f" Total valid: {total_valid}")
logger.info(f" Total invalid: {total_invalid}")
logger.info(f" Total processed: {total_processed}")
if __name__ == '__main__':
main()
Summary
This production-ready ETL pipeline includes:
✅ Backfilling: Process historical data with date range support
✅ Dead Letter Queue: Failed records saved to S3 with compression
✅ Schema Validation: Pydantic-based validation with detailed error reporting
✅ Batch Processing: Continues despite individual record failures
✅ Error Handling: Comprehensive logging and recovery
✅ Both Airflow & Prefect: Framework flexibility
✅ S3 Integration: Partitioned storage with compression
✅ Metrics & Monitoring: Detailed pipeline metrics
✅ Testing: Comprehensive test suite
✅ Scalability: Process large datasets in batches
Run with:
python scripts/run_backfill.py --start-date 2024-01-01 --end-date 2024-01-31