Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 2

Incremental Loads with Watermarks and Lookbacks

Build a watermark-based incremental load in PostgreSQL, watch it lose a late-committed row, then fix it with a lookback window, per-key deduplication, a guarded upsert and a watermark that moves only when the data commits.

Contentsand lesson path

What you will learn

  • Implement incremental loads with high-watermark columns, including a lookback window for late-arriving records and deduplication of repeats.

Prerequisites: Data Handling, SQL Fundamentals

01. The problem

A full load copies the whole source table on every run. It is simple and always correct, but its cost grows with the size of the table, not with the amount of change. An incremental load copies only what changed since the last run. To know what "since the last run" means, the pipeline stores a high watermark: the highest value of a change column, such as updated_at, that it has already loaded. The next run asks the source for rows above that value.

The idea is simple, but two things break it in practice. First, updated_at is usually set when a transaction starts writing a row, while other sessions see the row only when the transaction commits. A row can therefore appear in the source with a timestamp older than a watermark that has already moved past it. This is one kind of late-arriving data. Second, sources repeat themselves: a change feed may contain several versions of the same order, and a re-run reads some rows again. In this worked example you build the simple version, watch it lose a row, and then fix it.

You need the etl-lab PostgreSQL 17 container and the Python environment from Bulk Loading Without Row-by-Row Inserts (psycopg 3.3.9). If you removed the container, start it again with the docker run command from that lesson. Everything below runs in a new database, orders_inc. The source is a table that receives one row per change, like an API that returns "changes since". The target dw.orders keeps one current row per order, and dw.etl_state stores the watermark.

SQL · seed.sql
SET client_min_messages = warning;
DROP SCHEMA IF EXISTS source, dw CASCADE;
CREATE SCHEMA source;
CREATE SCHEMA dw;
-- The source appends one row per change, like an API "changes since" feed.
CREATE TABLE source.order_changes (
  order_id   int NOT NULL,
  status     text NOT NULL,
  amount     numeric(8,2) NOT NULL,
  updated_at timestamptz NOT NULL
);
INSERT INTO source.order_changes VALUES
  (1, 'placed',  20.00, '2026-11-02 09:00+00'),
  (2, 'placed',  35.00, '2026-11-02 09:10+00'),
  (1, 'paid',    20.00, '2026-11-02 09:15+00'),
  (3, 'placed',  12.50, '2026-11-02 09:30+00'),
  (4, 'placed',  80.00, '2026-11-02 09:40+00'),
  (2, 'paid',    35.00, '2026-11-02 09:50+00');
CREATE TABLE dw.orders (
  order_id   int PRIMARY KEY,
  status     text NOT NULL,
  amount     numeric(8,2) NOT NULL,
  updated_at timestamptz NOT NULL
);
CREATE TABLE dw.etl_state (
  pipeline  text PRIMARY KEY,
  watermark timestamptz NOT NULL
);
Terminal
docker exec etl-lab createdb -U postgres orders_inc
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < seed.sql
export DATABASE_URL=postgresql://postgres:[email protected]:55432/orders_inc

02. Step 1: The incremental job

The job below does five things inside one transaction. It reads the stored watermark; on the very first run there is none, so it uses -infinity and loads everything. It copies the rows above watermark minus lookback into a temporary batch table. It keeps only the newest version of each order with row_number(), because one INSERT ... ON CONFLICT statement may not update the same row twice. It upserts, with a guard that refuses to replace a newer target row with an older one. Finally, it saves the new watermark as the highest updated_at it actually read, and commits data and watermark together. The --lookback-minutes option starts at 0, which gives the simple version.

Python · incremental.py
"""Load changed orders since the watermark, minus a lookback window."""
import argparse
import os

import psycopg

