Full load or incremental

Part of the free LogicWiz Data Engineering course, Module 6: Batch pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is Thursday, 4:00 p.m. Nora puts the growth plan on the screen: 5 million orders by next year. Tonight's job will copy the whole orders table into the warehouse again: delete everything, insert everything. With 80 orders that takes a second. "At 5 million it runs for hours, and almost every row it copies did not change," she says. You fix that today. Two weeks later, one order goes missing.

You'll learn to

  • Choose between a full load and an incremental load
  • Load only changed rows with a watermark on `updated_at` or an id
  • Keep the watermark in a table and move it last
  • Explain how a slow transaction slips behind a watermark

Learn

Copy everything, every night

Tonight's job is called a full load (or full refresh): empty the copy, then copy the whole source again.

It is the simplest pipeline there is, and it has one great property. Whatever went wrong yesterday, today's copy is right, because it starts from scratch.

So a full load is the right choice when the table is small, like SwiftKart's 20 products or a list of countries. It is also the only choice when the source gives you no way to tell what changed.

A full load in Postgres

-- Empty the copy, then copy everything, in one transaction
BEGIN;
DELETE FROM dw.orders;
INSERT INTO dw.orders
SELECT * FROM orders;
COMMIT;

SELECT COUNT(*) AS rows_copied
FROM dw.orders;

Both statements sit inside one transaction, so other sessions keep seeing the old copy until COMMIT, then the new one. Nobody ever sees the table empty. All 80 orders are copied, changed or not.

The bill grows with the table

Now work it out for a big table: 500 million orders, about 250 bytes a row, and 0.1% of the rows change in a day. (The numbers are made up. The shape is real.)

  • The whole table: 500,000,000 x 250 bytes = 125 GB.
  • One day of changes: 0.1% of 500 million = 500,000 rows. 500,000 x 250 bytes = 125 MB.
  • Reading at 200 MB a second, the full load takes 125,000 MB / 200 = 625 seconds. The changes take under a second.

A full load pays for the size of the table, and it puts that read on the store's database every night. You want a load that pays for the size of the change.

What one night reads: 500 million orders, 0.1% changed

Bars compare the megabytes read each night by a full load, an incremental load and an incremental load with a two-day lookback; the full load is a thousand times larger.

Each bar is what one night reads. The red bar is 1,000 times the first green one. The third bar is a safety margin you will meet at the end of this lesson: reading three days of changes still costs almost nothing.

Ask only for what changed

An incremental load copies only the rows that are new or changed since the last run. For that, the source has to tell you what changed. Two signals are common:

  • an updated_at column that the app sets on every insert and every update (orders, customers);
  • an id that only goes up, for tables where rows are added and never changed (payments, events).

Think of a bookmark. You do not reread the book every evening: you start where you stopped. The pipeline keeps the highest value it has loaded so far. That value is the watermark (also called the high-water mark). The next run asks only for rows above it: WHERE updated_at > watermark.

A timeline of nightly incremental loads: each run picks the rows above the watermark, then moves the watermark to the newest row it loaded.

Press through a few nights and watch the watermark move to the newest row each run loaded. Ignore the late row for now: Lesson 6.4 is about it.

One incremental run, in order

Five steps in a row: read the watermark, ask the source for rows above it, upsert them by key, move the watermark to the newest row loaded, and commit; the next night starts from the new watermark.

Read it left to right (top to bottom on a phone). The SQL below does exactly these five steps.

An incremental load with a watermark table

-- The copy was last loaded on 7 June. What changed since?
SELECT COUNT(*) AS changed_rows
FROM orders
WHERE updated_at > (SELECT last_value FROM etl_watermark WHERE pipeline = 'orders');

BEGIN;
-- Insert new orders; update the ones the copy already has
INSERT INTO dw.orders
SELECT * FROM orders
WHERE updated_at > (SELECT last_value FROM etl_watermark WHERE pipeline = 'orders')
ON CONFLICT (order_id) DO UPDATE
SET status = EXCLUDED.status, updated_at = EXCLUDED.updated_at;
-- Move the watermark to the newest row now in the copy
UPDATE etl_watermark
SET last_value = (SELECT MAX(updated_at) FROM dw.orders)
WHERE pipeline = 'orders';
COMMIT;

SELECT pipeline, last_value, (SELECT COUNT(*) FROM dw.orders) AS rows_in_copy
FROM etl_watermark;

51 rows changed: 40 new orders and 11 older ones that were delivered or returned after the last run. ON CONFLICT (Module 2) updates an order the copy already has instead of adding a second row. Run it again in your head: the second run finds 0 changed rows.

What one night's run did

Before the runAfter the run
Watermark2025-06-07 21:47:402025-06-15 22:56:11
Rows read from the source51 (not 80)
Order 1024 in the copyplaceddelivered (updated)
Order 1041 in the copymissingcancelled (inserted)
Rows in the copy4080

