StackPractices
intermediate By Mathias Paulenko

Idempotent Load: Re-run Data Loads Safely Without Duplicates

How to re-run data loads safely without duplicates. Covers deduplication keys, MERGE upserts, load IDs, partition overwrite, and transactional loads.

Topics: data

Overview

An idempotent load produces the same result whether it runs once or ten times. A pipeline that dies halfway through gets re-run, and the target table comes out clean: no duplicates, no half-written rows, nothing missing.

Getting there takes a small set of techniques working together. Deduplication keys let the database tell a new row from a repeat. MERGE upserts update what exists and insert what doesn’t. Load IDs give every run a fingerprint you can check before loading again. Partition overwrite swaps a whole slice of the table atomically. Which of them you reach for depends on how your data arrives and what a duplicate would cost you.

Without this, every pipeline failure becomes a cleanup job: someone eyeballs the table, deletes the partial load, and hopes they caught it all.

When to Use

  • ETL/ELT pipelines that can fail and need safe re-runs
  • Scheduled loads where duplicates would corrupt analytics
  • Ingestion from external APIs with retry logic
  • Pipelines where data quality is non-negotiable
  • Streaming consumers that may see the same message twice

When NOT to Use

  • One-time migrations: the extra machinery buys you nothing on a load that runs once
  • Append-only event logs where deduplication happens downstream
  • Prototypes and exploratory loads where correctness doesn’t matter yet

Solution

MERGE upsert for idempotent loads

-- idempotent_upsert.sql: MERGE ensures no duplicates on re-run
MERGE INTO warehouse.customers AS target
USING staging.customers_batch AS source
ON target.id = source.id
WHEN MATCHED THEN
    UPDATE SET
        email = source.email,
        first_name = source.first_name,
        last_name = source.last_name,
        status = source.status,
        updated_at = source.updated_at
WHEN NOT MATCHED THEN
    INSERT (id, email, first_name, last_name, status, created_at, updated_at)
    VALUES (source.id, source.email, source.first_name, source.last_name,
            source.status, source.created_at, source.updated_at);

Python idempotent load with load IDs

# idempotent_load.py: idempotent load with tracking
import pandas as pd
import hashlib
from datetime import datetime
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class IdempotentLoader:
    def __init__(self, warehouse_conn, load_history_table="_load_history"):
        self.warehouse = warehouse_conn
        self.history_table = load_history_table

    def _generate_load_id(self, source_table, batch_date):
        raw = f"{source_table}_{batch_date}"
        return hashlib.sha256(raw.encode()).hexdigest()[:16]

    def _is_already_loaded(self, load_id):
        query = f"SELECT COUNT(*) FROM {self.history_table} WHERE load_id = %s"
        with self.warehouse.cursor() as cur:
            cur.execute(query, (load_id,))
            return cur.fetchone()[0] > 0

    def _record_load(self, load_id, source_table, target_table, row_count):
        query = f"""
            INSERT INTO {self.history_table} (load_id, source_table, target_table, row_count, loaded_at)
            VALUES (%s, %s, %s, %s, %s)
        """
        with self.warehouse.cursor() as cur:
            cur.execute(query, (load_id, source_table, target_table, row_count, datetime.now()))
        self.warehouse.commit()

    def load(self, df, target_table, source_table, batch_date, key_columns=None):
        load_id = self._generate_load_id(source_table, batch_date)

        # Check if already loaded
        if self._is_already_loaded(load_id):
            logger.info(f"Load {load_id} already completed. Skipping.")
            return {"load_id": load_id, "status": "skipped", "rows": 0}

        logger.info(f"Starting load {load_id} for {target_table}")

        # Add load metadata
        df = df.copy()
        df['_load_id'] = load_id
        df['_loaded_at'] = datetime.now()

        # Load to staging table
        staging_table = f"stg_{target_table}_{load_id}"
        df.to_sql(staging_table, self.warehouse, index=False, if_exists='replace')

        # Upsert from staging to target
        key_cols = key_columns or ['id']
        set_cols = ', '.join([
            f"{c} = source.{c}" for c in df.columns
            if c not in key_cols and not c.startswith('_')
        ])
        insert_cols = ', '.join([c for c in df.columns if not c.startswith('_')])

        upsert_sql = f"""
            MERGE INTO {target_table} AS target
            USING {staging_table} AS source
            ON {' AND '.join([f'target.{c} = source.{c}' for c in key_cols])}
            WHEN MATCHED THEN UPDATE SET {set_cols}
            WHEN NOT MATCHED THEN INSERT ({insert_cols})
                VALUES ({', '.join([f'source.{c}' for c in df.columns if not c.startswith('_')])})
        """

        with self.warehouse.cursor() as cur:
            cur.execute(upsert_sql)
            row_count = cur.rowcount
            # Clean up staging
            cur.execute(f"DROP TABLE {staging_table}")

        # Record the load
        self._record_load(load_id, source_table, target_table, row_count)

        logger.info(f"Load {load_id} completed: {row_count} rows")
        return {"load_id": load_id, "status": "loaded", "rows": row_count}