EXTRACT = """
INSERT INTO batch
SELECT order_id, status, amount, updated_at FROM source.order_changes
WHERE updated_at > %(watermark)s::timestamptz - make_interval(mins => %(lookback)s)
"""
UPSERT = """
INSERT INTO dw.orders
SELECT order_id, status, amount, updated_at FROM (
  SELECT *, row_number() OVER (PARTITION BY order_id
                               ORDER BY updated_at DESC) AS rn
  FROM batch) latest
WHERE rn = 1                                   -- one row per key: the newest
ON CONFLICT (order_id) DO UPDATE
   SET status = EXCLUDED.status, amount = EXCLUDED.amount,
       updated_at = EXCLUDED.updated_at
 WHERE dw.orders.updated_at < EXCLUDED.updated_at   -- never go back in time
"""
SAVE_WATERMARK = """
INSERT INTO dw.etl_state VALUES ('orders', %s)
ON CONFLICT (pipeline) DO UPDATE SET watermark = EXCLUDED.watermark
"""

parser = argparse.ArgumentParser()
parser.add_argument("--lookback-minutes", type=int, default=0)
parser.add_argument("--fail-before-commit", action="store_true")
args = parser.parse_args()

with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
    row = conn.execute("SELECT watermark FROM dw.etl_state"
                       " WHERE pipeline = 'orders'").fetchone()
    watermark = row[0] if row else "-infinity"       # first run: load everything
    conn.execute("CREATE TEMP TABLE batch (LIKE dw.orders) ON COMMIT DROP")
    conn.execute(EXTRACT, {"watermark": watermark, "lookback": args.lookback_minutes})
    read, newest = conn.execute(
        "SELECT count(*), max(updated_at) FROM batch").fetchone()
    changed = conn.execute(UPSERT).rowcount
    if newest is not None and (row is None or newest > watermark):
        conn.execute(SAVE_WATERMARK, (newest,))   # same transaction as the data
    if args.fail_before_commit:
        raise SystemExit("simulated crash before commit")
    conn.commit()
    saved = conn.execute("SELECT watermark FROM dw.etl_state").fetchone()[0]
print(f"read {read} rows, upserted {changed}, watermark now {saved:%H:%M}")

03. Step 2: Lose a late row

Run the job, add the changes that happen after it, and run it again. In later_changes.sql, order 3 is paid at 10:05, a normal change. Order 5 is the late row: the application stamped it 09:45, but its transaction committed only at 10:06, after the first run had read everything up to 09:50.

SQL · later_changes.sql
-- After run 1: a normal change, and a late row. Order 5 was stamped 09:45 by a
-- transaction that only committed at 10:06, after run 1 had finished.
INSERT INTO source.order_changes VALUES
  (3, 'paid',    12.50, '2026-11-02 10:05+00'),
  (5, 'placed',  44.00, '2026-11-02 09:45+00');
Terminal
python incremental.py
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < later_changes.sql
python incremental.py
Expected output
read 6 rows, upserted 4, watermark now 09:50
read 1 rows, upserted 1, watermark now 10:05

The first run read 6 change rows but upserted 4, one per order, because orders 1 and 2 each had two versions. The second run read only the 10:05 row. Nothing failed, so nobody would notice. A reconciliation query compares the latest version of each order in the source with the target, and finds the gap.

SQL · reconcile.sql
-- Latest version of each order in the source that the target does not match.
SELECT s.order_id, s.status AS source_status, d.status AS target_status
FROM (SELECT DISTINCT ON (order_id) * FROM source.order_changes
      ORDER BY order_id, updated_at DESC) s
LEFT JOIN dw.orders d USING (order_id)
WHERE d.order_id IS NULL OR d.updated_at <> s.updated_at
ORDER BY s.order_id;
Terminal
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < reconcile.sql
Expected output
 order_id | source_status | target_status 
----------+---------------+---------------
        5 | placed        | 
(1 row)

Order 5 is missing, and it will stay missing: every future run asks for rows newer than 10:05, and order 5 will never be newer than that unless it changes again.

04. Step 3: Add a lookback window

