Change Data Capture (CDC) Patterns for Analytics Pipelines
Four ways to find the rows that changed in a source database, compared on deletes, source load, and access, with a trigger, a missed delete, and a MERGE run on PostgreSQL 16.
On this page · 18 sections
- Change data capture patterns compared
- The patterns on PostgreSQL 16: one table, four changes
- Trigger-based CDC: an audit table
- Timestamp (high-watermark) queries: the missed delete
- Full snapshot comparison
- Applying a batch of changes with MERGE
- Log-based CDC: reading the transaction log
- Debezium
- CDC features inside the warehouse
- Snowflake streams
- BigQuery CDC ingestion
- What to do with captured changes
- Frequently Asked Questions
- Does change data capture detect deleted rows?
- Is change data capture real time?
- What are the best practices for implementing change data capture in analytics pipelines?
- What performance considerations apply to change data capture?
- Primary sources and further reading
- Topic
- Data Modeling
- Category
- Fundamentals
Change data capture (CDC) is a set of techniques for finding the rows that were inserted, updated, or deleted in a source database since the last load, so a pipeline moves only those changes and not whole tables. There are four main change data capture patterns: log-based capture, which reads the database's transaction log; trigger-based capture, which writes each change to an audit table; timestamp (high-watermark) queries, which select rows modified after the last run; and full snapshot comparison, which compares the table with its previous copy. They differ in whether they see deletes, how much load they put on the source, and what access they need.
Change data capture patterns compared
| Pattern | How it detects changes | Sees deletes | Load on the source | What you need access to |
|---|---|---|---|---|
| Log-based | Reads the database's transaction log, in PostgreSQL the write-ahead log (WAL) | Yes | No table queries after the first copy. The log is kept until the consumer has read it | wal_level = logical, a replication slot, and a role allowed to replicate |
| Trigger-based | A trigger on each table writes one row per change to an audit table | Yes | One extra insert in every writing transaction | Permission to create tables and triggers in the source |
| Timestamp (high-watermark) query | Selects rows whose updated_at is later than the highest value already loaded | No | One query per run | Read access, and a timestamp that every writer maintains |
| Full snapshot comparison | Reads the whole table and compares it with the previous copy | Yes, as missing keys | A full table read on every run | Read access only |
The patterns on PostgreSQL 16: one table, four changes
The source is an application's customers table. The analytics copy, customers_current, was loaded once in full, so the highest updated_at it holds, the high watermark, is 2026-03-01 09:10:00.
create table customers (
customer_id integer primary key,
email text not null,
plan text not null,
updated_at timestamp not null
);
insert into customers values
(1, 'ana@example.com', 'free', '2026-03-01 09:00:00'),
(2, 'ben@example.com', 'pro', '2026-03-01 09:05:00'),
(3, 'cy@example.com', 'free', '2026-03-01 09:10:00');
create table customers_current as
select * from customers;
alter table customers_current add primary key (customer_id);
Trigger-based CDC: an audit table
A trigger is a function the database runs when a row is inserted, updated, or deleted. Trigger-based CDC uses one to copy every change into a change (audit) table with its operation: I, U, or D.
create table customers_changes (
op char(1) not null,
customer_id integer not null,
email text,
plan text,
updated_at timestamp,
change_id bigint generated always as identity primary key
);
create function capture_customer_change() returns trigger as $$
begin
if tg_op = 'DELETE' then
insert into customers_changes select 'D', old.*;
else
insert into customers_changes select left(tg_op, 1), new.*;
end if;
return null;
end;
$$ language plpgsql;
create trigger customers_capture
after insert or update or delete on customers
for each row execute function capture_customer_change();
The application then makes four changes.
update customers set plan = 'pro', updated_at = '2026-03-02 10:00:00' where customer_id = 1;
insert into customers values (4, 'dee@example.com', 'free', '2026-03-02 11:00:00');
update customers set plan = 'team', updated_at = '2026-03-02 11:30:00' where customer_id = 4;
delete from customers where customer_id = 2;
select change_id, op, customer_id, email, plan
from customers_changes
order by change_id;
change_id | op | customer_id | email | plan
-----------+----+-------------+-----------------+------
1 | U | 1 | ana@example.com | pro
2 | I | 4 | dee@example.com | free
3 | U | 4 | dee@example.com | team
4 | D | 2 | ben@example.com | pro
(4 rows)
All four changes are captured in order, including customer 4's short-lived free plan and the last values of the deleted row. The cost is that every write to customers is now two writes in one transaction. A rolled-back update left no change row, and the PostgreSQL documentation notes that a trigger raising an error aborts the write that fired it.
Timestamp (high-watermark) queries: the missed delete
The query-based pattern needs no trigger. Each run selects the rows modified after the watermark and stores the new maximum for the next run.
select *
from customers
where updated_at > '2026-03-01 09:10:00'
order by customer_id;
customer_id | email | plan | updated_at
-------------+-----------------+------+---------------------
1 | ana@example.com | pro | 2026-03-02 10:00:00
4 | dee@example.com | team | 2026-03-02 11:30:00
(2 rows)
Customer 4 appears only in its final state, and the deletion of customer 2 is missing, so the analytics copy would keep that customer. An update that does not set updated_at is missed the same way. A soft delete, where the source sets a deleted_at column and keeps the row, turns the delete into an update the query can see.
Full snapshot comparison
The fourth pattern compares the whole source table with the previous copy. A full join finds keys that exist on one side only and rows whose values differ.
select
customer_id,
case
when t.customer_id is null then 'I'
when s.customer_id is null then 'D'
else 'U'
end as op
from customers as s
full join customers_current as t using (customer_id)
where (s.email, s.plan, s.updated_at)
is distinct from (t.email, t.plan, t.updated_at)
order by customer_id;
customer_id | op
-------------+----
1 | U
2 | D
4 | I
(3 rows)
The delete is found without a timestamp column or a trigger. The comparison sees only net changes, and it reads every row on every run.
Applying a batch of changes with MERGE
MERGE inserts, updates, and deletes in one statement, but a target row should match at most one source row, so the batch is first reduced to the latest change per key.
merge into customers_current as t
using (
select distinct on (customer_id) *
from customers_changes
where change_id > 0 -- the last change_id already applied
order by customer_id, change_id desc
) as s
on t.customer_id = s.customer_id
when matched and s.op = 'D' then
delete
when matched then
update set email = s.email, plan = s.plan, updated_at = s.updated_at
when not matched and s.op <> 'D' then
insert (customer_id, email, plan, updated_at)
values (s.customer_id, s.email, s.plan, s.updated_at);
MERGE 3
select * from customers_current order by customer_id;
customer_id | email | plan | updated_at
-------------+-----------------+------+---------------------
1 | ana@example.com | pro | 2026-03-02 10:00:00
3 | cy@example.com | free | 2026-03-01 09:10:00
4 | dee@example.com | team | 2026-03-02 11:30:00
(3 rows)
The copy now matches the source. Merging all four change rows directly failed with duplicate key value violates unique constraint "customers_current_pkey", because customer 4 has two changes. Running the statement a second time reported MERGE 2 and changed nothing, so the step is idempotent: a batch delivered twice does no harm.
Log-based CDC: reading the transaction log
This pattern was not run for this article: the test server reports wal_level = replica and its configuration was left alone. What follows comes from documentation.
PostgreSQL's write-ahead log describes every change at the storage level, and logical decoding turns it into a stream of row changes a client can read. According to the PostgreSQL 16 documentation:
wal_levelmust be set tological.- A replication slot is one stream of changes, replayed to a consumer in the order they were made. It can resend recent changes after a crash, so the consumer has to tolerate duplicates.
- A slot keeps the WAL its consumer has not read, even when nothing is connected, so an abandoned slot uses up disk.
- A published table needs a replica identity, by default its primary key, for updates and deletes to be replicated.
- Schema changes (DDL) are not replicated.
Debezium
Debezium is a set of source connectors for Apache Kafka Connect, the framework that moves records into and out of Kafka. Its PostgreSQL connector reads the logical replication stream. On first connecting it takes a consistent snapshot, then writes a change event for every committed insert, update, and delete to a Kafka topic, by default one topic per table. Each event carries before and after row images and an op code: c (create), u (update), d (delete), or r (snapshot read). With the default replica identity, before holds at most the primary key columns.
Debezium's documentation lists what this offers over polling: every change is captured, deletes included, with no last-updated column in the data model. For modeling those events, see streaming data models with dbt and Kafka.
CDC features inside the warehouse
Snowflake streams
A Snowflake stream records the inserts, updates, and deletes made to a table in Snowflake. It does not read the source database. Snowflake's documentation compares it to a bookmark: it stores an offset and no data, and querying it returns the changes since that offset with the columns METADATA$ACTION (INSERT or DELETE) and METADATA$ISUPDATE. An update appears as a DELETE and INSERT pair. A standard stream returns net changes, an append-only stream tracks inserts only, and the offset advances only when a DML statement (one that writes data) consumes the stream.
BigQuery CDC ingestion
BigQuery applies the changes for you. A client streams rows through the Storage Write API with the pseudocolumn _CHANGE_TYPE set to UPSERT or DELETE, and BigQuery applies them to a table that declares a primary key, which it does not enforce. Pending changes are applied when the table is queried, or by background jobs at least once per interval if max_staleness is set. The result is a current-state table. Google's documentation points to Datastream for replicating transactional databases this way.
What to do with captured changes
CDC is one way to do the extract step of ETL or ELT. The modeling work that follows has three parts.
- Land them as an append-only change table. Keep one row per change with the operation, a position to order by (
change_idabove), and the row values, and never update it. Seed it with a full copy first: the change table above never mentions customer 3, who did not change. - Build the current-state table. Take the latest change per key and remove keys whose latest change is a delete, as the
MERGEabove does. In dbt this is an incremental model: dbt's documentation describes filtering for rows newer than the maximum already in the target table (a high watermark) and aunique_keythat updates existing rows instead of appending them. That is update or insert, so carry deletes as anis_deletedcolumn and filter on it. - Keep history. The change table already holds every version of every row. Turning versions into validity ranges is a Type 2 slowly changing dimension. If the source offers only its current table, dbt snapshots build that history by comparing on a schedule, which dbt's documentation calls a batch-based approach to change data capture.
Frequently Asked Questions
Does change data capture detect deleted rows?
Log-based and trigger-based capture record a delete as an event, and full snapshot comparison finds it as a key missing from the new copy. A timestamp query does not: in the example above, the deleted customer never appeared in the extract. dbt snapshots take no action on deleted rows unless hard_deletes is set to invalidate or new_record.
Is change data capture real time?
It depends on the pattern. Timestamp queries and snapshot comparisons are as fresh as their schedule, and dbt's documentation says snapshots are intended to run between hourly and daily. Debezium's documentation puts the delay of its change events in the millisecond range for MySQL or PostgreSQL. The changes still have to be loaded and transformed before a report shows them.
What are the best practices for implementing change data capture in analytics pipelines?
Apply changes in source order, by log position or sequence number, not arrival time. Store the last position applied and advance it only after the apply succeeds. Make the apply idempotent, because batches can arrive twice. Plan for schema changes: PostgreSQL logical replication does not carry DDL. Compare the copy with the source on a schedule to catch what the incremental path missed.
What performance considerations apply to change data capture?
Triggers add an insert to every write, timestamp queries add one query per run, and snapshot comparison reads the whole table each time. Log-based capture adds no queries, but PostgreSQL keeps WAL for a replication slot until its consumer has read it, so a stalled consumer uses up disk.
Primary sources and further reading
- Logical Decoding Concepts, PostgreSQL 16 documentation. WAL decoding, replication slots, and WAL retention.
- Logical Replication, PostgreSQL 16 documentation, with publications (replica identity), restrictions (no DDL), and configuration (
wal_level). - Trigger Functions, PostgreSQL 16 documentation. The audit trigger example.
- MERGE, PostgreSQL 16 documentation. One source row per target row.
- Debezium Features, Architecture, and connector for PostgreSQL. Capture versus polling, Kafka Connect, snapshots, and event fields.
- Introduction to streams, Snowflake documentation. Offsets, metadata columns, and stream types.
- Stream table updates with change data capture ingestion, Google Cloud.
_CHANGE_TYPE, primary keys, andmax_staleness. - Add snapshots to your DAG, dbt documentation.
hard_deletesand run frequency. - Configure incremental models, dbt documentation. The incremental filter and
unique_key.
The SQL was run on PostgreSQL 16 and the output is what it returned. Log-based capture was not run. Vendor pages were read in November 2026.
- dbt
Streaming Data Models with dbt and Kafka: Patterns That Work
Explore how to integrate dbt and Kafka for real-time data modeling. This guide covers architecture setup, pipeline automation, and maintaining data quality.
- Fundamentals
Change Data Capture (CDC) Patterns for Analytics Pipelines
Four ways to find the rows that changed in a source database, compared on deletes, source load, and access, with a trigger, a missed delete, and a MERGE run on PostgreSQL 16.
- Fundamentals
Natural Key vs Surrogate Key: Definitions, Examples, and When to Use Each
Learn the differences between surrogate and natural keys in databases. This guide covers their benefits, drawbacks, and when to use each type effectively.
Drill it in the exercise library.
Portfolio-ready builds on this topic.
- advanced · open →
SQL Survival Challenge: Last City on Earth
Emergency operations analytics: triage supplies, power, and threats to keep the Last City alive.
- advanced · open →
Zombie Virus - Phase 3: The Cure
Cohort & effectiveness analytics: measure a vaccine's impact on infections, survivors, and city resilience.
