Building Incremental ETL with Watermarks
Extract only what changed since the last run with durable watermarks, handle late data, and make reruns idempotent instead of duplicating rows.
On this page
Introduction
A full extract reloads everything every run, which is slow, expensive and increasingly impossible as the source grows. Incremental extraction reads only rows changed since the last successful run, tracked by a watermark such as an updated_at timestamp or a monotonic id. The gains are large, but so are the failure modes: a watermark that advances before the load commits loses data, and one that ignores late arriving rows silently drops them forever. Correctness lives entirely in how the watermark is chosen, advanced and made idempotent.
Why Full Reloads Stop Scaling
Reloading a growing table means the cost of each run grows with the whole history rather than with the change. Eventually the job no longer fits in the maintenance window, and teams respond by running it less often, which makes each run larger and the problem worse. Incremental extraction breaks that feedback loop by decoupling cost from total size. The price is a new class of bug: instead of being uniformly slow, the pipeline becomes fast and subtly wrong when the watermark is mishandled.
-- Durable watermark state, advanced in the same transaction as the load.
CREATE TABLE etl_state (
pipeline text PRIMARY KEY,
watermark timestamptz NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Read the window: strictly greater than the stored watermark.
WITH state AS (
SELECT watermark FROM etl_state WHERE pipeline = 'orders'
)
SELECT id, updated_at, amount
FROM source_orders, state
WHERE (updated_at, id) > (state.watermark, '\x00') -- composite boundary
ORDER BY updated_at, id;
Choosing a Watermark Column
A good watermark is strictly increasing, stable and present on every row. An updated_at timestamp set by the application is common but can be wrong if the clock skews or if updates do not touch it; a monotonic id is safer when rows are only inserted. Avoid columns that a later backfill might change, because rewriting history moves rows behind the watermark and they are never seen again. When no single column suffices, combine a high watermark with an overlap window and deduplicate downstream.
BEGIN;
-- Idempotent load keyed by the source primary key.
INSERT INTO dest_orders (id, updated_at, amount)
SELECT id, updated_at, amount FROM staging_orders
ON CONFLICT (id) DO UPDATE
SET updated_at = EXCLUDED.updated_at,
amount = EXCLUDED.amount;
-- Advance the watermark to the max actually processed, atomically.
UPDATE etl_state
SET watermark = (SELECT max_updated FROM staging_bounds),
updated_at = now()
WHERE pipeline = 'orders';
COMMIT; -- load and watermark commit together or not at all
Advancing the Watermark Safely
The watermark must advance only after the data it covers is durably loaded, otherwise a crash between reading and writing loses rows permanently. Store the watermark in the same transaction as the destination write so the two commit together, or use a staging table that records both. Read the old watermark, extract everything greater than it up to the new high value, load, then advance in one atomic step. Never advance on a failed run, and make the run idempotent so a retry after a partial load is harmless.
Handling Late Arriving Data
Rows can arrive with a timestamp older than the watermark because of clock skew, delayed replication or a backfilled batch. A strict greater-than watermark never sees them. Mitigate with an overlap window: reread the last few minutes or hours on each run and rely on an upsert keyed by primary key to absorb duplicates. For sources that can deliver arbitrarily late data, a separate reconciliation pass that compares source and destination counts catches what the window misses.
Making Loads Idempotent
The destination write must be an upsert or a merge keyed by a stable primary key so running the same batch twice yields the same table. Inserts alone duplicate rows on retry, which corrupts aggregates and confuses every downstream consumer. Use the source primary key, or a deterministic hash of it, as the merge key, and update all mutable columns from the incoming row. Idempotence is what makes retries and overlap windows safe rather than dangerous.
Boundary Conditions and Off By One
The boundary between runs is where bugs live. Use strictly greater than the stored watermark and store the maximum value actually processed, not the maximum seen, because unprocessed rows above a gap would be skipped. When two rows share the same timestamp, a greater-than filter can skip the second; store a composite watermark of timestamp plus id and compare lexicographically. Test the boundary explicitly with rows exactly at, just below and just above the watermark.
Monitoring Freshness and Volume
Incremental pipelines fail quietly: the job succeeds but extracts nothing because the watermark advanced too far, or extracts everything because it never advanced. Track rows processed per run, the watermark lag and the age of the newest row in the destination. Alert when the row count drops to zero unexpectedly or when the watermark stops advancing. These two signals catch most silent incremental failures before downstream users notice missing data.
Backfills and Schema Changes
A backfill deliberately reprocesses history, so it must run with the watermark frozen or with an explicit override range rather than the normal advance logic. Treat a source schema change as a data contract change: add columns in the destination before the source starts emitting them, and fail the load loudly when an unexpected column appears rather than dropping it silently. Record the schema version alongside the watermark so a rerun can be interpreted.
Testing the Pipeline
Test with a source you can mutate between runs: insert new rows, update existing ones, insert a late row and rerun, asserting the destination matches expectations each time. Include a simulated crash after load and before watermark advance to prove no rows are lost on retry. Verify idempotence by running the same window twice and asserting no duplicate keys. These tests exercise exactly the boundary that breaks in production.
Sources
Sources: PostgreSQL INSERT ON CONFLICT, PostgreSQL transactions, dbt incremental models.
FAQ
- Why not just use updated_at greater than the last run time?
- Clock skew, late arriving rows and duplicate timestamps can make that skip data. Prefer a composite watermark of timestamp plus id, add an overlap window, and upsert to absorb re-reads.
- How do I know an incremental pipeline is broken if it succeeds?
- Alert on rows processed per run, watermark lag and the age of the newest destination row. A run that processes zero rows or whose watermark never advances is the common silent failure.
Report a problem with this articleOpens a pre-filled issue on GitHub.