How-To Guide

How to Implement Idempotent Data Loads

Make data loads safe to retry: upsert on a natural key, deduplicate within a batch, track load checkpoints, and test that a re-run changes nothing.

On this page

  1. Introduction
  2. Define a natural key
  3. Upsert on the natural key
  4. Deduplicate within the batch
  5. Track a checkpoint and resume
  6. Test that a re-run is a no-op
  7. Common pitfalls
  8. Conclusion

Introduction

Data loads fail halfway. A network drops, a source file is malformed, the process is killed, and the next run starts from a state that may partially overlap the previous one. A load that depends on it never having run before must be rerun from scratch, which is slow and risky. An idempotent load can be retried safely: running it once or five times leaves the same result.

This tutorial makes a data load idempotent with a natural key, an upsert, in-batch deduplication, and a checkpoint. It covers why a retry must not duplicate rows, how to match rows on reload, how to handle duplicate keys within a batch, and how to resume after an interruption. The examples use PostgreSQL upsert and COPY, but the principles apply to any loader.

Define a natural key

Idempotency rests on being able to recognize a row that was already loaded. That requires a natural key: a stable identifier in the source, such as a source system’s id, an order number, or a composite of fields that uniquely identify the record. With a natural key, a reload matches the existing row and updates it; without one, every load inserts a new row and there is no way to tell a duplicate from a new record.

Put a unique constraint on the natural key so the database can enforce uniqueness and so the upsert has a target. If the source has no natural key, derive one deterministically from the record’s content, such as a hash of its stable fields. A content hash also detects when a record’s content changed, which is useful for deciding whether to update at all.

CREATE TABLE load_target (
  source_id   text PRIMARY KEY,      -- the natural key from the source
  content     jsonb NOT NULL,
  content_hash text NOT NULL,
  loaded_at   timestamptz NOT NULL DEFAULT now()
);

Upsert on the natural key

Write each row with an upsert: insert on the natural key, and on conflict update the mutable columns. A retry that re-reads the same source row updates the existing row to the same values, which is a no-op in effect. The unique constraint plus the upsert is what turns an at-least-once delivery, typical of message systems and file reprocessing, into an effectively once load.

Update only when the content actually changed, using the content hash, so a reload of unchanged data does not rewrite every row and inflate the table or trigger downstream change detection. Skip the update when the stored hash equals the incoming hash, which keeps a large reload cheap and makes downstream consumers see only genuine changes.

INSERT INTO load_target (source_id, content, content_hash)
SELECT source_id, content, content_hash FROM staging
ON CONFLICT (source_id) DO UPDATE
  SET content = EXCLUDED.content,
      content_hash = EXCLUDED.content_hash,
      loaded_at = now()
WHERE load_target.content_hash <> EXCLUDED.content_hash;  -- no-op when unchanged

Deduplicate within the batch

A single insert statement cannot update the same target row twice, so if the batch contains two rows with the same natural key, the upsert raises an error. Deduplicate the batch before writing it: keep one row per key according to a rule that reflects the source’s intent, such as the latest by a source timestamp or the last occurrence in the file.

DISTINCT ON is a compact way to pick one row per key by an ordering. Apply it in the staging step so the write sees a unique key set. This also protects against a source that legitimately contains revisions within one delivery, where the later revision should win. Document the deduplication rule, because when two rows conflict the choice is a business decision, not an accident.

-- keep the most recent revision per source_id before the upsert
INSERT INTO load_target (source_id, content, content_hash)
SELECT DISTINCT ON (source_id)
       source_id, content, content_hash
FROM staging
ORDER BY source_id, source_updated_at DESC
ON CONFLICT (source_id) DO UPDATE
  SET content = EXCLUDED.content, content_hash = EXCLUDED.content_hash, loaded_at = now();

Track a checkpoint and resume

For a long load, record how far it progressed so a resumed run continues instead of reprocessing everything. The checkpoint might be the last source offset, the last file processed, or the maximum source timestamp written. Persist it in the same transaction as the rows it covers, so the checkpoint never claims more progress than was committed. Then a resume continues after the last committed point.

Idempotency and the checkpoint work together. The checkpoint avoids redoing committed work; the upsert makes redoing it harmless if the checkpoint lags. Even without a checkpoint, an idempotent load can simply be rerun from the start, just slower. Add the checkpoint for efficiency and keep the upsert for safety, so neither the fast path nor the recovery path is wrong.

CREATE TABLE load_checkpoint (
  source    text PRIMARY KEY,
  offset    text NOT NULL,
  updated_at timestamptz NOT NULL DEFAULT now()
);
-- persist the checkpoint in the same transaction as the load
BEGIN;
INSERT INTO load_target (source_id, content, content_hash) SELECT ... ON CONFLICT ...;
UPDATE load_checkpoint SET offset = $1, updated_at = now() WHERE source = 'orders';
COMMIT;

Test that a re-run is a no-op

Load a batch and record the row count and a checksum. Load the same batch again and assert the count and checksum are unchanged, and that loaded_at did not move for unchanged rows. Interrupt a load partway, resume, and assert the final state equals a single complete load. Load a batch with a duplicate key and assert the deduplication keeps the intended row rather than erroring or duplicating.

psql -d app <<'SQL'
-- run the same load twice
SELECT count(*), md5(string_agg(source_id || content_hash, ',' ORDER BY source_id)) FROM load_target;
-- after re-running the identical batch, this checksum must be identical
SQL

Common pitfalls

Inserting without a natural key so retries duplicate, an upsert that fails because the batch has duplicate keys, updating every row on reload so unchanged data churns, a checkpoint committed before the rows it covers, and testing only a single successful run are the recurring mistakes. A natural key with a unique constraint, in-batch deduplication, a content-hash guard, a transactional checkpoint, and a re-run test address them.

Conclusion

An idempotent load can be retried safely. Define a natural key with a unique constraint, upsert on it, update only when the content changed, deduplicate the batch before writing, and track a checkpoint in the same transaction as the data. Self-check by asserting that running the same load twice leaves the count and checksum unchanged and that a resumed load equals a complete one. Then a failed load is a retry, not a cleanup.

Sources: PostgreSQL: INSERT … ON CONFLICT, PostgreSQL: DISTINCT ON and deduplication, PostgreSQL: COPY for bulk load.

FAQ

Why does an upsert fail with duplicate rows in one statement?
ON CONFLICT cannot update the same target row twice in a single command, so two rows in the same insert that share a key raise an error. Deduplicate the batch first, keeping one row per key by a defined rule such as the latest.
How do I make a load resumable?
Track a checkpoint, such as the last source offset or timestamp processed, and persist it as part of the transaction that writes the rows. A resumed run starts after the checkpoint, so it does not redo committed work and does not skip uncommitted work.

Related Examples