The run touched only what changed. On a big table that is the difference between minutes and hours, and between a small bill and a large one.

The bookmark has to survive the night

The watermark is state: the one thing a pipeline must remember between runs. In a variable, it dies with the job. Keep it in a small table (or a file), one row per pipeline.

Two rules decide whether you can trust it:

  • Move it to the highest value you loaded: MAX(updated_at) of the data, not the time the job ran. Your server's clock is not the store's clock, and a row written while the job was running could fall in between.
  • Move it after the load succeeds, in the same transaction if you can. If the job dies half-way, the watermark still has its old value, and the next run reads the same rows again.

Remember: the watermark is the newest row you loaded, on the source's clock. It moves last, together with the data.

The same bookmark for an API, kept in a file

import json, os
import swiftkart_api as api

STATE = 'state.json'

def load_state():
    if os.path.exists(STATE):
        with open(STATE) as f:
            return json.load(f)
    return {'orders': '1900-01-01 00:00:00'}   # first run: everything

def save_state(state):
    with open(STATE, 'w') as f:
        json.dump(state, f)

def run_once(copy):
    state = load_state()
    rows, page = [], 1
    while page:
        resp = api.get_orders(page=page, page_size=20, updated_since=state['orders'])
        rows += resp['data']
        page = resp['next_page']
    for r in rows:
        copy[r['order_id']] = r                 # upsert by key
    if rows:
        state['orders'] = max(r['updated_at'] for r in rows)
        save_state(state)                       # only after the load
    return len(rows)

copy = {}
print('night 1 read', run_once(copy))
print('night 2 read', run_once(copy))
with open('data/orders.csv', 'a') as f:         # the shop changes two orders
    f.write('1081,5,2025-06-16 09:12:00,placed,USD,2025-06-16 09:12:00\n')
    f.write('1080,4,2025-06-14 07:35:24,shipped,USD,2025-06-16 10:05:00\n')
print('night 3 read', run_once(copy))
print('orders in copy:', len(copy), '| 1080 is', copy[1080]['status'])
print('watermark:', load_state()['orders'])

Night 1 has no state, so it starts from 1900 and reads everything: the first run of an incremental pipeline is a full load. Night 2 reads nothing. Night 3 reads exactly the two changes. save_state runs only after the rows are in the copy.

Three classic watermark bugs. (1) An id watermark on a table whose rows change: order_id > last_id never sees order 1003 being delivered. (2) >= with a plain INSERT: the row sitting exactly on the watermark is loaded again every night. (3) Moving the watermark before the load commits: if the load fails, those rows are skipped for good.

One order never arrived

Two weeks later Tess finds order 1102. The store says it shipped. The warehouse never heard about it. No run failed.

A watermark on updated_at makes a quiet assumption: once you have seen 02:00:00, nothing older can still appear. Postgres breaks that assumption.

When the app writes updated_at = now(), the row is stamped with the time its transaction started. But other sessions can see the row only when the transaction commits, and that can be seconds or minutes later. In between, the row sits in the past where nobody can see it.

now() is when the transaction started

BEGIN;
SELECT now() AS stamped_as, clock_timestamp() AS wall_clock;
SELECT pg_sleep(0.5);
-- half a second later, still inside the transaction
SELECT now() AS stamped_as, clock_timestamp() AS wall_clock;
COMMIT;

now() does not move inside a transaction; clock_timestamp() does. Every row this transaction writes with DEFAULT now() carries the first value, however long it runs before it commits. (The times you see depend on when you run it.)

How order 1102 slipped behind the watermark

A timeline in seconds after 01:59:50: transaction A stamps order 1102 at 01:59:58 but commits at 02:00:05, transaction B commits at 02:00:00, the extract at 02:00:01 sees only B and sets the watermark to 02:00:00, and the next run never asks for A.

  1. 01:59:58: transaction A starts. It updates order 1102 and stamps it updated_at = 01:59:58. It will not commit for seven seconds, and until then nobody else can see the row.

  2. 02:00:00: transaction B. A quick update to order 1103. It is stamped 02:00:00 and commits at once, so everyone can see it.

  3. 02:00:01: the extract runs. It sees only committed rows: B, not A. The newest updated_at it loaded is 02:00:00, so that becomes the watermark.

  4. 02:00:05: A commits. Order 1102 appears in the table, stamped 01:59:58. That is two seconds behind the watermark.

  5. The next run. It asks for updated_at > 02:00:00: the green bar. A's stamp is where its red bar starts, to the left of the green one. So order 1102 is skipped tonight, and on every night after.

The axis is seconds after 01:59:50, so second 10 is 02:00:00. A bar starts when a transaction stamps its row and ends when it commits.

Replay the race, then the fix

-- committed_at is hidden from a real extract: it only sees committed rows.
-- Run 1 at 02:00:01, previous watermark 01:55:00
SELECT order_id, updated_at
FROM src_orders
WHERE committed_at <= '2025-06-10 02:00:01' AND updated_at > '2025-06-10 01:55:00'
ORDER BY order_id;

