Incremental loading and change data capture: load only what changed, without losing or doubling rows
TL;DR
Difficulty: Advanced
Loading only what changed is a promise that the piece by piece table equals a full rebuild. Keep it like this:
- Reload small tables in full. A full reload cannot drift.
- For a watermark on updated_at, take the upper bound from the database clock minus a settle margin, read back a lookback window and page by time stamp and key together.
- Apply changes with a deduplicated upsert that never overwrites newer data with older data.
- Give updates that skip updated_at and hard deletes their own fix: a trigger, soft deletes, or reloading all lines of a changed order.
- Measure how late your late data is before you pick a lookback.
- Use change data capture from the PostgreSQL log when you need deletes, every state or freshness in minutes, and watch the replication slot.
- Compare the incremental table with a full rebuild every week. The target is zero differences.
A full nightly copy is slow but honest. The moment you load only what changed, rows can go missing or appear twice without a single error message. This chapter walks through every trap, with working SQL, Python, dbt and Debezium examples from an invented homeware shop in Limerick.
Loading only what changed is where rows go missing
Every night, something copies data from the shop into the warehouse. The first version is almost always a full copy: take every row, replace yesterday's table, done. It is simple and it is correct. Then the tables grow, someone wants the numbers every hour instead of every morning, and the full copy starts to hurt. So you switch to loading only what changed since last time.
That switch is where most warehouses quietly start to lie. Not with an error message, but with an order that never arrives, a deleted basket line that never leaves, or a refund that is counted twice. The question this chapter answers is the one every data engineer meets sooner or later: how do I load only what changed without losing or doubling rows?
A few terms first, so nobody is left behind:
- A full load (or full reload) copies the whole table every time.
- An incremental load copies only the rows that changed since the last run.
- A watermark is the bookmark an incremental load keeps: "I have everything up to this point". Usually it is a time stamp such as
updated_at. - Change data capture (CDC) reads every insert, update and delete from the database's own change log instead of asking the tables what changed.
- An upsert updates a row if its key already exists and inserts it if not. In SQL this is usually a
MERGE. - Idempotent means that running the same load twice leaves the same result as running it once. It is the property that lets you rerun anything safely.
The previous chapter, ETL, ELT, batch and streaming, covered how data moves from source to warehouse. This one is about the hardest part of that journey: moving only the difference, and proving that the difference adds up to the whole. It assumes the layered design from raw, staging and clean layers: changes land in raw exactly as received, and everything downstream can be rebuilt from there.
Example: the nightly copy at Shannonside Home
Shannonside Home is the invented homeware shop in Limerick that runs through this whole series (shannonsidehome.example). Niamh owns it. Callum builds the shop and the data platform. The shop runs on Ruby on Rails and Solidus with PostgreSQL, and the warehouse is BigQuery in a European region.
Every figure for Shannonside in this chapter is invented for the example. Solidus keeps every basket as a row in spree_orders from the moment a visitor adds the first product, in the state cart, and only some of those rows ever reach complete. After five years, the tables Callum copies each night look like this:
| Table | Rows | Rows changed on a normal day |
|---|---|---|
spree_orders | 1,240,000 (118,800 completed orders, the rest baskets) | about 4,100 |
spree_line_items | 2,900,000 | about 5,600 |
spree_payments | 131,000 | about 140 |
spree_products | 1,400 | about 20 |
spree_variants | 4,600 | about 60 |
The nightly full copy of all five tables takes about nine minutes from a read replica of the shop database. It's grand, and nobody complains. Then Niamh asks for hourly sales during the Black Friday week, so she can move ad budget during the day. Twenty four full copies a day would read almost 103 million rows from the replica to pick up roughly 10,000 changes. That is the moment Callum starts thinking about incremental loads, and the moment the traps in this chapter become his problem.
How much of a table really changes
Before you build anything incremental, measure how much actually changes. The share of changed rows decides whether incremental loading is worth its complexity at all. See Foundations: ratios and rates for the basics.
where is the share of the table that changes per day, is the number of rows inserted, updated or deleted per day, and is the number of rows in the table.
The work each approach does per day follows from that:
where is the number of rows a full load reads per day, the number an incremental load reads, the number of runs per day, the overlap (lookback) each run reads again on purpose, and the time between runs. The overlap matters, and a later section explains why every honest incremental load has one. Both are rates per day, the same arithmetic as in Foundations: ratios and rates.
Example: Callum measures spree_orders
For spree_orders on a normal day:
So : about one row in 300 changes per day.
Hourly full loads would read:
So is almost 30 million rows a day for this one table.
Hourly incremental loads with a two hour overlap ( hours, hour) read each change about three times:
So is about 12,300 rows, roughly 2,400 times less work. For spree_products, with 1,400 rows, the same arithmetic says the full load reads 33,600 rows a day hourly, which is nothing. Callum writes the conclusion down before he writes a line of code: incremental for orders, line items and payments, full reloads for products and variants.
Full reloads are still the right answer more often than you think
A full reload has one property nothing else has: it cannot drift. Every run replaces the copy with the source as it is now. Deletes disappear, quiet fixes arrive, a changed business rule applies to all of history at once. Incremental loading gives that up in exchange for speed and lower load, so it has to earn its place.
Keep the full reload when any of these is true:
- The table is small. A few hundred thousand rows load in seconds, and the complexity of incremental code costs more than the compute it saves.
- The source has no reliable change marker. No
updated_at, or one that some code paths skip. - The source is a complete snapshot anyway. A supplier feed or a newsletter export that always contains everything is a full load by nature.
- Deletes matter and there is no other way to see them. A full copy is the simplest delete detector there is.
- The run fits comfortably in its window and nobody needs fresher data.
There is a useful middle way for snapshot sources: load the full snapshot into raw every day, and derive the changes yourself by comparing today's snapshot with yesterday's. That gives you inserts, updates and deletes from a source that only knows how to send everything.
Example: Shannonside's supplier feed
One of Shannonside's suppliers sends a complete XML feed of 380 products every morning. There is no change marker, and products that the supplier drops simply vanish from the file. Callum loads each file whole into a raw table with the file date, then compares the last two days in BigQuery:
-- BigQuery (GoogleSQL): derive changes from two daily snapshots
WITH today AS (
SELECT * FROM raw.supplier_feed WHERE feed_date = '2027-01-12'
), yesterday AS (
SELECT * FROM raw.supplier_feed WHERE feed_date = '2027-01-11'
)
SELECT
COALESCE(t.supplier_sku, y.supplier_sku) AS supplier_sku,
CASE
WHEN y.supplier_sku IS NULL THEN 'insert'
WHEN t.supplier_sku IS NULL THEN 'delete'
ELSE 'update'
END AS change_type
FROM today AS t
FULL OUTER JOIN yesterday AS y
ON t.supplier_sku = y.supplier_sku
WHERE y.supplier_sku IS NULL
OR t.supplier_sku IS NULL
OR TO_JSON_STRING(t) != TO_JSON_STRING(y);
On 12 January the result has 7 rows: 2 new products, 1 product the supplier dropped and 4 price changes. The comparison of the whole row as JSON catches any column that changed. In practice Callum compares only the business columns, because feed_date differs on every row by design. The output feeds the product history described in versioning, history and audit trails.
Incremental loading by high watermark
The most common incremental method is the high watermark. You remember the highest change time you have safely loaded, and next time you ask the source only for rows that changed after it. It needs nothing but a reliable updated_at column and somewhere to keep the bookmark.
Three details separate a watermark load that works from one that leaks rows:
- The watermark is the upper bound of the window you asked for, not the largest
updated_atyou happened to see. - The upper bound is now minus a settle margin, so rows still being written are left for the next run.
- Each run starts a little before the last watermark (the lookback), and the load is written as an upsert, so the overlap is harmless.
Order the extraction by updated_at and then the primary key, and page with the pair, never with OFFSET. That is called keyset pagination: each page asks for rows after the last pair it saw, so rows with identical time stamps can never fall between two pages.
-- PostgreSQL, run against a read replica of the shop database.
-- Solidus stores updated_at as timestamp without time zone, in UTC.
SELECT id, number, state, payment_state, shipment_state,
item_total, adjustment_total, total, currency,
user_id, completed_at, canceled_at, created_at, updated_at
FROM spree_orders
WHERE (updated_at, id) > (%(last_ts)s, %(last_id)s)
AND updated_at < %(high)s
ORDER BY updated_at, id
LIMIT 5000;
The loop around it keeps the state and only moves the watermark after the data has landed:
# Python 3 with psycopg 3: one incremental run for spree_orders
from datetime import timedelta
SETTLE = timedelta(minutes=10) # leave rows still being written for next time
LOOKBACK = timedelta(hours=2) # read this much again on purpose
def run(shop_conn, state, write_raw, query):
with shop_conn.cursor() as cur:
cur.execute("SELECT (now() AT TIME ZONE 'UTC') - %s", (SETTLE,))
high = cur.fetchone()[0]
low = state.get("spree_orders") - LOOKBACK
last_ts, last_id = low, 0
while True:
with shop_conn.cursor() as cur:
cur.execute(query, {"last_ts": last_ts, "last_id": last_id, "high": high})
rows = cur.fetchall()
if not rows:
break
write_raw("spree_orders", rows) # append to raw with load metadata
last_id, last_ts = rows[-1][0], rows[-1][-1] # id first, updated_at last
state.set("spree_orders", high) # only after every page has landed
If the run fails halfway, the watermark has not moved, so the next run reads the same window again. Because raw is append only and the clean layer is built with an upsert, reading a row twice changes nothing.
Example: the 2am run on 13 January
The stored watermark for spree_orders is 2027-01-13 00:50:00, from the 1am run. At 2am the database clock reads 02:00:04, so:
- The upper bound is
01:50:04(now minus 10 minutes). - The lower bound is
2027-01-12 22:50:00(watermark minus 2 hours). - The query returns 517 rows in one page. 341 of them were already loaded by earlier runs and simply overwrite themselves. 176 are new or changed.
- All 517 rows land in raw with the batch id and load time. Only then does the watermark become
01:50:04.
An order that was completed at 01:55 is not in this run, and that is correct. It sits in the next window, which starts at 23:50:04 and ends ten minutes before 3am.
The five traps of a watermark
The watermark idea is simple. The ways it leaks are not obvious, and none of them raises an error. Each trap below is something a real Rails and PostgreSQL shop does every day.
Trap 1: rows that commit after you have read past them
A row is stamped with its updated_at when the application saves it, but other readers can only see it when its transaction commits. PostgreSQL's default isolation level, read committed, means a query sees only data committed before the query began1. If PostgreSQL sets the time stamp itself, functions such as now() return the start time of the current transaction, not the moment it commits2.
So a slow transaction can write a row stamped 01:59:58 that only becomes visible at 02:00:30. A load that ran at 02:00:05 and moved its watermark to the largest time stamp it saw has already stepped past that row. The next run asks for rows after the new watermark, and the row is gone for good.
The settle margin and the lookback are the fix. Rows newer than now minus ten minutes are never read, so a transaction has ten minutes to commit before its rows are asked for, and every window overlaps the last one by two hours anyway.
Example: the slow stock import
On 14 January at 01:58 Callum's stock import updates 900 variants inside one transaction and commits at 02:01:40. A naive watermark load at 02:00 reads rows up to 01:59:59, sets the watermark to the largest updated_at it saw, 01:59:57, and finishes. The 900 rows stamped 01:58:xx become visible 100 seconds later, behind the watermark. They never load.
With the settle margin, the 2am run only reads up to 01:50:04 and the 3am run reads from 23:50:04 to 02:50:07. By then the import has long committed, and all 900 rows arrive.
Trap 2: ties on the boundary
Many rows can share one time stamp: a bulk update, a batch of line items written in one save, or a source that stores time only to the second. If you page with updated_at > :last and a page ends in the middle of a group of equal time stamps, the rest of the group is skipped. If you use >= without a key, you read the group twice and need an upsert to absorb it.
The Solidus tables store created_at and updated_at to the microsecond3, which makes ties rarer but not impossible, and older tables or other sources may only have seconds. Keyset pagination on the pair (updated_at, id) removes the problem completely.
Example: the voucher run
Callum's voucher job updates 12,000 orders with one UPDATE statement that sets updated_at to the same value. The extractor pages by 5,000 rows with updated_at > :last_ts. Page one ends at row 5,000, all with the same time stamp. Page two asks for rows strictly after that time stamp and gets none of the remaining 7,000. With (updated_at, id) > (:last_ts, :last_id), page two continues at the next id with the same time stamp, and all 12,000 rows load in three pages.
Trap 3: clock skew between machines
Rails sets updated_at from the clock of the application server that saved the record, not from the database. If one of three servers runs four seconds slow, its rows arrive in the database stamped four seconds in the past. If your upper bound comes from a different clock, or you use the largest time stamp seen as the watermark, those rows can land behind it.
Take the upper bound from the database clock, as the code above does, keep every server on network time, and make the lookback far larger than any skew you could plausibly have. A two hour lookback swallows a four second skew without anyone noticing.
Example: the slow server
App server three drifts 4 seconds behind after a host migration. An order saved there at real time 02:00:02 is stamped 01:59:58. The extractor's upper bound is 01:50:04 for the 2am run, so the order is not yet asked for, and the 3am run's window starts at 23:50:04. The order loads at 3am with its slightly wrong time stamp, and nothing is lost. Callum still fixes the clock, because the wrong time stamp also skews the hourly sales report by a few seconds.
Trap 4: updates that never touch updated_at
This is the trap that catches the most shops. In Rails, update_all sends one SQL UPDATE straight to the database, skips callbacks, and does not update updated_at4. update_columns skips callbacks too and only touches the time stamps when you ask it to5. Add a fix typed into a SQL console, a data migration, or a trigger, and you have rows that changed without telling anyone.
There are three fixes, from lightest to strongest:
- Set
updated_atyourself in every bulk update and every manual fix. A team rule, easy to forget. - Let the database set it, with a trigger on update, so no code path can skip it.
- Use change data capture, which reads changes from the database log and does not care about time stamps at all.
# Rails 8: update_all skips callbacks, so set updated_at explicitly
Spree::Address.where(id: invalid_phone_ids)
.update_all(phone: nil, updated_at: Time.current)
-- PostgreSQL: the database stamps every update, whichever code path ran it
CREATE OR REPLACE FUNCTION set_updated_at() RETURNS trigger AS $fn$
BEGIN
NEW.updated_at := clock_timestamp() AT TIME ZONE 'UTC';
RETURN NEW;
END;
$fn$ LANGUAGE plpgsql;
CREATE TRIGGER spree_addresses_set_updated_at
BEFORE UPDATE ON spree_addresses
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
The trigger uses clock_timestamp(), the actual time when the row is written, rather than now(), the start of the transaction, which shrinks the gap from trap 1. It does not close it, which is why the settle margin stays.
Example: the phone number clean up
About 2% of Shannonside's orders have a missing or invalid phone number. In January Callum runs a one off script that blanks 2,310 invalid numbers in spree_addresses with update_all, without setting updated_at. The shop is fixed. The warehouse still shows all 2,310 invalid numbers, and the data quality report from standardising values still counts them as a problem a month later. Nobody notices until the weekly comparison described later in this chapter reports 2,310 rows with different values between the incremental table and a full copy. Callum adds the trigger, reruns the fix with updated_at, and the next hourly load carries all 2,310 rows.
Trap 5: deletes leave no trace
A watermark asks "which rows changed?". A deleted row cannot answer, because it no longer exists. Whatever was loaded before stays in the warehouse forever, and its numbers stay in every total.
In Solidus, products and variants are soft deleted: they get a deleted_at time stamp and stay in the table6. Line items are not. When a customer removes a product from the basket, the spree_line_items row is deleted for real. The line item model does declare touch: true on its order7, so the parent order's updated_at moves whenever a line item is saved or destroyed. That gives you a clean fix: whenever an order changes, reload all of its line items and replace the order's old set in the warehouse.
-- BigQuery script: replace the line items of every changed order, atomically
DECLARE changed ARRAY<INT64> DEFAULT (
SELECT ARRAY_AGG(DISTINCT order_id) FROM raw_batch.spree_line_items
);
MERGE core.order_lines AS t
USING (SELECT * FROM raw_batch.spree_line_items) AS s
ON FALSE
WHEN NOT MATCHED BY SOURCE AND t.order_id IN UNNEST(changed) THEN
DELETE
WHEN NOT MATCHED THEN
INSERT ROW;
The batch here contains every current line item of each changed order, extracted by joining on the changed orders rather than by the line items' own updated_at. ON FALSE turns the MERGE into an atomic delete plus insert, which the BigQuery documentation describes for exactly this replace pattern8. INSERT ROW needs the batch table to have the same columns in the same order as the target. Orders that did not change are untouched.
Example: ghost lines in the basket report
Before the fix, Callum's line item load used a plain watermark on spree_line_items. Customers remove a good few products from their baskets, about 650 a week. Over eight weeks the warehouse collects 5,200 line items that no longer exist in the shop. Most belong to abandoned baskets and inflate the "added to basket" figures. But 312 belong to orders that went on to complete after the customer removed something, so the order lines report overstates sold items by 312 and item revenue by €10,296 (an average item price of €33 in the example). The chart below shows the two row counts drifting apart, week by week.
The drift is 0.17% of the table. Small enough to miss on a dashboard, large enough to put a wrong number in front of Niamh every single week.
Soft deletes make deletes visible
A soft delete replaces DELETE with an update that sets a flag or a time stamp, usually deleted_at. The row stays, the application hides it, and an incremental load sees the change like any other update. Solidus does this for products and variants with the discard gem's conventions6.
For a warehouse, soft deletes are the friendliest design there is, with three rules attached:
- Carry
deleted_atinto staging and filter on it in the marts, never earlier. A mart can then choose whether "products sold last year" includes products discontinued since. - Do not soft delete personal data you are obliged to erase. A row with
deleted_atset still holds the name and the address. Erasure needs a real delete, or an anonymising update, that flows through every layer. A later chapter in this series, on privacy engineering, covers how. - If you control the source, add soft deletes where hard deletes hurt you most. If you do not, you need one of the other fixes in this chapter.
Example: the discontinued lamp
On 15 January Niamh discontinues a table lamp. Solidus sets deleted_at on the product and on its three variants. The hourly load picks up four updated rows. The product dimension keeps the lamp with is_deleted = true. The sales mart for last year still shows the lamp's €13,380 of revenue, because it was real revenue. The live product catalogue view, which Niamh's merchandiser uses, filters is_deleted = false, so the lamp disappears there within the hour.
Applying changes with upserts and MERGE
Loading changed rows is half the job. The other half is applying them to the clean table without creating a second copy of a row that already exists. That is the upsert: update when the key exists, insert when it does not.
PostgreSQL offers INSERT ... ON CONFLICT DO UPDATE and, since version 15, the SQL standard MERGE9. Version 17 added WHEN NOT MATCHED BY SOURCE, which can act on target rows that have no partner in the source10. BigQuery has MERGE with all three kinds of clause8.
Both engines share one rule that catches every new pipeline: a single statement may not change the same target row twice. PostgreSQL raises a cardinality violation if an ON CONFLICT DO UPDATE would affect one row more than once11. BigQuery fails with "UPDATE/MERGE must match at most one source row for each target row"8. Because the lookback reads changes more than once, your batch will often hold two versions of the same order. Deduplicate the batch first, keeping the newest version.
The second rule protects you from going backwards. Only apply an incoming version if it is at least as new as the one you already have. Otherwise a rerun of an old batch, or two loads overlapping, can overwrite fresh data with stale data.
-- BigQuery (GoogleSQL): idempotent upsert of a batch of order changes
MERGE core.orders AS t
USING (
SELECT *
FROM raw_batch.spree_orders
WHERE TRUE
QUALIFY ROW_NUMBER() OVER (
PARTITION BY id ORDER BY updated_at DESC, _loaded_at DESC) = 1
) AS s
ON t.order_id = s.id
WHEN MATCHED AND s.updated_at >= t.updated_at THEN
UPDATE SET state = s.state,
payment_state = s.payment_state,
shipment_state = s.shipment_state,
total = s.total,
completed_at = s.completed_at,
canceled_at = s.canceled_at,
updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT (order_id, order_number, state, payment_state, shipment_state,
total, currency, completed_at, canceled_at, created_at, updated_at)
VALUES (s.id, s.number, s.state, s.payment_state, s.shipment_state,
s.total, s.currency, s.completed_at, s.canceled_at, s.created_at, s.updated_at);
The same in PostgreSQL, when the warehouse is PostgreSQL itself:
-- PostgreSQL: deduplicate the batch, then upsert with a freshness guard
INSERT INTO core.orders AS t
(order_id, order_number, state, total, completed_at, updated_at)
SELECT DISTINCT ON (id)
id, number, state, total, completed_at, updated_at
FROM raw_batch.spree_orders
ORDER BY id, updated_at DESC
ON CONFLICT (order_id) DO UPDATE
SET state = EXCLUDED.state,
total = EXCLUDED.total,
completed_at = EXCLUDED.completed_at,
updated_at = EXCLUDED.updated_at
WHERE t.updated_at <= EXCLUDED.updated_at;
The WHERE on the DO UPDATE is the freshness guard: an older version is simply skipped. If prices from the legacy import are still floating point numbers, cast them to NUMERIC in staging before they ever reach a MERGE. Data types, schemas and formats explains why a float total can never be trusted to match.
Example: order R482913704 arrives twice
The 3am batch contains two versions of order R482913704, because the two hour lookback overlaps the 2am window:
| id | state | payment_state | total | updated_at |
|---|---|---|---|---|
| 88231 | confirm | balance_due | 84.00 | 01:31:12.204511 |
| 88231 | complete | paid | 84.00 | 01:32:47.990132 |
Without the deduplication, BigQuery rejects the whole MERGE. With it, the QUALIFY keeps the second row only. The target already holds the confirm version from the 2am run, stamped 01:31:12, so the guard s.updated_at >= t.updated_at is true and the row becomes complete and paid. If someone reruns the 2am batch by mistake an hour later, the guard is false for this order and the complete row stays. The table ends up the same however many times the batches run, in whatever order. That is idempotence, and it is the same property that makes background jobs safe to retry, as the background workers article explains for Rails jobs.
Late arriving changes and lookback windows
Late data is a row that belongs to a period you have already processed. It is normal, not an error. The 3PL warehouse reports returns days after they happen. A refund arrives weeks after the order. And Google Analytics 4 keeps updating its daily BigQuery export tables: a table for a given date can receive late events for up to three more days, so the table for 1 January may change until 4 January12.
The fix is a lookback window in the transformation: every run rebuilds not only today, but the last few days or partitions too. The right length comes from measurement, not from a guess. Measure the lag between when something happened and when you received it, then pick a window that covers the lags you see, plus a margin. See Foundations: distributions for the idea of a cumulative share.
where is the share of late rows a lookback of days catches, is the delay of row in days, and is the number of rows observed.
Example: how late are the 3PL returns?
Shannonside's 3PL sends its returns in a daily CSV, semicolon delimited and in Windows 1252 encoding, and a return can appear in the file up to 5 days after the parcel arrived at the warehouse. Callum measures 90 days of returns: 535 return lines, each with the date the parcel arrived and the date of the file that first reported it.
A three day lookback catches:
So . The other 17.0%, 91 returns, would land in partitions the model no longer rebuilds, and the return rate for recent days would stay too low.
A five day lookback catches all 535, so of what Callum observed. He sets seven days, because 90 days without a six day delay does not prove the 3PL never takes six. The cost is trivial: about 6 return lines a day, rebuilt seven times each. Business rule cleaning covers the other half of late data: what to tell finance when a closed month changes.
Example: the GA4 events model
Shannonside's GA4 export writes about 110,000 events a day. Because a daily table can change for three more days, Callum's model rebuilds the last four days on every daily run. Each run therefore reads:
So each daily run reads events instead of , four times the minimum. A full rebuild of three years of the export would read about 120 million events every day. The lookback costs four times the bare minimum and saves about 270 times the full rebuild.
Change data capture from the database log
Every write to a PostgreSQL database is first recorded in the write ahead log (WAL), the journal the database uses to recover after a crash and to feed replicas. Logical decoding turns that log into a stream of row changes: this row was inserted with these values, that row was updated from these values to those, this one was deleted13. Change data capture tools read that stream.
CDC fixes, by design, every trap above. It does not depend on updated_at, so quiet updates, clock skew and ties do not matter. It sees deletes as events. It sees every intermediate state of a row, not just the last one. And it reads from the log instead of querying the tables, so the load on the shop database is small.
The moving parts in PostgreSQL:
wal_levelmust belogical, so the WAL carries enough information to decode row changes14. It can only be set at server start. The newest PostgreSQL documentation also describes logical decoding switching itself on when the first logical slot is created13, so check the documentation for the version you run. Managed services expose the setting as a flag.- A publication names the tables, and optionally the columns and rows, whose changes are published. Column lists and row filters arrived in PostgreSQL 1515.
- A replication slot remembers how far a consumer has read, survives crashes, and keeps the WAL the consumer still needs13.
REPLICA IDENTITYdecides what the log records about the old version of an updated or deleted row: by default only the primary key, withFULLevery column16.- The output plugin turns the decoded changes into messages.
pgoutputis built into PostgreSQL.
Two limits to know before you start. Schema changes (DDL) are not replicated, so a new column in the shop does not create itself in the warehouse17. And a publication that publishes updates and deletes must include the replica identity columns in any column list18.
-- PostgreSQL 15 or later: publish only what the warehouse needs
CREATE ROLE debezium WITH LOGIN REPLICATION PASSWORD 'change me';
GRANT SELECT ON spree_orders, spree_line_items, spree_payments,
spree_refunds, spree_return_items TO debezium;
CREATE PUBLICATION shannonside_warehouse FOR TABLE
spree_orders (id, number, state, payment_state, shipment_state,
item_total, adjustment_total, promo_total,
included_tax_total, additional_tax_total, total,
currency, user_id, completed_at, canceled_at,
created_at, updated_at),
spree_line_items, spree_payments, spree_refunds, spree_return_items;
The column list on spree_orders leaves out email, last_ip_address and special_instructions, and it keeps id, the replica identity. The warehouse never receives those personal details, and no privacy control costs less than data you never copied. That is data minimisation: personal data should be adequate, relevant and limited to what is necessary for the purpose, a principle in Article 5(1)(c) of the GDPR, which the Data Protection Commission sets out in its guidance on the principles of data protection19. This is general information and not legal advice. A later chapter in this series covers privacy engineering in pipelines in depth.
Example: one checkout, seen two ways
A customer adds two cushions to a basket at 7.14pm and pays at 7.21pm. In Solidus the order moves through the checkout states one by one, each step an update to spree_orders, plus inserts into spree_line_items and spree_payments.
| Time | Change | Seen by an hourly watermark | Seen by CDC |
|---|---|---|---|
| 7.14pm | order inserted, state cart | no | yes |
| 7.14pm | 2 line items inserted | no | yes |
| 7.16pm | one cushion removed (line item deleted) | no | yes, as a delete |
| 7.17pm | state address | no | yes |
| 7.18pm | state delivery | no | yes |
| 7.19pm | state payment, payment inserted | no | yes |
| 7.21pm | state complete, payment completed | yes, the final row only | yes |
The watermark load at 8pm sees one row per table, in its final state. CDC sees nine events. For revenue, the final state is all you need. For checkout analysis, how long people spend in each step and where they give up, only the events will do. That difference, and the deleted line item, is what decides whether CDC is worth its moving parts.
What a change event contains
Debezium is an open source CDC platform with a connector for PostgreSQL. Its documentation describes the change event in detail20. Each event has a key (the primary key of the row) and a value with four main parts:
before: the row before the change. For an insert it is null. For updates and deletes, what it holds depends on the table's replica identity: with the default, only the key columns are reliable, withFULLthe whole old row.after: the row after the change. Null for a delete.source: where and when the change happened, including the database, the table, the transaction id, the log position (lsn) and the commit time stamp in milliseconds.op: the kind of change,cfor create,ufor update,dfor delete,rfor a row read during the initial snapshot,tfor truncate.
Three details matter in practice. Large values that PostgreSQL stores out of line, in what it calls TOAST storage, are left out of an update event when they did not change and are not part of the replica identity, and Debezium puts a placeholder in their place, __debezium_unavailable_value by default20. Your loader must not overwrite a real value with the placeholder. Second, by default Debezium sends NUMERIC columns in a precise binary form, and decimal.handling.mode set to string sends them as text you can cast exactly20. Third, after a delete Debezium by default sends a tombstone, a message with the same key and an empty value, so that Kafka's log compaction can forget the key20.
Example: the update event for the cushion order
The cushion order from the checkout example is order 88407, R739205118. Shortened to the parts that matter, the event for it turning complete at 7.21pm on 15 January looks like this:
{
"before": { "id": 88407, "state": "payment", "payment_state": null, "total": "84.00" },
"after": { "id": 88407, "state": "complete", "payment_state": "paid", "total": "84.00",
"completed_at": 1800040867990132, "updated_at": 1800040867990132 },
"source": { "connector": "postgresql", "db": "shannonside_production",
"table": "spree_orders", "txId": 9184402, "lsn": 51874420344,
"ts_ms": 1800040868012, "snapshot": false },
"op": "u",
"ts_ms": 1800040868230
}
The before image is complete here because Callum set REPLICA IDENTITY FULL on spree_orders. With the default he would only get the id. total arrives as the string "84.00" because of decimal.handling.mode: string. The time stamps are microseconds since 1970, which is how Debezium encodes a microsecond precision timestamp column with the default time precision mode. The lsn is the position in the log, and it orders the changes of one row reliably, which the time stamps cannot.
Running Debezium without surprises
Debezium usually runs as a connector in Kafka Connect and writes each table's changes to a Kafka topic. If you do not run Kafka, Debezium Server streams the same events to other systems, Google Cloud Pub/Sub among them21. A managed alternative on Google Cloud is Datastream, a serverless CDC service that reads PostgreSQL and writes to BigQuery22. It saves you running anything, in exchange for less control and a separate bill.
A connector configuration for Shannonside, using the property names from the Debezium documentation20:
{
"name": "shannonside-shop",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"plugin.name": "pgoutput",
"database.hostname": "shop-db.internal",
"database.port": "5432",
"database.user": "debezium",
"database.password": "********",
"database.dbname": "shannonside_production",
"topic.prefix": "shannonside",
"table.include.list": "public.spree_orders,public.spree_line_items,public.spree_payments,public.spree_refunds,public.spree_return_items",
"publication.name": "shannonside_warehouse",
"publication.autocreate.mode": "disabled",
"slot.name": "shannonside_warehouse",
"snapshot.mode": "initial",
"decimal.handling.mode": "string",
"heartbeat.interval.ms": "60000",
"tombstones.on.delete": "false"
}
}
What each setting is for:
plugin.name: pgoutputuses PostgreSQL's built in output plugin, so nothing extra is installed on the database.publication.autocreate.mode: disabledmakes Debezium use the publication created above, with its column list, instead of creating one for all tables.snapshot.mode: initialreads every existing row once (asrevents) when the connector starts for the first time, then streams changes.heartbeat.interval.mssends a heartbeat every minute. Without it, a database where most writes happen in tables you do not capture lets the slot fall behind, and PostgreSQL keeps WAL it no longer needs20.tombstones.on.delete: falsebecause Callum's loader writes into BigQuery, not into compacted Kafka topics.
Debezium's documentation says each change is delivered exactly once in normal operation, but that while recovering from a fault the connector may emit duplicates, so it then delivers at least once20. Design for duplicates: the current state model below keeps the newest event per key, so a duplicate changes nothing.
The replication slot can fill your disk
The one CDC failure that can take down the shop itself is the slot. A slot keeps every piece of WAL its consumer has not confirmed, even when nothing is connected13. If the connector stops for a week, the WAL grows for a week. PostgreSQL's max_slot_wal_keep_size caps how much WAL slots may retain. The default, -1, means no limit14. With a limit, a slot that falls too far behind is invalidated instead of filling the disk, and the wal_status column of pg_replication_slots tells you which state a slot is in: reserved, extended, unreserved or lost23.
where is the number of days until the disk is full, the free disk space and the WAL the database writes per day. See Foundations: ratios and rates.
-- PostgreSQL: how much WAL is each slot holding back?
SELECT slot_name, active, wal_status,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
Example: the connector stops over Christmas
Shannonside's database volume has 60 GB free and writes about 3 GB of WAL a day in December. If the Debezium connector stops on 24 December and nobody looks:
So after days the disk is full and the shop stops taking orders. Callum sets max_slot_wal_keep_size to 30 GB, so the slot is invalidated after about 10 days of downtime instead, and the shop keeps running. He adds an alert when retained_wal passes 5 GB, which is less than two days of WAL. And he writes down the recovery: if the slot is ever lost, create a new slot and take a fresh snapshot, then compare the result with a full copy, as described in the last section of this chapter.
Landing change events and building the current state
Treat change events like any other raw data: append every event to a raw table exactly as received, with its load metadata, and never update or delete there. The current state of each table is then a query over the events: for each key, the newest event by log position, unless that event is a delete.
-- BigQuery (GoogleSQL): current state of spree_orders from the change log
CREATE OR REPLACE VIEW staging.spree_orders_current AS
SELECT * EXCEPT (op, source_lsn)
FROM (
SELECT after.*, op, source.lsn AS source_lsn
FROM raw.cdc_spree_orders
WHERE TRUE
QUALIFY ROW_NUMBER() OVER (
PARTITION BY key.id ORDER BY source.lsn DESC, _loaded_at DESC) = 1
)
WHERE op != 'd';
For a delete, after is null, so the key comes from the event key, which is why the view partitions by key.id. A duplicate event has the same lsn, so it does not matter which copy wins. Snapshot rows (op = 'r') behave like inserts. Because the raw change table keeps every event, you get the full history of every order for free, and the history chapter's type 2 tables can be built from it without snapshots.
As the table grows, build the current state incrementally too, with a lookback on _loaded_at. The same rules apply: deduplicate by key, keep the newest by lsn, apply deletes.
Example: three events, one row
For order 88407 the raw change table holds three events by 7.22pm: the insert as cart (lsn 51874401120), the update to payment (lsn 51874419876) and the update to complete (lsn 51874420344). The connector restarted at 7.40pm and sent the last event a second time. The view ranks the four rows by lsn, keeps one of the two copies of 51874420344, sees op = 'u', and returns one row: complete, paid, €84.00. If Callum later deletes this order from the shop, say because it turns out to be a staff test, a fifth event with op = 'd' arrives, ranks first, and the order disappears from the current view while its history stays in raw.
dbt incremental models and their strategies
dbt Core builds a model as incremental when you set materialized = 'incremental'24. On the first run, or with --full-refresh, it builds the whole table. On later runs the is_incremental() macro returns true, the model selects only new or changed rows, and dbt applies them to the existing table, which the model can refer to as {{ this }}.
How dbt applies the rows is the incremental strategy. The current documentation lists five built in strategies, and support depends on the adapter25:
| Strategy | What it does | dbt-postgres | dbt-bigquery |
|---|---|---|---|
append | Inserts the selected rows, no duplicate check | yes | no |
merge | Updates rows whose unique_key exists, inserts the rest | yes | yes |
delete+insert | Deletes rows with the incoming keys, then inserts | yes | no |
insert_overwrite | Replaces whole partitions | no | yes |
microbatch | Processes time based batches by event_time, with a lookback | yes | yes |
A few configuration rules from the documentation are worth knowing by heart24:
on_schema_changedecides what happens when columns change:ignore(the default),fail,append_new_columnsorsync_all_columns. None of them backfills values for old rows in a new column.mergewithout aunique_keybehaves likeappend, so it can double rows25.incremental_predicatescan limit how much of the existing table amergescans25.
That last one hides a trap of its own. If you restrict the target to, say, orders from the last 400 days, an older order that receives a refund today does not match any row inside the restricted target. The MERGE therefore inserts it as a new row, and the order now exists twice. Only use a predicate on the target when the incoming rows can never fall outside it.
-- models/marts/fct_orders.sql (dbt Core, BigQuery)
{{ config(
materialized = 'incremental',
incremental_strategy = 'merge',
unique_key = 'order_id',
on_schema_change = 'fail',
partition_by = {'field': 'order_date', 'data_type': 'date'}
) }}
with changed as (
select *
from {{ ref('stg_spree_orders') }}
{% if is_incremental() %}
-- read two hours behind the newest row already loaded
where updated_at >= (
select timestamp_sub(max(updated_at), interval 2 hour) from {{ this }}
)
{% endif %}
),
latest as (
select *
from changed
where true
qualify row_number() over (partition by order_id order by updated_at desc) = 1
)
select
order_id,
order_number,
date(completed_at) as order_date,
state,
payment_state,
total_gross,
refunded_amount,
is_test_order,
updated_at
from latest
where completed_at is not null
For the GA4 events, where whole days change for three more days, microbatch fits better. It needs an event_time column, a batch_size, a begin date for full builds, and an optional lookback in batches, which defaults to 126. On BigQuery it also needs partition_by26. The upstream model must declare its own event_time, or dbt scans it in full for every batch.
-- models/marts/fct_ga4_daily_events.sql (dbt Core, BigQuery)
{{ config(
materialized = 'incremental',
incremental_strategy = 'microbatch',
event_time = 'event_date',
batch_size = 'day',
begin = '2024-01-01',
lookback = 4,
partition_by = {'field': 'event_date', 'data_type': 'date'}
) }}
select
event_date,
event_name,
count(*) as events,
count(distinct user_pseudo_id) as users
from {{ ref('stg_ga4_events') }}
group by event_date, event_name
The model has no is_incremental() block, because microbatch filters the upstream model by event_time itself. A lookback of four batches covers the three days Google may still update, with one day of margin.
Example: Callum's first incremental run of fct_orders
On 18 January the newest updated_at in fct_orders is 2027-01-18 09:58:12. The 11am run selects rows from stg_spree_orders with updated_at at or after 07:58:12: 214 rows. Deduplication keeps 197. Of those, 161 match existing orders and are updated (state changes, refunds), 36 are new completed orders and are inserted. The other 118,900 or so rows of the table are not touched. If the run is repeated at 11.05am, the same 197 rows match, the same values are written, and the table is unchanged.
Backfills and reprocessing
A backfill rebuilds history: after a bug fix, a new column, or a changed business rule. Incremental models make this a deliberate act, because by design they only process recent rows. You have three ways to do it:
dbt run --full-refresh --select fct_ordersdrops and rebuilds the model from all of its source24. Simple and safe for tables of Shannonside's size.- For microbatch models, run a range of batches with
--event-time-startand--event-time-end. Both flags are needed together26. - For partitioned tables in general, rebuild the affected partitions only.
For anything that feeds finance, build the backfill next to the live table first, compare the two, and only then swap. Reporting on cleaned data covers how to tell people that last quarter's numbers just moved.
Example: the new test order rule
In January Callum tightens the rule that flags test and staff orders, from the business rule chapter. The incremental model would only apply it to orders that change from now on. The roughly 40 test orders a year from the past five years would keep their old flags. He builds fct_orders with --full-refresh into a development dataset, compares it with production, and finds 61 orders newly flagged as test orders, worth €4,620 of revenue across five years. Finance agrees the restatement, he swaps the tables, and the change log records the rule version and the date.
# dbt Core: rebuild one month of the GA4 model after a fix in stg_ga4_events
dbt run --select fct_ga4_daily_events \
--event-time-start "2026-12-01" --event-time-end "2027-01-01"
Testing that incremental equals full
Every incremental pipeline makes one promise: the table it builds piece by piece is the same as the table a full rebuild would give you. Test that promise directly, on a schedule. Build the full version into a separate dataset once a week, and compare the two key by key.
The comparison has four numbers: rows missing from the incremental table, rows that exist only in the incremental table, keys that appear more than once, and rows whose values differ. Hashing the business columns of each row makes the last one quick to compute.
-- BigQuery (GoogleSQL): does the incremental fct_orders equal a full rebuild?
WITH f AS (
SELECT order_id,
FARM_FINGERPRINT(TO_JSON_STRING(STRUCT(
state, payment_state, total_gross, refunded_amount, is_test_order))) AS h
FROM check_full.fct_orders
), i AS (
SELECT order_id,
FARM_FINGERPRINT(TO_JSON_STRING(STRUCT(
state, payment_state, total_gross, refunded_amount, is_test_order))) AS h
FROM marts.fct_orders
)
SELECT
COUNTIF(i.order_id IS NULL) AS missing_in_incremental,
COUNTIF(f.order_id IS NULL) AS extra_in_incremental,
COUNTIF(f.order_id IS NOT NULL AND i.order_id IS NOT NULL AND f.h != i.h) AS different_values,
(SELECT COUNT(*) - COUNT(DISTINCT order_id) FROM marts.fct_orders) AS duplicate_keys
FROM f
FULL OUTER JOIN i ON f.order_id = i.order_id;
Express the result as a drift rate, so a threshold can decide whether it is an alert. See Foundations: percentages.
where is the drift rate, , , and are the four counts from the query, and is the number of rows in the full rebuild.
For an order table the target is zero, not "small". Every non zero count names a trap from this chapter, and the rows themselves tell you which one. Test first applies to pipelines as much as to application code, and test driven development explained is where the habit comes from. A later chapter in this series covers testing data pipelines in full.
Example: the weekly check finds the phone numbers
On Sunday 24 January the weekly check on Shannonside's address table returns 0 missing, 0 extra, 0 duplicate keys and 2,310 different values, out of addresses.
So , far above the threshold of zero. A query for ten of the differing rows shows the same pattern every time: the phone number is blank in the full copy and invalid in the incremental one, and updated_at is weeks old in both. That is trap 4, the update_all from the clean up. Callum fixes it as described above, and the following Sunday the check returns four zeros.
Choosing the method for each source
There is no single right method for a whole warehouse. Each source gets the simplest method that cannot lose or double its rows, and the choice follows a short list of questions.
Then two rules for every method. Land the raw data unchanged and append only, so any mistake can be replayed. And run the weekly comparison against a full copy, because every method on this list can be broken by a change nobody told you about.
Example: Shannonside's loading plan
Callum's plan, source by source, with the reason for each choice:
| Source | Method | Why |
|---|---|---|
spree_orders, spree_payments, spree_refunds, spree_return_items | Watermark now, CDC in spring | Large, mostly reliable updated_at; CDC later for checkout steps and deletes |
spree_line_items | Reload all lines of every changed order | Hard deleted from baskets, but every change touches the order |
spree_products, spree_variants | Full reload hourly | 6,000 rows, soft deletes, costs nothing |
spree_addresses | Watermark plus the update trigger | Bulk fixes skipped updated_at |
| GA4 export | Microbatch, lookback of 4 days | Daily tables change for 3 more days |
| Google Ads and Meta cost | Pull a trailing window of days, replace by date | Recent days are provisional, so the window is measured like the 3PL lag |
| Stripe and PayPal settlement files | Append each file once, deduplicate on transaction id | Files never change, but can be downloaded twice |
| 3PL shipments and returns CSV | Append raw, deduplicate, 7 day lookback in models | Returns up to 5 days late |
| Supplier feeds | Full snapshot, derive changes by comparison | Complete files, no change marker |
| Newsletter export, marketing cost sheet | Full reload | Small, complete every time |
He starts with watermarks rather than CDC on purpose. A watermark with a settle margin, a lookback, an upsert and the update trigger is correct for revenue reporting, and it has no slot that can fill a disk. CDC comes in when Niamh wants checkout step analysis, and by then the weekly comparison is already running, so he will know at once if the switch changes any number. Running these loads every hour, with retries and alerts, is the subject of the next chapter in this series, on orchestration.
Conclusion
Loading only what changed is not a performance trick. It is a promise that the piece by piece table equals the whole, and every method has its own way of breaking that promise quietly. Reload small tables in full, because a full reload cannot drift. For a watermark, take the upper bound from the database clock minus a settle margin, read back a lookback window, page by time stamp and key together, and apply rows with a deduplicated upsert that refuses to go backwards. Remember the updates that skip updated_at and the deletes that leave nothing behind, and give each a fix. Measure how late your late data really is before you choose a lookback. Use change data capture when you need deletes, every intermediate state or freshness within minutes, and watch the replication slot as closely as the data. Above all, compare the incremental result with a full rebuild every week. The day that comparison stops returning zeros is the day you find out, before Niamh does.
