Skip to content

Idempotent Data Pipelines and Backfills

Data & AI7 min read

Make data pipelines safe to retry and backfill. Learn overwrite, merge and staging patterns, late data handling and common duplicate traps.

In this article
  1. Why idempotency matters
  2. The core idea: determinism and a defined window
  3. Patterns for idempotent loads
  4. Running backfills safely
  5. Handle late and duplicate data
  6. Common mistakes
  7. What to do next

An idempotent data pipeline produces the same result whether it runs once or many times for the same input. That property lets you safely retry after a failure, rerun a day of data after fixing a bug, and backfill history without creating duplicates or double-counted totals. You achieve it by writing results in a way that replaces or merges data deterministically, rather than blindly appending, and by making every run depend on an explicit input window instead of "whatever is new right now".

This guide is for data engineers, analysts and technical managers who maintain scheduled data jobs. It explains the problem, the main patterns for idempotent loads, how to run backfills safely, and the mistakes that most often cause duplicates and gaps.

Why idempotency matters

Pipelines fail. Networks drop, an upstream file arrives late, a schema changes, a job runs out of memory. When that happens you need to run the job again. If rerunning appends the same rows a second time, your revenue report is suddenly wrong and nobody knows by how much.

Three situations make idempotency essential:

  • Retries. Orchestrators and queues often deliver work more than once. A job that fails halfway and restarts must not leave partial duplicates behind.
  • Bug fixes. When you correct a transformation, you want to recompute the affected period and overwrite the old numbers cleanly.
  • Backfills. Loading history for a new table, or reprocessing after a late source correction, means running many past periods in bulk.

Without idempotency, each of these becomes a manual clean-up exercise. With it, they are routine operations. This fits into the bigger picture of dependable data work described in our overview of data governance basics, where trust in the numbers is the point.

The core idea: determinism and a defined window

Two principles sit under every idempotent design.

First, a run is defined by its inputs, not by the clock. A job that says "load rows created since I last ran" depends on hidden state. If it runs twice, the second run sees a different answer. A job that says "load rows for 14 March, from midnight to midnight UTC" gives the same answer every time. Pass the window as a parameter: a date, a date range or a batch identifier.

Second, a write replaces what it owns. A run for 14 March should leave the target in the same state whether it is the first run or the fifth. Either it overwrites the 14 March slice, or it merges rows on a stable key, so that existing rows are updated and not repeated.

Keep transformations deterministic too. Avoid logic that depends on the current time, random values or unordered results, unless you fix the seed or the ordering. A query that picks "any one" duplicate row can give different answers on different runs.

Patterns for idempotent loads

There are four common patterns, each with trade-offs.

1. Overwrite the partition

If your target is partitioned by date, delete or replace the whole partition for the window and write fresh data. This is simple and robust, and works well for event and fact tables.

-- illustrative, syntax varies by database
DELETE FROM sales_daily WHERE sale_date = :run_date;
INSERT INTO sales_daily
SELECT * FROM staging_sales WHERE sale_date = :run_date;

Wrap the delete and insert in one transaction where your platform allows it, so readers never see an empty day. Some warehouses offer an atomic "insert overwrite" operation for the same purpose.

2. Merge (upsert) on a natural or business key

Match incoming rows to existing rows on a stable key, update matches and insert new ones. This suits dimension tables and records that change over time.

MERGE INTO customers t
USING staging_customers s ON t.customer_id = s.customer_id
WHEN MATCHED THEN UPDATE SET name = s.name, email = s.email
WHEN NOT MATCHED THEN INSERT (customer_id, name, email)
VALUES (s.customer_id, s.name, s.email);

This depends on having a key that is truly unique and stable. If the source has no reliable key, build one deliberately, for example a hash of the fields that define a record, and test it for uniqueness.

3. Load to staging, then swap

Write the whole result to a temporary table, validate it, then switch it into place in one step. If anything goes wrong, the live table is untouched. This is a good option for smaller tables that you can rebuild in full.

4. Append with deduplication on read

Keep an append-only raw layer and remove duplicates when building the clean layer, for example by keeping the latest record per key. This preserves a full audit trail and is common in layered designs, but you must apply the dedupe logic consistently, or reports will disagree.

PatternBest forMain risk
Overwrite partitionTime-based facts and eventsLate data landing in an old partition after it was replaced
Merge on keySlowly changing records, dimensionsNon-unique or changing keys
Staging and swapSmall to medium tablesCost of rebuilding in full
Append and dedupeAudit trails, raw layersInconsistent dedupe rules downstream

The right model for your tables also depends on how you shape them. The ideas in our star schema modelling basics help decide which tables are facts to be partitioned and which are dimensions to be merged.