Partition overwrite strategy (Spark)

# partition_overwrite.py: idempotent partition overwrite with PySpark
from pyspark.sql import SparkSession
from pyspark.sql.functions import lit, current_timestamp

spark = SparkSession.builder.appName("IdempotentLoad").getOrCreate()

def load_partition(df, table, partition_col, partition_value):
    """Overwrite a single partition; idempotent by design."""
    df_with_partition = df.withColumn(partition_col, lit(partition_value)) \
        .withColumn("_loaded_at", current_timestamp())

    # mode('overwrite') with dynamic partition overwrite
    # only the specific partition is replaced, not the whole table
    spark.conf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")

    df_with_partition.write \
        .mode("overwrite") \
        .partitionBy(partition_col) \
        .format("parquet") \
        .saveAsTable(table)

    print(f"Overwrote partition {partition_col}={partition_value} in {table}")

# Load daily partition; re-running replaces only this partition
load_partition(df, "warehouse.events", "load_date", "2026-07-05")

Deduplication with window functions

-- dedup_load.sql: remove duplicates from re-runs using window functions
WITH ranked_rows AS (
    SELECT
        *,
        ROW_NUMBER() OVER (
            PARTITION BY id
            ORDER BY _loaded_at DESC
        ) AS rn
    FROM warehouse.customers
    WHERE _load_id IN ('abc123', 'def456')  -- two runs that may overlap
)
DELETE FROM warehouse.customers
WHERE id IN (
    SELECT id FROM ranked_rows WHERE rn > 1
);

-- Or keep only the latest version per key
CREATE TABLE warehouse.customers_deduped AS
SELECT * FROM (
    SELECT
        *,
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY _loaded_at DESC) AS rn
    FROM warehouse.customers
) WHERE rn = 1;

Java idempotent consumer

The same pattern applied to stream consumption: a processed-events table plus one transaction for work and bookkeeping. For the messaging-side deep dive see Idempotent Consumer Pattern.

