DE Production Readiness
When to Use
Load this skill when the user needs to:
- Make a data pipeline idempotent and safe to retry or re-run
- Implement exponential backoff, retry logic, or error classification in Python or Airflow
- Set up SLA monitoring, alerting (Slack, PagerDuty), or Prometheus metrics for a pipeline
- Define or enforce data freshness SLAs and automate freshness checks
- Add structured logging, OpenTelemetry tracing, or observability metrics to a pipeline
- Build or audit data reconciliation: row counts, checksums, duplicate detection
- Implement graceful degradation — circuit breakers, stale-data fallback, skipping bad partitions
- Perform a blue/green table swap, schema migration, or define a rollback procedure
1. Idempotency Patterns
An idempotent pipeline produces the same final state whether it runs once or ten times for the same logical batch. This is the single most important property of a reliable pipeline because it makes retries, backfills, and incident recovery safe.
Idempotent INSERT — ON CONFLICT DO NOTHING (PostgreSQL / Trino)
sql
-- PostgreSQL: dedup on natural key
INSERT INTO orders (order_id, customer_id, amount, created_at)
SELECT order_id, customer_id, amount, created_at
FROM orders_staging
ON CONFLICT (order_id) DO NOTHING;
-- Trino / Iceberg: use MERGE as the equivalent
MERGE INTO orders AS t
USING orders_staging AS s
ON t.order_id = s.order_id
WHEN NOT MATCHED THEN
INSERT (order_id, customer_id, amount, created_at)
VALUES (s.order_id, s.customer_id, s.amount, s.created_at);
Idempotent MERGE — Upsert Pattern
sql
-- Works for Spark SQL, Trino+Iceberg, Delta Lake, ClickHouse ReplacingMergeTree
MERGE INTO dim_customers AS t
USING (
SELECT * FROM dim_customers_staging
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED AND t.updated_at < s.updated_at THEN
UPDATE SET
t.name = s.name,
t.email = s.email,
t.updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT (customer_id, name, email, updated_at)
VALUES (s.customer_id, s.name, s.email, s.updated_at);
Partition Overwrite Instead of Append
Overwriting an entire partition on each run is idempotent; appending blindly creates duplicates on retry.
python
# PySpark — dynamic partition overwrite (safe re-run)
spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
df.write \
.format("parquet") \
.mode("overwrite") \
.partitionBy("event_date") \
.save("s3://datalake/events/")
sql
-- Spark SQL equivalent
INSERT OVERWRITE TABLE events PARTITION (event_date = '2024-06-01')
SELECT * FROM events_staging WHERE event_date = '2024-06-01';
Deterministic Job IDs
Generate job run IDs deterministically from business keys so re-runs produce the same ID and idempotency guards in downstream systems work correctly.
python
import hashlib
def make_run_id(dag_id: str, logical_date: str) -> str:
"""Stable run ID — same inputs always produce the same ID."""
key = f"{dag_id}::{logical_date}"
return hashlib.sha256(key.encode()).hexdigest()[:16]
run_id = make_run_id("orders_etl", "2024-06-01")
# Insert guard: skip if run_id already recorded in audit table
Checkpointing for Streaming Jobs
python
# PySpark Structured Streaming — checkpoint enables exactly-once restart
query = (
df.writeStream
.format("delta")
.outputMode("append")
.option("checkpointLocation", "s3://checkpoints/orders_stream/")
.trigger(processingTime="1 minute")
.start("s3://datalake/orders_stream/")
)
2. Retry Strategies
Exponential Backoff with Jitter (Python)
Jitter prevents thundering-herd when many workers retry simultaneously after a shared outage.
python
import time
import random
import logging
from functools import wraps
logger = logging.getLogger(__name__)
class TransientError(Exception):
"""Retry this — network blip, lock timeout, rate limit."""
class PermanentError(Exception):
"""Do NOT retry — bad data, auth failure, schema mismatch."""
def retry_with_backoff(
max_attempts: int = 5,
base_delay: float = 1.0,
max_delay: float = 60.0,
jitter: bool = True,
retryable: type = TransientError,
):
"""Decorator: exponential backoff with full jitter."""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return fn(*args, **kwargs)
except PermanentError:
raise # never retry permanent errors
except retryable as exc:
if attempt == max_attempts:
logger.error(
"max_retries_exceeded",
extra={"function": fn.__name__, "attempt": attempt, "error": str(exc)},
)
raise
delay = min(base_delay * (2 ** (attempt - 1)), max_delay)
if jitter:
delay = random.uniform(0, delay) # full jitter
logger.warning(
"retrying",
extra={"function": fn.__name__, "attempt": attempt, "delay_s": round(delay, 2)},
)
time.sleep(delay)
return wrapper
return decorator
# Usage
@retry_with_backoff(max_attempts=5, base_delay=2.0, retryable=TransientError)
def fetch_api_data(url: str) -> dict:
import requests
resp = requests.get(url, timeout=10)
if resp.status_code == 429:
raise TransientError(f"Rate limited: {resp.status_code}")
if resp.status_code == 401:
raise PermanentError(f"Auth failure: {resp.status_code}")
resp.raise_for_status()
return resp.json()
Classify Transient vs Permanent Errors
| Error class | Examples | Action | |
|---|
| Transient | Network timeout, DB lock timeout, API rate limit (429), resource busy | Retry with backoff | |
| Permanent | Auth failure (401/403), schema mismatch, bad data (400), missing table | Fail immediately, alert | |
| Indeterminate | Unknown DB error, unexpected exception | Retry once, then alert | |
Airflow Retry Configuration
python
from datetime import timedelta
import pendulum
from airflow.sdk import dag, task
@dag(
dag_id="orders_etl",
start_date=pendulum.datetime(2024, 1, 1, tz="UTC"),
schedule="@daily",
catchup=False,
default_args={
"owner": "data-eng",
"retries": 3,
"retry_delay": timedelta(minutes=5),
"retry_exponential_backoff": True, # 5m, 10m, 20m
"max_retry_delay": timedelta(minutes=60),
"execution_timeout": timedelta(hours=2),
"sla": timedelta(hours=4), # triggers sla_miss_callback
},
)
def orders_etl():
...
Spark Stage Retry
python
# spark-defaults.conf or SparkSession config
spark = (
SparkSession.builder
.config("spark.task.maxFailures", "4") # default 4 — retries per task
.config("spark.stage.maxConsecutiveAttempts", "4")
.config("spark.network.timeout", "300s")
.config("spark.sql.broadcastTimeout", "300")
.getOrCreate()
)
3. Alerting and SLA Monitoring
Airflow SLA Miss Callback
The sla parameter is measured from DAG start time. Callbacks fire after the scheduler's next heartbeat past the deadline.
python
import pendulum
from airflow.sdk import dag, task
from airflow.utils.email import send_email
def handle_sla_miss(dag, task_list, blocking_task_list, slas, blocking_tis):
"""Called by Airflow when any task in dag misses its SLA."""
missed = ", ".join(t.task_id for t in task_list)
message = (
f"SLA missed in DAG `{dag.dag_id}`\n"
f"Tasks: {missed}\n"
f"Run at: {pendulum.now('UTC').isoformat()}"
)
# Slack
_post_slack(message)
# Email
send_email(
to=["data-oncall@company.com"],
subject=f"[AIRFLOW SLA] {dag.dag_id}",
html_content=f"<pre>{message}</pre>",
)
def _post_slack(text: str):
import requests, os
requests.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": text}, timeout=5)
@dag(
dag_id="orders_etl",
start_date=pendulum.datetime(2024, 1, 1, tz="UTC"),
schedule="@daily",
sla_miss_callback=handle_sla_miss,
default_args={"sla": pendulum.duration(hours=4)},
)
def orders_etl():
...
Prometheus Alerts — Pipeline Latency (PromQL)
Expose a pipeline_last_success_timestamp_seconds gauge from each job (or via Pushgateway), then alert on staleness.
yaml
# prometheus/alerts/pipelines.yml
groups:
- name: data_pipelines
rules:
# Alert when pipeline has not succeeded for more than 4 hours
- alert: PipelineSLAMiss
expr: |
(time() - pipeline_last_success_timestamp_seconds{job="orders_etl"}) > 14400
for: 5m
labels:
severity: critical
team: data-eng
annotations:
summary: "Pipeline {{ $labels.job }} has not completed in 4h"
runbook: "https://wiki.company.com/runbooks/orders_etl"
# Alert on high error rate
- alert: PipelineHighErrorRate
expr: |
rate(pipeline_records_failed_total[5m])
/ (rate(pipeline_records_processed_total[5m]) + 1) > 0.05
for: 10m
labels:
severity: warning
annotations:
summary: "Error rate > 5% in {{ $labels.job }}"
# Alert on consumer lag (Kafka)
- alert: KafkaConsumerLagHigh
expr: kafka_consumer_lag_sum{consumer_group="orders-cg"} > 100000
for: 15m
labels:
severity: warning
annotations:
summary: "Consumer lag {{ $value }} for {{ $labels.consumer_group }}"
python
# Push metrics from Python job to Prometheus Pushgateway
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
import time
def push_pipeline_metrics(job_name: str, records: int, errors: int):
registry = CollectorRegistry()
Gauge("pipeline_last_success_timestamp_seconds",
"Epoch of last successful run", registry=registry).set(time.time())
Gauge("pipeline_records_processed_total",
"Records processed", registry=registry).set(records)
Gauge("pipeline_records_failed_total",
"Records failed", registry=registry).set(errors)
push_to_gateway("pushgateway:9091", job=job_name, registry=registry)
PagerDuty Webhook Integration
python
import requests, os
def page_oncall(summary: str, severity: str = "critical", dag_id: str = ""):
"""Fire PagerDuty Events API v2 alert."""
payload = {
"routing_key": os.environ["PD_ROUTING_KEY"],
"event_action": "trigger",
"payload": {
"summary": summary,
"severity": severity, # critical | error | warning | info
"source": f"airflow:{dag_id}",
"custom_details": {"dag_id": dag_id},
},
}
resp = requests.post(
"https://events.pagerduty.com/v2/enqueue",
json=payload,
timeout=5,
)
resp.raise_for_status()
Dead-Letter Queue Alerting
python
# Kafka DLQ consumer — alert if DLQ depth crosses threshold
from confluent_kafka import Consumer
from prometheus_client import Gauge
dlq_depth_gauge = Gauge("dlq_depth", "Messages in dead-letter queue", ["topic"])