A lookback window makes each run start a fixed time before the watermark, so that rows which became visible late are read on the next run. The window must be longer than the longest delay you expect between a row being stamped and being committed, plus any clock difference between the machines that write updated_at. Ask the source team how long their longest transactions run, then add a margin. Here the late row was 21 minutes late, so 30 minutes is enough. Reset the database with seed.sql and replay the same history with a 30-minute lookback.

Terminal
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < seed.sql
python incremental.py --lookback-minutes 30
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < later_changes.sql
python incremental.py --lookback-minutes 30
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < reconcile.sql
Expected output
read 6 rows, upserted 4, watermark now 09:50
read 5 rows, upserted 2, watermark now 10:05
 order_id | source_status | target_status 
----------+---------------+---------------
(0 rows)

The second run now starts at 09:20 and reads five rows: the new 10:05 change, the late order 5, and three rows it had already loaded. It upserts only 2 of them. The deduplication step reduces the batch to one row per order, and the guard dw.orders.updated_at < EXCLUDED.updated_at turns the three repeats into no-ops, because the target already holds those exact versions. The reconciliation query returns no rows. Run the job once more without any new changes: it re-reads the window and changes nothing, so a lookback is safe to repeat.

Expected output (python incremental.py --lookback-minutes 30)
read 4 rows, upserted 0, watermark now 10:05

05. Step 4: Crash before the commit

The watermark is a promise: "everything up to here is safely in the target". If the job saved it in a separate step, a crash between the two would break the promise. Here, order 4 is paid at 10:20 and the job crashes after the upsert but before commit().

SQL · crash_change.sql
INSERT INTO source.order_changes VALUES (4, 'paid', 80.00, '2026-11-02 10:20+00');
Terminal
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < crash_change.sql
python incremental.py --lookback-minutes 30 --fail-before-commit; echo "exit code $?"
docker exec -i etl-lab psql -U postgres -d orders_inc -X -q < reconcile.sql
Expected output
simulated crash before commit
exit code 1
 order_id | source_status | target_status 
----------+---------------+---------------
        4 | paid          | placed
(1 row)

The transaction rolled back, so both the upsert and the new watermark disappeared together: the target still shows order 4 as placed, and the stored watermark is still 10:05. The next normal run therefore reads the change again and repairs the gap.

Expected output (python incremental.py --lookback-minutes 30, then reconcile.sql)
read 5 rows, upserted 1, watermark now 10:20
 order_id | source_status | target_status 
----------+---------------+---------------
(0 rows)

This works because the watermark lives in the same database as the target. When the target is a set of files or a different system, write the data first and the watermark last, and make the data write idempotent (the next lesson covers how), so a crash in between leads to a harmless re-read rather than a gap. Watermarks also have blind spots. A hard-deleted source row has no updated_at to select, so the target keeps it for ever; you need a soft-delete flag, a periodic full comparison, or change data capture from the database log, which the Change Data Capture skill covers.

06. Check your understanding

Practice check · 3 questions

Watermarks in practice

Each question changes one detail of the worked example. Pick the best answer.

Q1. The job uses a 30-minute lookback. A row stamped 09:10 commits at 10:06, and the stored watermark is 09:50. What does the next run do with it?
Q2. Order 3 is deleted from the source with `DELETE`. What does the watermark job do about it on later runs?
Q3. Two change rows for order 7 have exactly the same `updated_at`, one with status paid and one with refunded. Which one does the deduplication step keep?
Practice only: not graded, not saved, not evidence.

07. Apply it

In the skill practice, make the PostgreSQL table incremental. Store a watermark per source in a state table, read with a lookback you can justify from the source, reduce each batch to one row per business key with a tie-breaker, upsert with a "newer only" guard, and save the watermark in the same transaction. Add the reconciliation query as a check that runs after every load and fails the run if it returns rows.

08. Review prompt

Without looking back, explain: what a high watermark is and how the first run works; why a row can appear with a timestamp older than the watermark; how to size a lookback window; why the batch must be deduplicated and the upsert guarded; and why the watermark is saved in the same transaction as the data.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check