Retries, backfills, and re-runs are facts of life in production data pipelines. If your pipeline isn't idempotent, every one of them is a silent data corruption risk. This lesson teaches you exactly what idempotency means, why it matters, and how to implement it with upserts, truncate-and-reload, and partition overwrite patterns.

Imagine your daily sales aggregation pipeline runs every night at midnight. It pulls transaction data from your database, computes daily totals, and writes them to your analytics warehouse. One night, the warehouse is briefly unresponsive, and your pipeline crashes halfway through. Your orchestration tool — doing exactly what it's supposed to — retries the pipeline 10 minutes later. The retry succeeds. Great, right?
Not so fast. Depending on how your pipeline was written, you might now have duplicate rows in your warehouse. Your "daily sales" table might show $1.2 million in revenue when the actual number was $600,000. By the time your business analyst opens their dashboard in the morning and sends that number to the VP of Sales, you have a trust problem. The data looks right. It's just catastrophically wrong.
This is the problem idempotency solves. By the end of this lesson, you'll understand what idempotency means in the context of data pipelines, why it's one of the most important design properties you can build in from day one, and how to implement it concretely using patterns you can apply immediately in Python and SQL.
What you'll learn:
This lesson assumes you're comfortable with the basic concept of a data pipeline — if you're new to that, start with What is a Data Pipeline? Architecture and Core Concepts for Data Engineers. You should also have a basic working knowledge of Python and SQL. No advanced experience required.
The word "idempotent" comes from mathematics and computer science. An operation is idempotent if running it multiple times produces the same result as running it once.
A concrete, non-technical example: setting your thermostat to 72°F is idempotent. You can press the button ten times. The temperature will still be 72°F. Contrast that with turning up the heat by 2°F — do that ten times and you've added 20°F. That's a non-idempotent operation.
In data pipelines, idempotency means that re-running your pipeline — whether due to a retry, a failure recovery, a backfill, or just a human re-triggering it — produces the same final state in your destination system as if you had run it exactly once.
The critical phrase is final state. Idempotency isn't about preventing re-runs. It's about making re-runs safe.
Key insight
Idempotency doesn't mean "run it only once." It means "it doesn't matter how many times you run it — the outcome is always correct." This distinction is what makes it so powerful in distributed, failure-prone systems.
Let's look at a simple pipeline step that is definitely not idempotent:
def load_daily_orders(conn, orders: list[dict]):
cursor = conn.cursor()
for order in orders:
cursor.execute(
"INSERT INTO daily_orders (order_id, amount, order_date) VALUES (%s, %s, %s)",
(order["order_id"], order["amount"], order["order_date"])
)
conn.commit()
Run this once: 500 rows inserted. Run it again with the same data: 1,000 rows — all duplicates. Run it a third time: 1,500 rows.
That's a ticking time bomb in production.
Before we get to solutions, it's worth understanding why pipelines run multiple times. If it only happened during exceptional failures, you might argue it's not worth designing for. But in practice, re-runs happen constantly:
Retries on failure. Most orchestration tools like Apache Airflow automatically retry failed tasks. As you'll learn in Scheduling and Orchestrating Pipelines with Airflow, retries are a core feature of reliable orchestration — but they only help if your pipeline can survive them.
Backfills. When you deploy a new pipeline or fix a bug in an existing one, you often need to reprocess historical data. This is called a backfill, and it means intentionally re-running your pipeline for past time periods. If your pipeline isn't idempotent, backfilling means duplicating data. For a full treatment of this topic, see Understanding Data Pipeline Backfilling: Strategies for Reprocessing Historical Data.
Manual re-runs. A stakeholder notices something looks wrong in the dashboard and asks you to "just run the pipeline again." If your pipeline isn't idempotent, this is a terrifying request.
Partial failures. A pipeline might succeed for 8 of 10 source files and fail on the 9th. When it retries, should it re-process the first 8? If your pipeline isn't idempotent, you can't safely do that.
Infrastructure hiccups. Network timeouts, database deadlocks, cloud provider blips. These are not edge cases. They are the normal operating environment of production systems.
Warning
Never assume your pipeline will only run once per scheduled interval. Build as if it will run twice — because eventually, it will.
There are three main strategies you'll use in practice. Each fits different scenarios, and understanding when to reach for each one is a key skill.
An upsert is a database operation that says: "If this row already exists, update it. If it doesn't, insert it." Most modern databases support this directly.
This pattern works well when:
order_id)Here's a non-idempotent insert transformed into an idempotent upsert in PostgreSQL:
def load_daily_orders_idempotent(conn, orders: list[dict]):
cursor = conn.cursor()
for order in orders:
cursor.execute(
"""
INSERT INTO daily_orders (order_id, amount, order_date)
VALUES (%s, %s, %s)
ON CONFLICT (order_id)
DO UPDATE SET
amount = EXCLUDED.amount,
order_date = EXCLUDED.order_date
""",
(order["order_id"], order["amount"], order["order_date"])
)
conn.commit()
The ON CONFLICT ... DO UPDATE clause is PostgreSQL's upsert syntax. If a row with the same order_id already exists, it updates instead of duplicating. Run this ten times with the same data: you still have exactly 500 rows.
For SQLite (useful in local development), the equivalent is INSERT OR REPLACE:
INSERT OR REPLACE INTO daily_orders (order_id, amount, order_date)
VALUES (?, ?, ?);
Tip
For upserts to work correctly, your destination table must have a primary key or unique constraint defined on the natural key column(s). Without the constraint, the database has no way to detect conflicts.
Sometimes upserts are overkill — or impractical. If you're computing a full aggregate (like a daily rollup table), and you're always replacing the entire output for a given time period, it's simpler and more reliable to delete the old data and re-insert fresh data every time.
def reload_daily_summary(conn, summary_date: str, records: list[dict]):
cursor = conn.cursor()
# Step 1: Delete existing data for this date
cursor.execute(
"DELETE FROM daily_sales_summary WHERE summary_date = %s",
(summary_date,)
)
# Step 2: Insert fresh data
for record in records:
cursor.execute(
"""
INSERT INTO daily_sales_summary
(summary_date, region, total_sales, order_count)
VALUES (%s, %s, %s, %s)
""",
(summary_date, record["region"], record["total_sales"], record["order_count"])
)
conn.commit()
This is idempotent because no matter how many times you call it for 2024-11-15, you'll always end up with exactly one set of rows for that date — the most recently computed ones.
The key insight here is scoping your delete. You're not truncating the entire table (that would destroy historical data). You're deleting only the partition you're about to overwrite.
Note
Wrap the delete and insert in a single transaction whenever possible. If the insert fails after the delete, you don't want to end up with a date range that has zero rows. The transaction ensures it's atomic — either both succeed or neither does.
In columnar data warehouses and data lakes (like BigQuery, Redshift, or Parquet files in S3), the concept of "partitioning" lets you treat different slices of data (usually by date) as independent, replaceable units.
Partition overwrite means: "Replace the entire partition for this date with new data." It's the warehouse-native version of truncate-and-reload, but often more efficient because it operates at the storage level.
In BigQuery, for example, you can configure your load job to overwrite a specific partition:
from google.cloud import bigquery
def load_partition_to_bigquery(client, df, table_id: str, partition_date: str):
"""
Loads data into a specific date partition, overwriting any existing data.
"""
job_config = bigquery.LoadJobConfig(
write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
time_partitioning=bigquery.TimePartitioning(
type_=bigquery.TimePartitioningType.DAY,
field="event_date",
),
)
# Target the specific partition using the decorator syntax
partition_table = f"{table_id}${partition_date.replace('-', '')}"
job = client.load_table_from_dataframe(df, partition_table, job_config=job_config)
job.result() # Wait for the job to complete
By targeting my_dataset.my_table$20241115 (the $ decorator specifies the partition), you're telling BigQuery to atomically replace that date's data. Re-run it three times: same result.
This pattern is especially powerful when combined with incremental loading patterns, where you're processing one partition at a time based on a watermark.
Idempotency isn't just about database writes. If your pipeline reads from files or APIs, the source-side logic also needs to be idempotent in the sense that re-processing the same input produces the same output.
Consider a pipeline that reads CSV files from an S3 bucket and processes them:
import hashlib
import json
def compute_file_hash(filepath: str) -> str:
"""Generate a stable hash for a file's contents."""
with open(filepath, "rb") as f:
return hashlib.md5(f.read()).hexdigest()
def has_been_processed(conn, filepath: str, file_hash: str) -> bool:
"""Check if we've already successfully processed this file."""
cursor = conn.cursor()
cursor.execute(
"SELECT 1 FROM processed_files WHERE filepath = %s AND file_hash = %s",
(filepath, file_hash)
)
return cursor.fetchone() is not None
def mark_as_processed(conn, filepath: str, file_hash: str):
"""Record that we successfully processed this file."""
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO processed_files (filepath, file_hash, processed_at)
VALUES (%s, %s, NOW())
ON CONFLICT (filepath) DO UPDATE SET
file_hash = EXCLUDED.file_hash,
processed_at = EXCLUDED.processed_at
""",
(filepath, file_hash)
)
conn.commit()
def process_file(filepath: str, conn):
file_hash = compute_file_hash(filepath)
if has_been_processed(conn, filepath, file_hash):
print(f"Skipping {filepath} — already processed.")
return
# ... actual processing logic here ...
mark_as_processed(conn, filepath, file_hash)
This pattern — sometimes called a processing ledger or deduplication table — lets your pipeline skip files it's already handled. The hash check is important: if the file contents change (a corrected data file), the new hash won't match, and the pipeline will process it again.
Key insight
Tracking what has been processed is a form of checkpointing. It lets your pipeline resume intelligently after failures rather than reprocessing everything from scratch or blindly skipping new data.
The most common mistake engineers make with idempotency is assuming they've built it correctly without verifying. Here's a simple, concrete test protocol:
For any pipeline you build, run this test before considering it production-ready:
After each run, check:
GROUP BY key HAVING COUNT(*) > 1)?-- Check for duplicates after each run
SELECT order_id, COUNT(*) as row_count
FROM daily_orders
WHERE order_date = '2024-11-15'
GROUP BY order_id
HAVING COUNT(*) > 1;
If this query returns rows, your pipeline is not idempotent.
The more realistic test is simulating a crash partway through:
def load_orders_with_simulated_failure(conn, orders: list[dict], fail_at: int = None):
"""
Test harness: fail deliberately at a specific row to simulate mid-run crash.
"""
cursor = conn.cursor()
for i, order in enumerate(orders):
if fail_at and i == fail_at:
raise RuntimeError(f"Simulated failure at row {i}")
cursor.execute(
"""
INSERT INTO daily_orders (order_id, amount, order_date)
VALUES (%s, %s, %s)
ON CONFLICT (order_id) DO UPDATE SET
amount = EXCLUDED.amount
""",
(order["order_id"], order["amount"], order["order_date"])
)
conn.commit()
Run this with fail_at=250 on 500 rows. Then run the full pipeline. The final row count should be exactly 500 — not 750 (250 from the failed run + 500 from the successful one).
Tip
Building automated idempotency tests as part of your pipeline test suite — not just manual checks — is what separates production-grade pipelines from scripts that happen to work most of the time. For a comprehensive approach to pipeline testing, see Pipeline Testing: Unit Tests, Integration Tests, and Data Contracts.
Here's a self-contained exercise you can run locally with Python and SQLite. It demonstrates a non-idempotent pipeline, the problem it causes, and the fix.
Setup: Install Python 3.8+ and the sqlite3 module (it's part of the standard library).
import sqlite3
import os
# --- Setup ---
DB_PATH = "idempotency_exercise.db"
def get_connection():
return sqlite3.connect(DB_PATH)
def setup_tables(conn):
conn.execute("""
CREATE TABLE IF NOT EXISTS product_sales (
sale_id TEXT,
product TEXT,
revenue REAL,
sale_date TEXT
)
""")
conn.commit()
# --- Sample data (same data for every "run") ---
SAMPLE_SALES = [
{"sale_id": "S001", "product": "Widget Pro", "revenue": 299.99, "sale_date": "2024-11-15"},
{"sale_id": "S002", "product": "Gadget Plus", "revenue": 149.50, "sale_date": "2024-11-15"},
{"sale_id": "S003", "product": "Widget Pro", "revenue": 299.99, "sale_date": "2024-11-15"},
]
# --- NON-IDEMPOTENT version ---
def load_sales_bad(conn, sales):
for sale in sales:
conn.execute(
"INSERT INTO product_sales VALUES (?, ?, ?, ?)",
(sale["sale_id"], sale["product"], sale["revenue"], sale["sale_date"])
)
conn.commit()
# --- IDEMPOTENT version ---
def load_sales_good(conn, sales):
for sale in sales:
conn.execute(
"""
INSERT INTO product_sales (sale_id, product, revenue, sale_date)
VALUES (?, ?, ?, ?)
ON CONFLICT(sale_id) DO UPDATE SET
product = excluded.product,
revenue = excluded.revenue,
sale_date = excluded.sale_date
""",
(sale["sale_id"], sale["product"], sale["revenue"], sale["sale_date"])
)
conn.commit()
def check_results(conn, label):
rows = conn.execute("SELECT COUNT(*), SUM(revenue) FROM product_sales").fetchone()
print(f"[{label}] Row count: {rows[0]}, Total revenue: ${rows[1]:.2f}")
# --- Run the exercise ---
if os.path.exists(DB_PATH):
os.remove(DB_PATH)
conn = get_connection()
# Part 1: Demonstrate the problem
print("=== Part 1: Non-idempotent pipeline ===")
setup_tables(conn)
load_sales_bad(conn, SAMPLE_SALES)
check_results(conn, "After run 1")
load_sales_bad(conn, SAMPLE_SALES)
check_results(conn, "After run 2")
load_sales_bad(conn, SAMPLE_SALES)
check_results(conn, "After run 3")
# Reset
conn.execute("DELETE FROM product_sales")
conn.commit()
# Part 2: Note — SQLite requires the table to have a PRIMARY KEY for ON CONFLICT
# Recreate with proper constraint
conn.execute("DROP TABLE product_sales")
conn.execute("""
CREATE TABLE product_sales (
sale_id TEXT PRIMARY KEY,
product TEXT,
revenue REAL,
sale_date TEXT
)
""")
conn.commit()
print("\n=== Part 2: Idempotent pipeline ===")
load_sales_good(conn, SAMPLE_SALES)
check_results(conn, "After run 1")
load_sales_good(conn, SAMPLE_SALES)
check_results(conn, "After run 2")
load_sales_good(conn, SAMPLE_SALES)
check_results(conn, "After run 3")
conn.close()
Expected output for Part 1:
[After run 1] Row count: 3, Total revenue: $749.48
[After run 2] Row count: 6, Total revenue: $1498.96
[After run 3] Row count: 9, Total revenue: $2248.44
Expected output for Part 2:
[After run 1] Row count: 3, Total revenue: $749.48
[After run 2] Row count: 3, Total revenue: $749.48
[After run 3] Row count: 3, Total revenue: $749.48
The difference is the entire point. Part 2's pipeline is safe to retry, backfill, or re-run as many times as needed.
Mistake 1: Using timestamps as unique keys without understanding precision.
If your unique key includes a timestamp, make sure the precision is fine enough that two separate events don't share the same key. A TIMESTAMP column truncated to the second will cause collisions for high-frequency event streams. Use microsecond precision or a UUID.
Mistake 2: Forgetting to scope the delete in truncate-and-reload.
DELETE FROM daily_summary is a full wipe. DELETE FROM daily_summary WHERE summary_date = '2024-11-15' is scoped. Always scope your deletes to the partition you're replacing.
Mistake 3: Building idempotency in the application but not in the database.
If multiple pipeline instances can run simultaneously, an application-level if exists: skip check has a race condition — two instances can both pass the check before either has written. Use database constraints (unique indexes, ON CONFLICT) as the authoritative source of truth.
Mistake 4: Assuming idempotency means exactly-once delivery. Idempotency means the result is correct if you run multiple times. It doesn't prevent duplicates from being processed — it ensures duplicates don't corrupt your output. For a deeper treatment of exactly-once semantics, see Designing Idempotent Data Pipelines: Guaranteeing Exactly-Once Semantics in Production.
Mistake 5: Not wrapping delete+insert in a transaction. If your pipeline crashes between the delete and the insert steps in a truncate-and-reload pattern, you'll have a time window with zero rows for that partition. Always wrap both operations in a single transaction.
Warning
Data quality issues caused by non-idempotent pipelines are among the hardest to debug because the data looks real. A doubled row count doesn't throw an error — it just quietly corrupts your reports. This is why idempotency testing belongs in your standard pipeline quality checklist alongside schema validation and null checks. For more on building robust validation, see Data Quality: Validation, Testing, and Monitoring Pipelines.
Idempotency is one of those properties that feels optional until the moment you need it — and then feels absolutely essential. The good news is that building it in from the start is not significantly more work than building pipelines without it. The main shift is mindset: always ask yourself, "What happens if this runs again?"
Here's what we covered:
Where to go next:
Idempotency isn't a feature you add later. It's a foundation. Build it in now and your future self — the one getting paged at 2am after a retry storm — will thank you.
Data Pipeline Fundamentals