Running backfills safely

A backfill is a controlled reprocessing of past periods. Handle it as a planned operation, not as a loop in a notebook. A reliable approach:

  1. Define the range. Write down the first and last period, and the reason. Include the time zone, since "a day" differs between UTC and Irish local time, especially around clock changes.
  2. Test on a copy. Run one or two periods against a non-production target and compare results with known totals.
  3. Run period by period. Use your orchestrator to execute each window as its own idempotent task, with a limit on concurrency so you do not overload the source system or your own warehouse.
  4. Check upstream limits. Source APIs may rate-limit, and source systems may only keep recent data, so confirm that history still exists.
  5. Validate as you go. Compare row counts and key totals per period with the source, and spot-check individual records.
  6. Tell the consumers. Dashboards may change when history is corrected. A short note to report users avoids confusion. See BI dashboards people actually use for why trust in reports matters.
  7. Keep the code versioned. Record which version of the logic produced the backfilled data.

Handle dependent tables in order. If table B is built from table A, backfill A first, then B, or you will propagate stale numbers.

Handle late and duplicate data

Real data is messy. Events arrive late, sources resend records and systems occasionally emit the same record twice.

  • Late-arriving data. Decide how long you wait before closing a period, and re-process a rolling lookback window, such as the last few days, on every run. Your run then absorbs late corrections automatically.
  • Duplicates at source. Give each event a unique identifier at creation, and deduplicate on it. If the source cannot provide one, build a deterministic key.
  • Exactly-once claims. Messaging systems often guarantee at-least-once delivery. Treat that as a reminder to make consumers idempotent, rather than assuming exactly-once behaviour.
  • Deletes. If source rows are deleted, a merge that only inserts and updates will keep them forever. Decide whether to use soft-delete flags, full snapshots or change feeds.

Where records contain personal data, bear in mind that rebuilding and retaining history interacts with retention and erasure duties under GDPR. A pipeline that reprocesses old raw data could resurrect records that should have been removed, so align it with your policies, such as those in GDPR logging and retention. This is not legal advice.

Common mistakes

  • Using "now" inside the job. Current timestamps in filters make reruns return different data.
  • Appending without a key. Every retry adds another copy.
  • Partial writes. A job that fails after writing half its output and has no cleanup leaves the target inconsistent.
  • Non-deterministic dedupe. "Keep one row per customer" with no ordering picks arbitrarily.
  • Ignoring time zones. Daily windows that do not match business days cause mismatches with finance reports.
  • No validation. If nobody compares counts and totals, a silent duplicate can sit in production for months.
  • Unbounded backfills. Launching hundreds of parallel runs can degrade production systems.

Add tests that run the same job twice on the same input and assert that the target is unchanged. It is a small test with a large payoff, and fits the engineering habits found in our guide to CI pipelines. For feeding data between business systems, API integration best practices cover the same retry and duplicate concerns at the integration layer.

What to do next

Choose one important pipeline and review it against the principles above: Is the run defined by an explicit window? Does the write replace or merge deterministically? Can you run it twice without changing the result? Fix the weakest point first, add a double-run test, and document how to backfill a period. Then repeat for the next pipeline.

If you would like help with this, the CloudWiss team in Dublin can talk it through, from reviewing existing jobs to designing a reliable load pattern. Read more about our data engineering and analytics services.

Share this article

General educational information, not legal or professional advice for your specific situation.

Frequently asked questions

What does idempotent mean for a data pipeline?

Running the job once or many times on the same input gives the same final result. This makes retries and reruns safe because they never create duplicates or double counts.

Is MERGE always better than overwriting a partition?

No. Overwriting a partition is simpler and robust for time-based facts, while merge suits records that change and have a stable key. Choose by table type.

How do I handle late-arriving data?

Reprocess a rolling lookback window on each run, such as the last few days, so late corrections are absorbed. Decide when a period is final and document it.

How can I test that a pipeline is idempotent?

Run it twice on the same input in a test environment and assert that the target tables are unchanged after the second run. Add row count and total checks.

Keep reading

  • Data & AI6 min read

    Data Governance Basics for SMEs

    A practical, lightweight approach to data governance for small and medium businesses: owners, a data inventory, quality rules, access and retention.

  • Data & AI6 min read

    BI Dashboards People Actually Use

    How to design BI dashboards that get opened: start from decisions, trust the numbers, cut clutter, keep them fast, and avoid the common mistakes.

Let’s build it

Ready to build with CloudWiss?

Tell us what you want to build, move to the cloud or keep running. We reply with a clear next step.