-- Run 2 at 03:00:00 with the strict watermark run 1 saved (02:00:00)
SELECT order_id AS strict_run_2
FROM src_orders
WHERE committed_at <= '2025-06-10 03:00:00' AND updated_at > '2025-06-10 02:00:00';

-- Run 2 with a 5-minute lookback (then a merge on order_id)
SELECT order_id AS lookback_run_2
FROM src_orders
WHERE committed_at <= '2025-06-10 03:00:00'
  AND updated_at > TIMESTAMP '2025-06-10 02:00:00' - INTERVAL '5 minutes'
ORDER BY order_id;

Run 1 reads 1101 and 1103 and saves 02:00:00. The strict run 2 reads only 1104: order 1102 is never loaded. The run with a 5-minute lookback rereads 1101 and 1103 (harmless with a merge) and catches 1102.

Three ways to close the hole

1. Look back. Ask for rows a little below the watermark: more than your longest transaction, plus any clock difference between servers or delay on a read replica (both cause the same hole). The rows you reread are harmless if the load merges on the key (Lesson 6.4). It is cheap, and it is the usual default.

2. Read only settled time. Stop the read at run_start - margin, say 10 minutes ago, and save that upper bound as the new watermark instead of MAX(updated_at). Newer rows wait for the next run. This is safe only if no transaction lives longer than the margin.

3. Read in commit order. A change log lists changes in the order they committed, so this race cannot happen. That is log-based CDC, in Lessons 6.5 and 6.7.

Remember: a lookback must be longer than the longest transaction. A shorter one only makes the hole smaller.

Numbers to remember

NameValueWhat it is
now()the transaction's start timeWhat DEFAULT now() or a trigger stamps on updatedat. clocktimestamp() is the real clock
transactiontimeoutPostgres 17 and later; default 0 (off)Ends a transaction that runs too long, so a "settled time" margin can be trusted
idleintransactionsessiontimeouta Postgres settingEnds a session that sits idle inside an open transaction: the other way to enforce the margin
LSNa position in the change logLog-based CDC reads changes in commit order by LSN (Lessons 6.5 and 6.7)
Index on updatedatneeded on the sourceWithout it, the database scans the whole table to find the changed rows
First runwatermark 1900-01-01 00:00:00With no state, an incremental load reads everything: its first run is a full load
Watermark copyAzure Data FactoryA Lookup reads the old watermark, a Copy activity pulls WHERE updatedat old, a stored procedure writes the new one
CursorFivetran, AirbyteTheir name for the watermark. They keep it for you
CheckpointDatabricks Auto LoaderRemembers which files it has already read: the same idea for files

The story needs only the first row. The rest are the names you will meet when you build this for real.

What changed at SwiftKart

The nightly job now reads 51 rows instead of the whole table, and at 5 million orders it will still read only the day's changes. The watermark lives in etl_watermark and moves in the same transaction as the load. The read looks back 5 minutes, so a slow transaction like order 1102's is caught on the next run.

A watermark still cannot see two things: rows that arrive days late (Lesson 6.4) and rows that are deleted (Lesson 6.5).

And the lookback reads some rows twice on purpose. That is only safe if loading a row twice does no harm. Lesson 6.3 runs a load twice and finds out.

In one line

A full load copies the whole table every night; an incremental load reads only the rows above a watermark, which lives in a table, moves after the load and is read with a small lookback.

Interview corner

Full load or incremental load: how do you choose?

A full load is simplest and self-healing, so I use it for small tables or sources with no reliable change signal. For large tables I load incrementally on updated_at (or an increasing id for append-only data) with an upsert on the key. I often still schedule a periodic full refresh, say weekly, to catch anything the incremental logic missed, such as deletes.

How do you implement an incremental load, and where is the watermark stored?

Read the watermark from a state table, pull WHERE updated_at > watermark, upsert by key, then set the watermark to MAX(updated_at) of what was loaded, in the same transaction as the load where possible. The state lives in a table (or the orchestrator's store), never only in the job's memory.

An incremental extract on `updated_at` loses a few rows a week, always ones written by the nightly bulk job. What is happening?

The bulk job runs long transactions. Postgres stamps updated_at = now() with the transaction start, but the rows are only visible at commit, so an extract that runs during the transaction saves a watermark above their updated_at and the next run skips them. I would prove it by comparing the missing rows' updated_at with the job's transaction window. Fixes: a lookback longer than the longest transaction plus a merge, or a settled upper bound such as run_start - 15 minutes saved as the watermark with transaction_timeout enforcing the bound, or moving to log-based CDC, which is ordered by commit.

What can go wrong with a watermark on updated_at?

Rows can commit late with an older updated_at and fall below the watermark; some code paths may update a row without touching updated_at; clocks differ between servers; and deletes never show up at all. The fixes are a lookback window with a merge, checks against the source, and a CDC method for deletes.