Implement a Python ETL pipeline with Airflow or Prefect that supports backfilling past dates. Include a dead letter queue where rows that fail schema validation get saved to S3 for manual inspection while the rest of the batch continues processing.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm creating a Python ETL pipeline using Prefect 2 with tasks for extract, transform (including pydantic validation), and load. The pipeline supports backfilling by accepting start and end dates, logs invalid rows to S3 as a dead letter queue via boto3, continues processing valid rows, and uses environment variables for credentials without embedding secrets.
Below is a minimal, production-ready pattern for a date-partitioned ETL built with Prefect 2 that:
Accepts a target run_date (supporting backfills via parameters or a for-loop).
Validates records against a schema (via pydantic).
Routes invalid rows to a Dead Letter Queue (DLQ) in S3 for manual inspection, while continuing to process valid rows.
Writes valid rows to a destination (e.g., Postgres).
You can adapt the extract/transform/load to your own sources/targets; the key pieces are the parameterized flow, validation, and DLQ handling.
python
from datetime import date, datetime
import json
import os
from typing import List, Tuple
import boto3
import pandas as pd
from pydantic import BaseModel, ValidationError
from prefect import flow, task, get_run_logger
from sqlalchemy import create_engine, text
# -----------------
# Config / Clients
# -----------------
S3_BUCKET = os.getenv("DLQ_BUCKET", "my-dlq-bucket")
DLQ_PREFIX = os.getenv("DLQ_PREFIX", "etl-dead-letter")
s3_client = boto3.client(
"s3",
region_name=os.getenv("AWS_REGION", "us-east-1"),
aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"),
aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"),
)
DB_CONN_STR = os.getenv("DB_CONN_STR", "postgresql://user:pass@host:5432/db")
engine = create_engine(DB_CONN_STR)
# -----------------
# Schema Definition
# -----------------
class MyRecord(BaseModel):
id: int
name: str
amount: float
event_time: datetime
# -----------------
# Tasks
# -----------------
@task
def extract(run_date: date) -> pd.DataFrame:
"""
Example extract. Replace with your own source (API, CSV, database, etc).
Filters data for the given run_date (partition).
"""
logger = get_run_logger()
logger.info(f"Extracting data for {run_date}")
# Example: local CSV or upstream query; here we just mock:
data = [
{"id": 1, "name": "Alice", "amount": 10.5, "event_time": "2024-06-01T12:00:00Z"},
{"id": 2, "name": "Bob", "amount": "not-a-number", "event_time": "2024-06-01T13:00:00Z"},
{"id": 3, "name": "Charlie", "amount": 99.9, "event_time": "2024-06-01T14:00:00Z"},
]
df = pd.DataFrame(data)
# Example filter by run_date if present in event_time:
df["event_time"] = pd.to_datetime(df["event_time"])
df = df[df["event_time"].dt.date == run_date]
return df
@task
def validate_records(df: pd.DataFrame) -> Tuple[List[dict], List[dict]]:
"""
Validate rows with Pydantic. Return (valid_records, invalid_records).
"""
logger = get_run_logger()
valid, invalid = [], []
for idx, row in df.iterrows():
try:
record = MyRecord(**row.to_dict())
valid.append(record.dict())
except ValidationError as e:
logger.warning(f"Validation failed for row {idx}: {e}")
invalid.append({"row": row.to_dict(), "errors": e.errors()})
logger.info(f"Valid: {len(valid)}, Invalid: {len(invalid)}")
return valid, invalid
@task
def send_to_dlq(invalid_records: List[dict], run_date: date) -> None:
"""
Upload invalid rows to S3 Dead Letter Queue for manual inspection.
"""
logger = get_run_logger()
if not invalid_records:
logger.info("No invalid records to send to DLQ.")
return
key = f"{DLQ_PREFIX}/dt={run_date}/dlq_{datetime.utcnow().isoformat()}.json"
body = json.dumps(invalid_records, default=str)
s3_client.put_object(Bucket=S3_BUCKET, Key=key, Body=body)
logger.info(f"Uploaded {len(invalid_records)} invalid records to s3://{S3_BUCKET}/{key}")
@task
def load_valid_records(valid_records: List[dict]) -> None:
"""
Load valid records to Postgres (or any target).
"""
logger = get_run_logger()
if not valid_records:
logger.info("No valid records to load.")
return
# Example upsert/insert
with engine.begin() as conn:
conn.execute(
text("""
INSERT INTO my_table (id, name, amount, event_time)
VALUES (:id, :name, :amount, :event_time)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name,
amount = EXCLUDED.amount,
event_time = EXCLUDED.event_time
"""),
valid_records,
)
logger.info(f"Loaded {len(valid_records)} records to destination.")
# -----------------
# Main Flow
# -----------------
@flow
def etl_flow(run_date: date = None):
"""
Run ETL for a specific run_date (supports backfill).
"""
if run_date is None:
run_date = date.today()
df = extract(run_date)
valid, invalid = validate_records(df)
# Send invalid rows to DLQ, continue processing
send_to_dlq(invalid, run_date)
load_valid_records(valid)
# -----------------
# Backfill Flow
# -----------------
@flow
def backfill_flow(start_date: date, end_date: date):
"""
Backfill inclusive of start_date through end_date.
"""
current = start_date
while current <= end_date:
etl_flow(current)
current = current + pd.Timedelta(days=1)
if __name__ == "__main__":
# Example single run: today
etl_flow()
# Example backfill:
# backfill_flow(start_date=date(2024, 6, 1), end_date=date(2024, 6, 3))
How to Run & Schedule
Local dev:python etl_prefect.py
Prefect orchestration: Create a deployment with parameters. For example: