When a transformation bug corrupts six days of downstream data, your ability to recover depends on decisions you made long before the incident. This lesson teaches you how to build immutable ingestion logs, audit schemas, and idempotent replay engines that let you re-derive correct downstream state without touching backups.

It's 2:47 AM on a Tuesday. Your on-call alert fires. A transformation job that runs nightly has been silently applying the wrong discount logic to your e-commerce orders table for the past six days — ever since a developer merged a bugfix that accidentally introduced a rounding error. The orders have been aggregated into a revenue summary table, that summary table feeds a customer lifetime value model, and the CLV model drives tomorrow morning's marketing spend decisions. Six days of downstream state is now corrupt.
You have two options. Option one: restore from a backup, losing six days of legitimate new orders alongside the bad transformations, then spend the rest of the week manually reconciling what actually happened. Option two: replay your pipeline from the immutable raw ingestion log — re-applying correct transformations over the same source events, in the same order, as if the bug never existed.
Option two only works if you built for it. That's what this lesson is about.
By the end of this article, you'll be able to design and implement a replay-capable pipeline architecture from scratch, build the audit infrastructure needed to identify exactly what went wrong and when, write idempotent replay jobs that safely rebuild downstream state without duplicating or corrupting data, and reason through the edge cases — schema drift, late-arriving events, fan-out sinks — that make replay harder than it looks.
What you'll learn:
This lesson assumes you're comfortable with the following:
You don't need to be using any particular stack. We'll use Python, SQL (BigQuery-flavored with notes for Postgres/Snowflake), and a Kafka-style log abstraction that you can adapt to S3, GCS, Azure Blob, or a real Kafka cluster.
Before we write a single line of replay logic, we need to establish the architectural principle that makes replay possible: the ingestion layer must be immutable.
Immutability here means that raw events, once written, are never modified or deleted. Your ingestion layer is an append-only record of what happened in the source system. Transformations — cleaning, enriching, aggregating — happen downstream, and they consume from this log. The log itself is sacred.
This isn't a novel idea. It's the core insight behind Kafka's log-centric architecture, behind the Lambda architecture's batch layer, and behind the modern data lakehouse pattern of separating raw landing zones from curated layers. The reason every serious data platform eventually converges on this pattern is that it creates a time machine: you can always re-derive any downstream state by re-processing the log.
Let's look at what an immutable ingestion log looks like on a practical level. Say you're ingesting order events from an e-commerce platform. Each event lands in your raw storage with the following envelope:
# raw_event_schema.py
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Dict, Optional
import uuid
@dataclass
class RawIngestEvent:
"""
The immutable record written at ingestion time.
Never modified after write. Never deleted until retention policy triggers.
"""
# Ingestion-layer identity
ingest_id: str # UUID assigned at ingest time — not from source
ingest_timestamp: datetime # When WE received this event
ingest_batch_id: str # Which ingestion run produced this record
source_system: str # e.g., "shopify_orders", "stripe_payments"
source_partition: str # e.g., "2024-01-15" or Kafka partition key
# Source event identity (from upstream)
source_event_id: str # The ID the source system assigned
source_event_timestamp: datetime # When it happened in the source system
# The actual payload — stored as-is, no transformation
raw_payload: Dict[str, Any] # Exact bytes from source, deserialized to dict
# Schema tracking
schema_version: str # e.g., "shopify_orders_v3"
# Lineage
ingestion_job_version: str # Git commit SHA of the ingestion job
ingestion_pipeline_name: str # e.g., "shopify_orders_ingest"
Three fields in that schema deserve particular attention: ingest_id, ingest_batch_id, and ingestion_job_version.
The ingest_id is a UUID you generate at ingest time, completely independent of whatever the source system calls the event. This matters because source systems sometimes reuse IDs, emit duplicates, or use natural keys that are only unique within a time window. Your ingest layer needs its own identity system.
The ingest_batch_id groups all events from a single ingestion run. When you replay, you replay by selecting specific batch IDs — not by time range alone. Time ranges are fuzzy and prone to off-by-one errors; batch IDs are discrete and exact.
The ingestion_job_version records the git commit SHA of the code that wrote this event. This is your defense against "what did the ingestion logic do differently on that date?" questions. If your ingestion code changed between batch runs, you can see exactly where and cross-reference against the commit log.
Key insight
The ingestion layer's immutability guarantee should be enforced at the infrastructure level, not just by convention. Use object storage with object lock enabled (S3 Object Lock, GCS Bucket Lock), or write to Kafka with compaction disabled for your raw topics. Human conventions erode under pressure; infrastructure constraints don't.
The immutable ingestion log tells you what raw events existed. The audit log tells you what transformations ran against them, when, with which code version, and what they produced. Together, these two systems let you answer the question: "Given that my transformation was buggy between dates X and Y, exactly which output records are corrupted, and what should they have looked like?"
Here's the audit log schema we'll build around:
-- audit_transformation_runs table
-- Written by the transformation layer at job completion (or failure)
CREATE TABLE pipeline_audit.transformation_runs (
-- Run identity
run_id UUID NOT NULL,
pipeline_name VARCHAR(255) NOT NULL,
pipeline_version VARCHAR(64) NOT NULL, -- git commit SHA
-- Temporal bounds
run_started_at TIMESTAMPTZ NOT NULL,
run_completed_at TIMESTAMPTZ, -- NULL if still running or failed
run_status VARCHAR(32) NOT NULL, -- 'running', 'success', 'failed', 'replayed'
-- Input scope (what did this run consume from the ingestion log?)
source_batch_ids TEXT[] NOT NULL, -- array of ingest_batch_ids consumed
source_event_count BIGINT,
source_date_min DATE,
source_date_max DATE,
-- Output scope (what did this run produce?)
target_table VARCHAR(255) NOT NULL,
target_partition VARCHAR(64), -- e.g., '2024-01-15' for date-partitioned tables
output_row_count BIGINT,
output_checksum VARCHAR(64), -- SHA-256 of ordered output for verification
-- Failure context
error_message TEXT,
failed_at_stage VARCHAR(64), -- e.g., 'enrich_customer_data', 'apply_discount'
-- Replay tracking
is_replay BOOLEAN NOT NULL DEFAULT FALSE,
replays_run_id UUID, -- if this is a replay, points to original run_id
replay_reason TEXT,
PRIMARY KEY (run_id)
);
-- Index for the most common recovery query pattern:
-- "Show me all runs that touched this partition that succeeded before the bug was introduced"
CREATE INDEX idx_runs_pipeline_partition_status
ON pipeline_audit.transformation_runs (pipeline_name, target_partition, run_status, run_started_at);
-- audit_output_lineage table
-- One row per (input_ingest_id, output_row_id) pair
-- This is expensive to maintain but invaluable for surgical recovery
CREATE TABLE pipeline_audit.output_lineage (
lineage_id UUID NOT NULL DEFAULT gen_random_uuid(),
run_id UUID NOT NULL REFERENCES pipeline_audit.transformation_runs(run_id),
source_ingest_id UUID NOT NULL, -- the RawIngestEvent.ingest_id
output_table VARCHAR(255) NOT NULL,
output_row_id VARCHAR(255) NOT NULL, -- natural key in the output table
output_snapshot JSONB, -- optional: what the output row looked like
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (lineage_id)
);
CREATE INDEX idx_lineage_run ON pipeline_audit.output_lineage(run_id);
CREATE INDEX idx_lineage_source ON pipeline_audit.output_lineage(source_ingest_id);
CREATE INDEX idx_lineage_output_row ON pipeline_audit.output_lineage(output_table, output_row_id);
The output_lineage table is where cost meets capability. Maintaining row-level lineage is expensive — for a pipeline that processes 10 million events per day, that's 10 million rows per run in this table. You'll want to think carefully about which pipelines warrant full lineage tracking versus which are satisfied by partition-level audit records alone.
A practical middle ground: maintain partition-level audit by default (every pipeline), and opt in to row-level lineage for high-value, high-change-risk pipelines. Your order revenue pipeline? Row-level lineage. Your web traffic sessionization pipeline? Partition-level is probably sufficient.
Tip
Store output_snapshot as JSONB rather than a full row copy. Keep only the fields you'd need to verify correctness — the aggregate values, computed fields, or keys — not the entire denormalized row. This can reduce lineage table size by 80% while preserving all the information you actually need during an incident.
Before you replay anything, you need to know exactly what's corrupted. This is the "audit recovery" part of the title — figuring out the scope of damage before you start fixing it.
Let's work through the e-commerce scenario. Your discount rounding bug was introduced in git commit a3f8c21 and fixed in commit d9e4b87. You need to find every transformation run that used any version between those two commits.
-- Step 1: Find all transformation runs using the buggy pipeline version
-- You'd replace the commit list with your actual affected range
WITH buggy_runs AS (
SELECT
run_id,
pipeline_name,
pipeline_version,
target_partition,
run_started_at,
source_batch_ids,
output_row_count
FROM pipeline_audit.transformation_runs
WHERE pipeline_name = 'orders_revenue_transform'
AND pipeline_version IN (
'a3f8c21', 'b2d9f44', 'c8a1e33' -- all commits between bug intro and fix
)
AND run_status = 'success'
ORDER BY run_started_at
),
-- Step 2: Find what partitions are affected
affected_partitions AS (
SELECT DISTINCT target_partition
FROM buggy_runs
),
-- Step 3: Check if any LATER successful runs re-processed those partitions
-- (maybe someone manually re-ran something)
later_good_runs AS (
SELECT
tr.target_partition,
MAX(tr.run_started_at) AS last_good_run_at
FROM pipeline_audit.transformation_runs tr
JOIN affected_partitions ap ON tr.target_partition = ap.target_partition
WHERE tr.pipeline_name = 'orders_revenue_transform'
AND tr.pipeline_version NOT IN ('a3f8c21', 'b2d9f44', 'c8a1e33')
AND tr.run_status = 'success'
AND tr.run_started_at > (SELECT MIN(run_started_at) FROM buggy_runs)
GROUP BY tr.target_partition
)
-- Final: Show blast radius — partitions that need replay
SELECT
br.target_partition,
COUNT(*) AS buggy_run_count,
SUM(br.output_row_count) AS estimated_affected_rows,
MIN(br.run_started_at) AS first_corrupted_at,
MAX(br.run_started_at) AS last_corrupted_at,
lgr.last_good_run_at AS already_fixed_by_later_run
FROM buggy_runs br
LEFT JOIN later_good_runs lgr ON br.target_partition = lgr.target_partition
GROUP BY br.target_partition, lgr.last_good_run_at
HAVING lgr.last_good_run_at IS NULL -- only show partitions not already fixed
ORDER BY br.target_partition;
This query gives you a table like:
target_partition | buggy_run_count | estimated_affected_rows | first_corrupted_at | last_corrupted_at
2024-01-09 | 1 | 142,338 | 2024-01-10 02:15:00 UTC | 2024-01-10 02:15:00 UTC
2024-01-10 | 1 | 138,901 | 2024-01-11 02:15:00 UTC | 2024-01-11 02:15:00 UTC
2024-01-11 | 1 | 155,220 | 2024-01-12 02:15:00 UTC | 2024-01-12 02:15:00 UTC
...
2024-01-14 | 1 | 149,667 | 2024-01-15 02:15:00 UTC | 2024-01-15 02:15:00 UTC
Six partitions need replay. You now know exactly which ingestion batches fed each of them (from source_batch_ids), which means you can retrieve exactly the right raw events for each replay run.
Warning
Don't assume the blast radius ends at the transformation layer you're fixing. If a corrupted partition fed into aggregations, models, or reporting tables further downstream, those need to be replayed after you fix the base layer. Trace the full dependency chain before you start. The lesson on understanding upstream and downstream dependencies covers how to build that dependency map.
Now we build the thing that actually fixes the problem. The replay engine has four responsibilities:
Here's the core replay engine structure:
# replay_engine.py
import hashlib
import json
import uuid
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Callable, Iterator, List, Optional
import psycopg2 # or your database driver of choice
@dataclass
class ReplayConfig:
"""Everything needed to describe a single replay operation."""
# What we're replaying
pipeline_name: str
target_partition: str
source_batch_ids: List[str]
# The original corrupted run we're replacing
original_run_id: str
replay_reason: str
# Code version being used for the replay
corrected_pipeline_version: str # git SHA of the fixed code
# Safety controls
dry_run: bool = False
max_events: Optional[int] = None # Safety cap for testing
verify_output_checksum: bool = True
@dataclass
class ReplayResult:
"""What came out of a replay operation."""
run_id: str
status: str # 'success', 'failed', 'dry_run_complete'
events_processed: int
output_rows_written: int
output_checksum: str
duration_seconds: float
error: Optional[str] = None
class ReplayEngine:
def __init__(
self,
raw_log_reader, # Abstraction over your storage layer
output_writer, # Abstraction over your target table writer
audit_db_conn, # Connection to your audit database
):
self.raw_log = raw_log_reader
self.writer = output_writer
self.audit_db = audit_db_conn
def execute_replay(
self,
config: ReplayConfig,
transform_fn: Callable[[Iterator[dict]], Iterator[dict]],
) -> ReplayResult:
"""
Execute a full replay for a single partition.
transform_fn accepts an iterator of raw payloads and yields transformed records.
This is where you pass in your corrected transformation logic.
"""
run_id = str(uuid.uuid4())
started_at = datetime.now(timezone.utc)
# Register the run as 'running' in audit log before we do anything
self._write_audit_run_start(run_id, config, started_at)
try:
# 1. Retrieve raw events using the EXACT batch IDs from the original run
raw_events = self.raw_log.read_batches(
batch_ids=config.source_batch_ids,
max_records=config.max_events
)
# 2. Apply corrected transformation
transformed_records = list(transform_fn(raw_events))
events_processed = len(list(self.raw_log.read_batches(
batch_ids=config.source_batch_ids,
max_records=config.max_events
))) # Re-count since transform_fn exhausts the iterator
# 3. Compute output checksum for verification
checksum = self._compute_checksum(transformed_records)
if config.dry_run:
return ReplayResult(
run_id=run_id,
status='dry_run_complete',
events_processed=events_processed,
output_rows_written=len(transformed_records),
output_checksum=checksum,
duration_seconds=(datetime.now(timezone.utc) - started_at).total_seconds()
)
# 4. Write output — this MUST be idempotent (overwrite, not append)
rows_written = self.writer.overwrite_partition(
partition_key=config.target_partition,
records=transformed_records,
pipeline_name=config.pipeline_name,
replay_run_id=run_id,
)
completed_at = datetime.now(timezone.utc)
# 5. Update audit log with success
self._write_audit_run_complete(
run_id=run_id,
config=config,
status='success',
output_row_count=rows_written,
output_checksum=checksum,
completed_at=completed_at
)
return ReplayResult(
run_id=run_id,
status='success',
events_processed=events_processed,
output_rows_written=rows_written,
output_checksum=checksum,
duration_seconds=(completed_at - started_at).total_seconds()
)
except Exception as e:
self._write_audit_run_failed(run_id, str(e))
raise
def _compute_checksum(self, records: List[dict]) -> str:
"""
Deterministic checksum over output records.
Records must be sorted by their natural key before hashing
to ensure checksum is stable regardless of processing order.
"""
# Sort by whatever natural key your records have
sorted_records = sorted(records, key=lambda r: r.get('order_id', ''))
canonical = json.dumps(sorted_records, sort_keys=True, default=str)
return hashlib.sha256(canonical.encode()).hexdigest()
def _write_audit_run_start(self, run_id: str, config: ReplayConfig, started_at: datetime):
with self.audit_db.cursor() as cur:
cur.execute("""
INSERT INTO pipeline_audit.transformation_runs
(run_id, pipeline_name, pipeline_version, run_started_at, run_status,
source_batch_ids, target_partition, is_replay, replays_run_id, replay_reason)
VALUES (%s, %s, %s, %s, 'running', %s, %s, TRUE, %s, %s)
""", (
run_id, config.pipeline_name, config.corrected_pipeline_version,
started_at, config.source_batch_ids, config.target_partition,
config.original_run_id, config.replay_reason
))
self.audit_db.commit()
def _write_audit_run_complete(self, run_id, config, status, output_row_count,
output_checksum, completed_at):
with self.audit_db.cursor() as cur:
cur.execute("""
UPDATE pipeline_audit.transformation_runs
SET run_status = %s,
run_completed_at = %s,
output_row_count = %s,
output_checksum = %s
WHERE run_id = %s
""", (status, completed_at, output_row_count, output_checksum, run_id))
self.audit_db.commit()
def _write_audit_run_failed(self, run_id: str, error_message: str):
with self.audit_db.cursor() as cur:
cur.execute("""
UPDATE pipeline_audit.transformation_runs
SET run_status = 'failed',
run_completed_at = NOW(),
error_message = %s
WHERE run_id = %s
""", (error_message, run_id))
self.audit_db.commit()
Notice that transform_fn is passed in as a parameter rather than hard-coded into the engine. This is intentional — the replay engine is infrastructure; the transformation logic is business logic. They should be independently versioned and independently tested. When you replay, you instantiate the engine with the fixed transformation function and pass it in. The engine doesn't need to know what a discount is.
The writer abstraction in the replay engine needs to implement overwrite_partition correctly, and "correctly" here means genuinely overwriting — not appending. This is where most replay implementations go wrong.
# partition_writer.py
class IdempotentPartitionWriter:
"""
Writes output records to a partitioned table using a delete-then-insert
pattern within a single transaction. Safe to call multiple times on the
same partition — produces identical results each time (given identical input).
"""
def __init__(self, db_conn, target_schema: str, target_table: str,
partition_column: str):
self.db = db_conn
self.target = f"{target_schema}.{target_table}"
self.partition_col = partition_column
def overwrite_partition(
self,
partition_key: str,
records: list[dict],
pipeline_name: str,
replay_run_id: str,
) -> int:
"""
Atomically replace all rows in a partition with the provided records.
Uses a staging table + rename pattern for large volumes, or a simple
DELETE + INSERT for smaller partitions. We use DELETE + INSERT here.
Returns the number of rows written.
"""
if not records:
raise ValueError(
f"Refusing to overwrite partition {partition_key} with empty record set. "
f"If the partition should be empty, pass explicit empty=True flag."
)
with self.db.cursor() as cur:
try:
# Both operations in a single transaction
# Either both succeed or neither does
# Step 1: Delete existing partition data
cur.execute(
f"DELETE FROM {self.target} WHERE {self.partition_col} = %s",
(partition_key,)
)
deleted_count = cur.rowcount
# Step 2: Insert corrected records with replay metadata
insert_sql = self._build_insert_sql(records[0].keys())
for record in records:
record_with_meta = {
**record,
'_pipeline_run_id': replay_run_id,
'_pipeline_name': pipeline_name,
'_written_at': datetime.now(timezone.utc).isoformat(),
}
cur.execute(insert_sql, record_with_meta)
self.db.commit()
print(f"Partition {partition_key}: deleted {deleted_count} rows, "
f"inserted {len(records)} rows.")
return len(records)
except Exception:
self.db.rollback()
raise
def _build_insert_sql(self, columns) -> str:
all_cols = list(columns) + ['_pipeline_run_id', '_pipeline_name', '_written_at']
col_list = ', '.join(all_cols)
val_list = ', '.join(f'%({c})s' for c in all_cols)
return f"INSERT INTO {self.target} ({col_list}) VALUES ({val_list})"
Warning
The DELETE + INSERT pattern works for partitions up to roughly 5-10 million rows, depending on your database. Beyond that, you're better off writing to a staging table and then swapping it in with a DDL operation (or using your warehouse's native partition swap — BigQuery's WRITE_TRUNCATE disposition, Snowflake's CREATE OR REPLACE TABLE ... AS SELECT, Delta Lake's replaceWhere). The staging swap avoids long-running transactions that lock the table from query traffic during the replay.
For BigQuery specifically, partition overwrite looks quite different and much simpler:
# bigquery_partition_writer.py
from google.cloud import bigquery
class BigQueryPartitionWriter:
def __init__(self, project: str, dataset: str, table: str):
self.client = bigquery.Client(project=project)
self.table_ref = f"{project}.{dataset}.{table}"
def overwrite_partition(self, partition_key: str, records: list[dict],
pipeline_name: str, replay_run_id: str) -> int:
"""
BigQuery's WRITE_TRUNCATE disposition atomically replaces a partition.
No explicit DELETE needed — BigQuery handles it transactionally.
"""
# Add metadata columns
enriched = [
{**r, '_pipeline_run_id': replay_run_id, '_pipeline_name': pipeline_name}
for r in records
]
# Target a specific partition using the decorator syntax
partition_ref = f"{self.table_ref}${partition_key.replace('-', '')}"
job_config = bigquery.LoadJobConfig(
write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
# Schema autodetect or provide explicit schema
)
job = self.client.load_table_from_json(enriched, partition_ref, job_config=job_config)
job.result() # Wait for completion
return len(enriched)
The BigQuery version is cleaner because partition-level WRITE_TRUNCATE is an atomic operation that the storage layer handles. This is one of the genuinely nice things about columnar warehouses — they're designed for the "replace a time partition" operation that replay depends on.
Things get more complex when your transformation writes to multiple downstream sinks. Consider this common pattern: your orders transformation writes to (1) the orders_fact table, (2) a customer_order_summary materialized table, and (3) publishes events to a downstream notification queue.
During replay, you need to:
orders_fact ✓ (covered above)customer_order_summary for affected customersThis is the fan-out replay problem, and it has no universal answer. You have to reason about each sink's semantics:
# fan_out_replay_config.py
from enum import Enum
from dataclasses import dataclass
from typing import List
class SinkReplayBehavior(Enum):
OVERWRITE = "overwrite" # Replace existing data (tables, files)
RECOMPUTE = "recompute" # Re-derive dependent aggregations
SKIP = "skip" # Don't replay — event already fired
COMPENSATE = "compensate" # Send a correction event (e.g., accounting systems)
MANUAL = "manual" # Requires human decision
@dataclass
class SinkReplayPolicy:
sink_name: str
behavior: SinkReplayBehavior
compensation_handler: callable = None # Only for COMPENSATE behavior
skip_reason: str = None # Document why we're skipping
# Example: orders pipeline replay policy
ORDERS_PIPELINE_REPLAY_POLICY = [
SinkReplayPolicy(
sink_name="orders_fact",
behavior=SinkReplayBehavior.OVERWRITE,
),
SinkReplayPolicy(
sink_name="customer_order_summary",
behavior=SinkReplayBehavior.RECOMPUTE,
# This table is fully derived from orders_fact, so after we overwrite
# orders_fact, we recompute it with a SQL query
),
SinkReplayPolicy(
sink_name="order_confirmation_kafka_topic",
behavior=SinkReplayBehavior.SKIP,
skip_reason="Confirmation emails already sent; re-firing would confuse customers"
),
SinkReplayPolicy(
sink_name="accounting_ledger",
behavior=SinkReplayBehavior.COMPENSATE,
compensation_handler=send_revenue_correction_entries,
# We'll emit +/- correction entries rather than replaying the original
),
]
The compensation pattern for accounting systems deserves special attention. You cannot overwrite ledger entries — that would destroy the audit trail of what was actually charged. Instead, you emit correction entries: for each corrupted order, you calculate the delta (what should have been charged minus what was charged) and write that as a new entry. This is exactly how double-entry bookkeeping works, and it's the right model for any sink that tracks historical state rather than current state.
Key insight
The question "should I replay this sink or skip it?" ultimately comes down to: "Is this sink tracking what happened or what is currently true?" Event queues and ledgers track what happened — you can't change history, you can only add corrections. Tables and materialized views track what's currently true — you can overwrite them. Getting this distinction wrong during a replay incident is how you generate customer complaints.
The lesson on cross-system transaction management with distributed sagas goes deep on the compensation pattern across multiple systems, which is directly applicable here.
Here's a scenario that happens more often than you'd like: during the six days your pipeline was running buggy, your source schema also changed. The Shopify orders webhook gained a new discount_code field on day three of the incident window. Your immutable log faithfully captured this — events before day three don't have the field, events from day three onward do.
When you replay, your corrected transformation has to handle both schemas. This is where the schema_version field in your RawIngestEvent earns its keep:
# adaptive_transform.py
from typing import Iterator
def corrected_orders_transform(raw_events: Iterator[dict]) -> Iterator[dict]:
"""
Corrected transformation that handles schema evolution within the replay window.
Uses schema_version to route events to the appropriate parsing path.
"""
for event in raw_events:
schema_version = event.get('schema_version', 'shopify_orders_v1')
payload = event['raw_payload']
if schema_version in ('shopify_orders_v1', 'shopify_orders_v2'):
# Pre-discount-code schema: discount is embedded in line items
transformed = _transform_legacy_order(payload, event)
elif schema_version == 'shopify_orders_v3':
# Post-discount-code schema: explicit discount_code field
transformed = _transform_v3_order(payload, event)
else:
raise ValueError(
f"Unknown schema version: {schema_version} for event {event['ingest_id']}. "
f"Cannot replay without schema handler."
)
yield transformed
def _transform_legacy_order(payload: dict, envelope: dict) -> dict:
"""Pre-v3 schema handler. BUG FIXED: discount applied correctly."""
subtotal = sum(
item['quantity'] * item['unit_price']
for item in payload['line_items']
)
# BUG WAS HERE: original code did int(discount_pct * subtotal) which truncated
# to nearest dollar. Fixed: round to 2 decimal places.
discount_amount = round(
payload.get('discount_percentage', 0) / 100 * subtotal,
2
)
return {
'order_id': payload['id'],
'order_date': payload['created_at'][:10],
'customer_id': payload['customer']['id'],
'subtotal': subtotal,
'discount_amount': discount_amount,
'total': round(subtotal - discount_amount, 2),
'_source_schema_version': 'shopify_orders_v1_v2',
'_ingest_id': envelope['ingest_id'],
}
def _transform_v3_order(payload: dict, envelope: dict) -> dict:
"""V3 schema handler with explicit discount_code field."""
subtotal = sum(
item['quantity'] * item['unit_price']
for item in payload['line_items']
)
discount_amount = round(
payload.get('discount_percentage', 0) / 100 * subtotal,
2
)
return {
'order_id': payload['id'],
'order_date': payload['created_at'][:10],
'customer_id': payload['customer']['id'],
'subtotal': subtotal,
'discount_amount': discount_amount,
'discount_code': payload.get('discount_code'), # new field in v3
'total': round(subtotal - discount_amount, 2),
'_source_schema_version': 'shopify_orders_v3',
'_ingest_id': envelope['ingest_id'],
}
The key discipline here is that your output schema has to accommodate both the pre-and-post evolution states. If your target table doesn't have a discount_code column yet, you either need to add it (and accept NULL for pre-v3 records) or handle schema migration as part of the replay process. The lesson on schema evolution strategies for production pipelines covers exactly how to manage this without downtime.
After replay completes, you need to verify that it actually fixed the problem. This isn't optional — "it ran without errors" is not the same as "it produced correct results."
Here's a verification query that cross-checks your replayed output against the expected corrected values:
-- Verification: compare replayed output against manually computed expected values
-- for a sample of orders where we can independently verify the correct discount
WITH
-- Get the most recent run for each partition (should be our replay run)
latest_runs AS (
SELECT DISTINCT ON (target_partition)
run_id,
target_partition,
pipeline_version,
is_replay,
run_completed_at,
output_checksum
FROM pipeline_audit.transformation_runs
WHERE pipeline_name = 'orders_revenue_transform'
AND target_partition BETWEEN '2024-01-09' AND '2024-01-14'
AND run_status = 'success'
ORDER BY target_partition, run_completed_at DESC
),
-- Verify that the latest run for each partition IS actually a replay
-- If it's not, we have a gap
replay_verification AS (
SELECT
target_partition,
run_id,
pipeline_version,
is_replay,
CASE
WHEN is_replay = TRUE AND pipeline_version = 'd9e4b87' THEN 'VERIFIED_REPLAYED'
WHEN is_replay = FALSE THEN 'WARNING_NOT_REPLAYED'
WHEN pipeline_version != 'd9e4b87' THEN 'WARNING_WRONG_VERSION'
ELSE 'UNKNOWN'
END AS replay_status
FROM latest_runs
),
-- Spot-check: for a sample of orders, verify the discount math is now correct
-- We independently calculate what the total should be
order_math_check AS (
SELECT
o.order_date,
o.order_id,
o.subtotal,
o.discount_amount,
o.total,
ROUND(o.subtotal * (1 - COALESCE(src.discount_percentage, 0) / 100.0), 2) AS expected_total,
ABS(o.total - ROUND(o.subtotal * (1 - COALESCE(src.discount_percentage, 0) / 100.0), 2)) AS total_discrepancy
FROM orders_fact o
JOIN raw_orders_verification_sample src ON o.order_id = src.order_id -- your verification dataset
WHERE o.order_date BETWEEN '2024-01-09' AND '2024-01-14'
)
-- Summary
SELECT
rv.target_partition,
rv.replay_status,
COUNT(mc.order_id) AS orders_checked,
COUNT(CASE WHEN mc.total_discrepancy > 0.01 THEN 1 END) AS orders_still_wrong,
MAX(mc.total_discrepancy) AS max_discrepancy,
AVG(mc.total_discrepancy) AS avg_discrepancy
FROM replay_verification rv
LEFT JOIN order_math_check mc ON mc.order_date = rv.target_partition
GROUP BY rv.target_partition, rv.replay_status
ORDER BY rv.target_partition;
You want this query to return VERIFIED_REPLAYED for every partition and zero orders with a discrepancy above your tolerance threshold.
Tip
Store a small "golden dataset" — a handful of orders with known-correct values that you computed manually or via a trusted alternative system — and include them in every verification run. This golden set acts as a tripwire: if your replay is correct, the golden set matches; if something went wrong in your replay logic, it'll show up here before you discover it in production reporting.
You rarely replay a single partition. Usually you're replaying days or weeks of data. That means the replay itself needs orchestration: parallelism where it's safe, sequencing where dependencies demand it, and proper failure handling so that a single bad partition doesn't abort six others that were progressing fine.
Here's a replay orchestration pattern using Python's concurrent.futures:
# replay_orchestrator.py
import concurrent.futures
from datetime import date, timedelta
from typing import List
import logging
logger = logging.getLogger(__name__)
def orchestrate_replay(
affected_partitions: List[dict], # Output of the blast radius query
replay_engine: ReplayEngine,
transform_fn,
corrected_version: str,
replay_reason: str,
max_parallel: int = 3, # Don't overwhelm your database
dry_run: bool = False,
) -> dict:
"""
Orchestrate replay across multiple partitions with controlled parallelism.
Returns a summary of which partitions succeeded and which failed.
"""
results = {}
failed_partitions = []
def replay_single_partition(partition_info: dict) -> tuple:
partition_key = partition_info['target_partition']
config = ReplayConfig(
pipeline_name='orders_revenue_transform',
target_partition=partition_key,
source_batch_ids=partition_info['source_batch_ids'],
original_run_id=partition_info['original_run_id'],
replay_reason=replay_reason,
corrected_pipeline_version=corrected_version,
dry_run=dry_run,
)
try:
result = replay_engine.execute_replay(config, transform_fn)
logger.info(
f"Partition {partition_key}: {result.status} — "
f"{result.events_processed} events, "
f"{result.output_rows_written} rows written, "
f"{result.duration_seconds:.1f}s"
)
return partition_key, result
except Exception as e:
logger.error(f"Partition {partition_key} FAILED: {e}", exc_info=True)
return partition_key, None
# Sort partitions chronologically — older ones first
# This matters if downstream aggregations are date-cumulative
sorted_partitions = sorted(
affected_partitions,
key=lambda p: p['target_partition']
)
with concurrent.futures.ThreadPoolExecutor(max_workers=max_parallel) as executor:
future_to_partition = {
executor.submit(replay_single_partition, p): p['target_partition']
for p in sorted_partitions
}
for future in concurrent.futures.as_completed(future_to_partition):
partition_key, result = future.result()
if result is not None:
results[partition_key] = result
else:
failed_partitions.append(partition_key)
# Summary report
logger.info(
f"\n{'='*60}\n"
f"REPLAY SUMMARY\n"
f"{'='*60}\n"
f"Total partitions: {len(sorted_partitions)}\n"
f"Succeeded: {len(results)}\n"
f"Failed: {len(failed_partitions)}\n"
f"Failed partitions: {failed_partitions or 'none'}\n"
f"Total rows written: {sum(r.output_rows_written for r in results.values())}\n"
f"{'='*60}"
)
return {
'succeeded': results,
'failed': failed_partitions,
}
The max_parallel=3 default is deliberate. Replay is expensive — you're reading from raw storage, applying CPU-intensive transformations, and writing large batches to your database. Running 10 partitions in parallel on a system that also serves production queries is a good way to cause a secondary incident on top of your primary one. Start conservative and monitor your database query queue depth. The lesson on checkpointing and state management in long-running pipelines has useful patterns for safely managing long-running operations like this.
This exercise will take you from a corrupted partition to a verified replayed state. You'll need Python 3.11+, PostgreSQL (or any database with JSON support), and about 90 minutes.
Setup
Create the audit tables from the schema defined earlier in this lesson. Then seed some fake raw ingestion data:
# exercise_setup.py
import uuid
import json
import random
from datetime import datetime, timezone, date, timedelta
def generate_seed_data(db_conn, num_batches: int = 6, events_per_batch: int = 100):
"""
Generate 6 batches of raw order events with an intentional discount bug
in batches 1-5 and correct data in batch 6 (representing the fixed state).
"""
start_date = date(2024, 1, 9)
with db_conn.cursor() as cur:
cur.execute("""
CREATE TABLE IF NOT EXISTS raw_ingest_events (
ingest_id UUID PRIMARY KEY,
ingest_timestamp TIMESTAMPTZ,
ingest_batch_id TEXT,
source_system TEXT,
source_event_id TEXT,
raw_payload JSONB,
schema_version TEXT,
ingestion_job_version TEXT
)
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS orders_fact (
order_id TEXT,
order_date DATE,
customer_id TEXT,
subtotal NUMERIC(12,2),
discount_amount NUMERIC(12,2),
total NUMERIC(12,2),
_pipeline_run_id TEXT,
_pipeline_name TEXT,
_written_at TIMESTAMPTZ,
PRIMARY KEY (order_id)
)
""")
db_conn.commit()
for batch_num in range(num_batches):
batch_date = start_date + timedelta(days=batch_num)
batch_id = f"batch_{batch_date.isoformat()}"
for i in range(events_per_batch):
order_id = f"ORD-{batch_date.isoformat()}-{i:04d}"
subtotal = round(random.uniform(25.0, 500.0), 2)
discount_pct = random.choice([0, 5, 10, 15, 20])
payload = {
'id': order_id,
'created_at': f"{batch_date.isoformat()}T10:00:00Z",
'customer': {'id': f"CUST-{random.randint(1000, 9999)}"},
'line_items': [{'quantity': 1, 'unit_price': subtotal}],
'discount_percentage': discount_pct,
}
cur.execute("""
INSERT INTO raw_ingest_events
(ingest_id, ingest_timestamp, ingest_batch_id, source_system,
source_event_id, raw_payload, schema_version, ingestion_job_version)
VALUES (%s, %s, %s, 'shopify_orders', %s, %s, 'shopify_orders_v2', %s)
""", (
str(uuid.uuid4()),
datetime.now(timezone.utc).isoformat(),
batch_id,
order_id,
json.dumps(payload),
'a3f8c21' if batch_num < 5 else 'd9e4b87' # buggy vs fixed version
))
db_conn.commit()
print(f"Seeded {num_batches * events_per_batch} events across {num_batches} batches")
Your Tasks
Write the "buggy" transformation (use int() truncation on the discount calculation) and run it against all 6 batches. Record each run in your audit table.
Write the "correct" transformation (use round(..., 2)) and wire it into the ReplayEngine from earlier in this lesson.
Use the blast radius query to identify which batches used the buggy pipeline version.
Run the replay engine against those batches with dry_run=True first. Examine the output to confirm the discount amounts are now correct.
Run the actual replay and verify with the verification query.
Extend the exercise: add a second downstream table (e.g., customer_lifetime_value aggregated from orders_fact) and implement the RECOMPUTE sink behavior for it.
Mistake 1: Replaying by time range instead of batch ID
If you filter raw events by ingest_timestamp BETWEEN '2024-01-09' AND '2024-01-14' instead of using source_batch_ids, you're vulnerable to including late-arriving events that landed during that window but belonged to earlier batches. You'll get different data than the original run consumed, which means your replay isn't a true re-derivation. Always use the exact batch IDs recorded in the audit log.
Mistake 2: Not disabling the production pipeline during replay
If your production pipeline continues to run while you replay, you risk a race condition: the production job reads the now-correct replayed data as its "starting state" and writes on top of it, potentially re-introducing issues or corrupting the replay. Pause the production pipeline or implement a replay lock in your audit table before starting:
-- Add a replay_lock_acquired column to track active replays
-- Check this before starting any production run
SELECT COUNT(*) FROM pipeline_audit.transformation_runs
WHERE pipeline_name = 'orders_revenue_transform'
AND run_status = 'running'
AND is_replay = TRUE;
-- If > 0, production pipeline should wait
Mistake 3: Forgetting that aggregations upstream of your target may also need replay
You fixed orders_fact. Did you remember that weekly_revenue_summary aggregates from orders_fact? And that marketing_roi_model reads from weekly_revenue_summary? The corrupted data has propagated upward through your dependency graph. Your blast radius analysis needs to follow these dependencies transitively. Tools like dbt's lineage graph or a manually maintained dependency map make this tractable at scale — see the guide on understanding data pipeline dependencies and lineage tracking.
Mistake 4: Assuming idempotency means you can replay infinitely without consequence
Idempotency means repeated runs produce the same result. But replay still has side effects: it consumes compute, it creates audit records, it temporarily increases load on your database. Running the same replay 50 times because you're unsure if it worked doesn't hurt your data, but it will hurt your cloud bill and potentially your database performance during business hours.
Mistake 5: Not testing the replay path before you need it
Replay is incident response infrastructure. If you build it, deploy it, and never test it, you'll discover it's broken exactly when you need it most. Include replay dry-runs in your quarterly disaster recovery testing. Many teams include "replay one recent partition" as part of their monthly pipeline health checks.
Warning
If your raw ingestion log has a retention policy shorter than your expected incident detection window, you will lose the ability to replay. A bug that runs for 90 days before anyone notices cannot be replayed from a log that only retains 30 days. Align your log retention period with your maximum acceptable incident detection time — and then add a safety buffer. For high-value pipelines, treat raw log storage as essentially permanent (or at minimum, retain for 1-2 years).
Mistake 6: Skipping output verification
A replay that completes without errors is not necessarily a correct replay. Always run verification queries that independently confirm the output values are what you expect. Even better, integrate your verification step into the replay engine itself, failing the audit record if the output checksum doesn't match a pre-computed expected checksum (when you can derive one).
What we built in this lesson is a complete feedback loop for data correctness: an immutable ingestion log that preserves history, an audit system that tracks exactly what code touched exactly what data, a blast radius analysis that identifies corrupted state precisely, and an idempotent replay engine that safely re-derives correct downstream state.
The key architectural principles to take away:
Immutability first. Your ingestion layer cannot be a replay source unless it's genuinely immutable. This isn't optional — it's the prerequisite for everything else in this lesson.
Audit records are infrastructure, not afterthoughts. They need to be written atomically with the data they describe, versioned alongside your pipeline code, and queryable during incidents when time pressure is high.
Replay is different from backfill. Backfilling strategies are about processing data that was never processed. Replay is about re-processing data that was processed incorrectly. The mechanics overlap but the semantics and verification requirements differ.
Fan-out sinks require explicit policy decisions. There is no universal answer for "should I replay this sink?" You have to reason about whether each sink tracks history or current state, and implement overwrite, recompute, skip, or compensate behaviors accordingly.
Verification closes the loop. A replay that you can't verify is a replay you can't trust.
For next steps: if you haven't yet designed your pipeline for idempotency from the ground up, the lesson on designing idempotent data pipelines for exactly-once semantics will show you how replay capability is tightly coupled to idempotency guarantees. If the fan-out compensation pattern interests you, implementing dead letter queues and poison message handling covers the adjacent problem of handling events that can't be processed at all — another scenario where audit infrastructure determines whether you can recover gracefully or not.
Data Pipeline Fundamentals