// IdempotentConsumer.java: process messages without duplicates
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class IdempotentConsumer {

    private final Connection db;

    public IdempotentConsumer(Connection db) {
        this.db = db;
        initProcessedTable();
    }

    private void initProcessedTable() {
        try (var stmt = db.createStatement()) {
            stmt.execute("""
                CREATE TABLE IF NOT EXISTS processed_events (
                    event_id VARCHAR(255) PRIMARY KEY,
                    processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
                """);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public boolean isProcessed(String eventId) {
        try (var ps = db.prepareStatement(
                "SELECT 1 FROM processed_events WHERE event_id = ?")) {
            ps.setString(1, eventId);
            try (var rs = ps.executeQuery()) {
                return rs.next();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void process(String eventId, Runnable handler) {
        if (isProcessed(eventId)) {
            System.out.println("Event " + eventId + " already processed. Skipping.");
            return;
        }

        try {
            db.setAutoCommit(false);

            // Process the event
            handler.run();

            // Mark as processed in the same transaction
            try (var ps = db.prepareStatement(
                    "INSERT INTO processed_events (event_id) VALUES (?)")) {
                ps.setString(1, eventId);
                ps.executeUpdate();
            }

            db.commit();
            System.out.println("Processed event " + eventId);
        } catch (Exception e) {
            try { db.rollback(); } catch (Exception ignored) {}
            throw new RuntimeException("Failed to process event " + eventId, e);
        } finally {
            try { db.setAutoCommit(true); } catch (Exception ignored) {}
        }
    }
}

Atomic load with temp table and rename

-- atomic_swap.sql: atomic table replacement
-- Step 1: Load into a temp table
CREATE TABLE warehouse.customers_new AS
SELECT
    id,
    LOWER(TRIM(email)) AS email,
    TRIM(first_name) AS first_name,
    TRIM(last_name) AS last_name,
    status
FROM staging.customers_batch;

-- Step 2: Atomic swap: rename old to backup, new to live
ALTER TABLE warehouse.customers RENAME TO customers_backup;
ALTER TABLE warehouse.customers_new RENAME TO customers;

-- Step 3: Verify and drop backup
-- SELECT COUNT(*) FROM warehouse.customers;
-- DROP TABLE warehouse.customers_backup;

Explanation

Every idempotent load answers the same question: what makes a re-run land on the same state? Three mechanisms, alone or combined:

flowchart diagram: Source batch
  • Deduplication key. MERGE and window dedup both need something to match on: a primary key or composite business key. No key, no idempotency: the database can’t tell a repeat from a new row.
  • Staging plus MERGE. Land the batch in a throwaway table first, then upsert. If the run dies mid-write, staging is dropped and the target never saw partial data. MERGE is the workhorse for incremental loads; its cost grows with target size, so on very large tables it gets profiled against the alternatives.
  • Load ID plus history table. Hash source + batch_date, check the history table before touching anything, record it after. Cheap insurance against the most common re-run: the scheduler retrying a batch that already finished.
  • Partition overwrite. When data arrives partition-aligned (daily loads, tenant splits), replacing the whole partition is simpler and cheaper than row-level matching, and idempotent by construction. It only works if your table is partitioned along the load boundary, which is why it pairs with MERGE rather than replacing it.
  • Atomic swap. Rename-based replacement gives you a full-table overwrite with zero partial visibility. Strongest guarantee, biggest blast radius; it rebuilds everything, so it suits full refreshes, not incremental feeds.

Pick the mechanism by blast radius: partition overwrite for aligned batch data, MERGE for row-level changes, atomic swap for full refreshes, load IDs as the belt around any of them.

Variants

Idempotent API ingestion with checkpointing

# api_ingestion.py: idempotent API data ingestion
import requests
import json
from datetime import datetime
from pathlib import Path

class IdempotentApiLoader:
    def __init__(self, checkpoint_file="checkpoints.json"):
        self.checkpoint_file = Path(checkpoint_file)
        self.checkpoints = self._load_checkpoints()

    def _load_checkpoints(self):
        if self.checkpoint_file.exists():
            return json.loads(self.checkpoint_file.read_text())
        return {}

    def _save_checkpoints(self):
        self.checkpoint_file.write_text(json.dumps(self.checkpoints, indent=2))

    def load_page(self, api_url, endpoint, page=1):
        checkpoint_key = f"{endpoint}_page_{page}"

        if checkpoint_key in self.checkpoints:
            print(f"Page {page} already loaded. Skipping.")
            return self.checkpoints[checkpoint_key]

        response = requests.get(f"{api_url}/{endpoint}", params={"page": page})
        data = response.json()

        self.checkpoints[checkpoint_key] = {
            "loaded_at": str(datetime.now()),
            "record_count": len(data.get("results", []))
        }
        self._save_checkpoints()

        return data

Conditional load with pre-checks

# conditional_load.py: cheap short-circuit before an expensive MERGE
class ConditionalLoader:
    def __init__(self, warehouse):
        self.warehouse = warehouse

    def load_if_needed(self, df, table, key_col, batch_date):
        # Short-circuit: if the target already holds a full batch, skip.
        # A partial load falls through to the MERGE, which finishes it safely.
        with self.warehouse.cursor() as cur:
            cur.execute(f"""
                SELECT COUNT(*) FROM {table}
                WHERE DATE(created_at) = %s
            """, (batch_date,))
            existing_count = cur.fetchone()[0]

        if existing_count >= len(df):
            print(f"Target already has {existing_count} rows for {batch_date}. Skipping.")
            return

        self._upsert(df, table, key_col)

    def _upsert(self, df, table, key_col):
        cols = [c for c in df.columns]
        set_cols = ', '.join(
            f"{c} = source.{c}" for c in cols if c != key_col
        )
        merge_sql = f"""
            MERGE INTO {table} AS target
            USING staging_batch AS source
            ON target.{key_col} = source.{key_col}
            WHEN MATCHED THEN UPDATE SET {set_cols}
            WHEN NOT MATCHED THEN INSERT ({', '.join(cols)})
                VALUES ({', '.join(f'source.{c}' for c in cols)})
        """
        with self.warehouse.cursor() as cur:
            df.to_sql("staging_batch", self.warehouse,
                      index=False, if_exists='replace')
            cur.execute(merge_sql)
        self.warehouse.commit()

Best Practices

  • For a deeper guide, see ETL Extract-Transform-Load.

  • Use MERGE instead of bare INSERT: existing rows update, new rows insert, and a re-run changes nothing

  • Track load IDs in a history table so you can detect a finished batch and skip it

  • Prefer partition overwrite for partition-aligned batch data; it replaces a whole slice atomically

  • Wrap the load in a transaction so a mid-run failure rolls back instead of stranding partial rows

  • Stage first: load into a staging table, then MERGE to target in one statement

  • Deduplicate with ROW_NUMBER() OVER (PARTITION BY key ORDER BY loaded_at DESC) when cleaning up after a double-run

  • Persist checkpoints to a file or table so a restarted job skips finished pages

  • Test the failure mode: run the pipeline twice and count rows in the target

Common Mistakes

  • Using INSERT instead of MERGE: every re-run stacks duplicate rows on top of the last.
  • No load tracking: without a history table there’s no way to know a batch already ran.
  • Partial loads without transactions: the pipeline dies halfway and leaves the target half-written.
  • Overwriting the whole table: DROP TABLE + CREATE TABLE destroys every other partition’s data.
  • No deduplication key: MERGE can’t match rows without a primary or composite key, so nothing is idempotent.

Further Reading

Frequently Asked Questions

What is an idempotent data load?

A load that produces the same result whether it runs once or multiple times. Re-running the pipeline creates no duplicates and corrupts nothing, because the target table lands in the same state every time.

How do I make a load idempotent?

Use MERGE instead of INSERT. Give each run a load ID and check the history table first. Stage the batch, upsert to target in a transaction.

What is a load ID?

A fingerprint for one load run, usually a hash of source table plus batch date. It lives in a load history table, so a retried batch can be detected and skipped.

Should I use partition overwrite or MERGE?

Partition overwrite for partition-aligned batch data: it replaces the whole slice atomically. MERGE for incremental loads that touch individual rows, like CDC feeds or streaming sinks.

How do I handle idempotency in streaming consumers?

Use the event ID as the dedup key. Keep a processed-events table, check it before handling, and mark the event processed inside the same transaction as the work.