Design an Idempotent Incremental Data Pipeline for Big Data Tables
SQL & DataModel answerLast updated
Explain how to build a robust, idempotent daily incremental ingestion workflow that handles duplicates, backfills, and schema validation on large relational tables.
You are given a sample raw daily delta log (daily_order_events) from an upstream transaction database:
+------------+----------+-------------+--------+
| event_date | order_id | customer_id | amount |
+------------+----------+-------------+--------+
| 2024-05-20 | 1001 | 501 | 58.90 |
| 2024-05-20 | 1002 | 743 | 12.50 |
| 2024-05-21 | 1003 | 501 | 35.00 |
| 2024-05-22 | 1004 | 888 | 77.10 |
| 2024-05-22 | 1002 | 743 | 12.50 |
+------------+----------+-------------+--------+
Scenario
You need to maintain a large production analytical table (fact_orders) that captures order records without duplicates or inflated metrics. The upstream source drops daily files containing both new orders and repeated re-transmissions of historical records (as seen with order_id = 1002 on both 2024-05-20 and 2024-05-22).
Question
Describe your approach for designing a production-ready, daily incremental load process for this dataset:
- Architecture & Pipeline Logic: What structural steps ensure that re-executing a daily job for any arbitrary date range yields identical results (idempotency)?
- Duplicate Detection: How do you identify whether an arriving record is a brand-new insert, a state update, or an identical re-delivery? Provide the SQL and/or Python code to demonstrate this handling.
- Operational Robustness: How do you handle schema changes, out-of-order data, and failure recovery at scale?
Hints
Hint 1
Look carefully at order 1002: notice how event_date differs while the primary keys and payload remain unchanged.
Hint 2
Consider how window functions (ROW_NUMBER) combined with row-level hashing help distinguish between no-ops and actual payload updates.
Hint 3
Think about staging architecture: landing data in append-only partitions before applying MERGE statements.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Standard Model Answer
1. Executive Summary & Strategy
To build a reliable incremental pipeline over large tables, the architecture must guarantee idempotency (re-running a batch produces no side effects or duplicate metrics) and data freshness.
Given the sample data where order_id = 1002 appears twice across different dates (2024-05-20 and 2024-05-22) with identical values, a simple INSERT INTO approach would cause double-counting ($12.50 added twice). The solution relies on a Landing/Staging -> Deduplicate -> Hash Comparison -> Upsert (MERGE) architecture.
2. End-to-End Pipeline Steps
[ Raw File / CDC Stream ]
│
▼
┌───────────────────────────┐
│ Staging Table (Partition) │ (Append-only / Overwritten per partition run)
└─────────┬─────────────────┘
│
▼
┌───────────────────────────┐
│ In-Batch Deduplication │ (ROW_NUMBER by order_id, keep latest event_date)
└─────────┬─────────────────┘
│
▼
┌───────────────────────────┐
│ Hash-Based Upsert (MERGE) │ (Compare row_hash to separate updates vs no-ops)
└─────────┬─────────────────┘
│
▼
┌───────────────────────────┐
│ Target Table (fact_orders)│
└───────────────────────────┘
- Extract & Landing: Land raw daily data into an append-only staging table partitioned by
event_date. Re-executing a day's load wipes and overwrites only that day's partition in staging. - In-Batch Deduplication: Before touching the target table, run a window function to resolve intra-batch duplicates. For a given
order_id, take the record with the most recentevent_date(or highest sequence/timestamp). - Change Detection via Fingerprinting: Compute a standard row hash (e.g.,
MD5orSHA256) across all non-key payload attributes (customer_id,amount). - Atomic Upsert: Perform a SQL
MERGEstatement against the target table:- Matching Key + Matching Hash: No-op (exact re-delivery).
- Matching Key + Different Hash:
UPDATEpayload and refreshed timestamp. - Non-matching Key:
INSERTnew record.
- Watermarking & Auditing: Record batch metadata (
batch_id,record_count,checksum,execution_time) in a metadata control table.
3. Technical Implementation
SQL Deduplication & Incremental Upsert
-- Step 1: Detect exact re-deliveries and inspect anomalies in staging
SELECT
order_id,
COUNT(*) AS total_appearances,
COUNT(DISTINCT MD5(CONCAT_WS('|', customer_id, amount))) AS distinct_payloads,
MIN(event_date) AS first_seen,
MAX(event_date) AS last_seen
FROM daily_order_events
GROUP BY order_id
HAVING COUNT(*) > 1;
-- Step 2: Incremental Upsert Logic using MERGE
WITH deduplicated_staging AS (
SELECT
order_id,
customer_id,
amount,
event_date,
MD5(CONCAT_WS('|', COALESCE(CAST(customer_id AS VARCHAR), ''),
COALESCE(CAST(amount AS VARCHAR), ''))) AS payload_hash,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY event_date DESC
) AS row_num
FROM daily_order_events
WHERE event_date = :target_run_date
)
MERGE INTO fact_orders AS target
USING (
SELECT order_id, customer_id, amount, event_date, payload_hash
FROM deduplicated_staging
WHERE row_num = 1
) AS source
ON target.order_id = source.order_id
-- Case A: Key matches, but payload has changed -> Genuine Update
WHEN MATCHED AND target.payload_hash <> source.payload_hash THEN
UPDATE SET
customer_id = source.customer_id,
amount = source.amount,
payload_hash = source.payload_hash,
updated_at = CURRENT_TIMESTAMP
-- Case B: Key does not exist -> Brand-New Order
WHEN NOT MATCHED THEN
INSERT (
order_id,
customer_id,
amount,
payload_hash,
created_at,
updated_at
)
VALUES (
source.order_id,
source.customer_id,
source.amount,
source.payload_hash,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
);
-- Note: Matching key AND matching payload_hash is implicitly skipped (no-op).
Python/Pandas Pre-Validation Alternative (for ETL workers)
import pandas as pd
import hashlib
def generate_row_hash(df: pd.DataFrame, columns: list) -> pd.Series:
"""Computes SHA256 string hash for given columns."""
concatenated = df[columns].astype(str).agg('|'.join, axis=1)
return concatenated.apply(lambda val: hashlib.sha256(val.encode('utf-8')).hexdigest())
def process_daily_batch(raw_batch: pd.DataFrame, target_df: pd.DataFrame):
# 1. Intra-batch deduplication (keep latest event_date)
deduplicated = (
raw_batch.sort_values("event_date", ascending=True)
.groupby("order_id")
.last()
.reset_index()
)
# 2. Add payload hash
payload_cols = ["customer_id", "amount"]
deduplicated["payload_hash"] = generate_row_hash(deduplicated, payload_cols)
# 3. Merge with existing target keys to classify actions
merged = deduplicated.merge(
target_df[["order_id", "payload_hash"]],
on="order_id",
how="left",
suffixes=("_new", "_existing")
)
# Inserts: order_id not in target
inserts = merged[merged["payload_hash_existing"].isna()]
# Updates: order_id exists but hash differs
updates = merged[
merged["payload_hash_existing"].notna() &
(merged["payload_hash_new"] != merged["payload_hash_existing"])
]
# Ignored: exact re-deliveries (same key, same hash)
ignored_count = len(merged) - len(inserts) - len(updates)
return inserts, updates, ignored_count
4. Handling Edge Cases & Failures
- Late-Arriving Data: If an event for
2024-05-20arrives on2024-05-22, filtering byevent_date = :run_datein full-table scans can miss updates. A standard pattern is a lookback window (e.g., scanevent_date >= :run_date - INTERVAL '3 DAYS') or utilizing a monotonic watermark column (updated_at/ingested_at). - Schema Evolution: When new columns are added, compute row hashes using only explicit, versioned column lists rather than
SELECT *, preventing hash mismatches when upstream schemas shift. - Engine Scale Considerations:
- Databricks / Snowflake / BigQuery: Native
MERGEhandles hash comparisons efficiently across distributed partitions. - Amazon Redshift: Lacks optimized
MERGEperformance for massive target tables; prefer writing changed records to a temporary stage table, running aDELETEon matching keys in target, followed by a bulkINSERT.
- Databricks / Snowflake / BigQuery: Native