# Change data capture with Debezium and Kafka Connect, applied safely with MERGE

Change data capture streams every insert, update and delete from a database log instead of copying whole tables. This guide follows one PostgreSQL row from the write-ahead log through Debezium and Kafka to a warehouse table, and shows a MERGE that survives duplicates and replays.

Copying a production table into a warehouse every night is simple until the table gets big, the night gets short, or someone needs the data within minutes. Change data capture (CDC) solves this by reading the database's own change log and sending only what changed: each insert, update and delete, in commit order. The database does the work it already does for replication, and your pipeline receives a stream of small events instead of a full copy.

This article explains log-based CDC end to end with the most widely used open-source tool, Debezium, running on Kafka Connect. It follows one PostgreSQL row through the write-ahead log, a replication slot, a Debezium change event and a Kafka topic, and then shows how to apply those events to a warehouse table with a `MERGE` that stays correct when events arrive twice or a batch is replayed. The SQL runs as written in DuckDB 2.0.1.

## What happened

### Debezium 3.7.0.Final (29 September 2026)

The Debezium project released 3.7.0.Final. Its changelog lists, among other items, a dedicated single message transform that converts MongoDB events into relational-style structs, a lossless handling mode for MongoDB BSON timestamp values, an Oracle DDL rule called `modify_to_partitioned`, and a fix so that the Debezium Server Kafka sink uses the partition an SMT selects.

### Debezium 3.8.0.Alpha2 (19 November 2026)

Development of the next line continued with 3.8.0.Alpha2. The changelog lists support for managed initial snapshots in the TiDB connector, warnings when a write-ahead log search runs without advancing, and usability work on the table picker for large catalogs. Alpha releases are for testing, so production pipelines should stay on the Final line.

## How log-based CDC works

Every serious relational database writes changes to a log before it changes data files. PostgreSQL calls it the write-ahead log (WAL). The log exists for crash recovery and replication, and it already contains every committed change in order. Log-based CDC simply becomes one more reader of that log.

There are three broad ways to capture changes:

| Method | How it finds changes | Captures deletes | Load on source | Typical latency |
|---|---|---|---|---|
| Full reload | Copy the whole table | Yes, by comparison | High | Hours |
| Query-based (timestamp or id column) | `WHERE updated_at > last_run` | No, unless soft deletes | Medium, repeated scans | Minutes |
| Log-based | Read the transaction log | Yes | Low | Seconds |

Query-based capture is easy but misses hard deletes and any update that forgets to touch `updated_at`. Log-based capture sees everything the database committed.

### The PostgreSQL side

For PostgreSQL, Debezium uses logical decoding. The setup has three parts:

1. **`wal_level = logical`** so the WAL contains enough information to rebuild row changes.
2. **A replication slot**, which remembers how far the consumer has read. PostgreSQL keeps WAL segments until the slot confirms them.
3. **A logical decoding output plug-in.** The Debezium documentation describes `pgoutput` as the standard plug-in in PostgreSQL 10 and later. Note that the connector's `plugin.name` property defaults to `decoderbufs`, so set `pgoutput` explicitly if you want the built-in one. With `pgoutput`, Debezium recommends `publication.autocreate.mode = filtered` so the publication covers only the tables you capture.

The replication slot is the part that bites. Think of it as a bookmark the database must respect. If the connector stops for a weekend, PostgreSQL keeps every WAL segment written since the bookmark, and disk usage grows. The Debezium documentation also describes a quieter case: when captured tables change rarely but other tables are busy, the slot may not advance, and WAL piles up. Its recommended fix is periodic heartbeat events via `heartbeat.interval.ms`.

### REPLICA IDENTITY decides what "before" contains

PostgreSQL's `REPLICA IDENTITY` setting controls how much of the old row appears in update and delete events. With `DEFAULT`, update and delete events carry the previous values of the primary key columns only, and a table without a primary key produces only create events. With `FULL`, events carry the previous values of all columns. If you need to know what a field changed from, set `REPLICA IDENTITY FULL` on that table and accept the extra WAL volume.

## Anatomy of a Debezium change event

Debezium writes one event per row change to a Kafka topic named `topicPrefix.schemaName.tableName`. Each event has a key (the primary key) and a value. Simplified, the value of an update looks like this:

```json
{
  "before": { "id": 1, "email": "ana@example.com", "tier": "silver" },
  "after":  { "id": 1, "email": "ana@example.com", "tier": "gold" },
  "source": { "connector": "postgresql", "lsn": 130, "ts_ms": 1795400000000 },
  "op": "u",
  "ts_ms": 1795400000250
}
```

The `op` field is the most important one. Its documented values are `c` (create), `u` (update), `d` (delete), `r` (read, used only for snapshot rows), `t` (truncate) and `m` (message). The `source` block records where the change came from, including the log position. Comparing `source.ts_ms` (when the database made the change) with the top-level `ts_ms` (when Debezium processed it) gives you capture lag.

Two details catch people out. First, after a delete, Debezium by default emits a **tombstone**: an event with the same key and a null value, so that Kafka log compaction can eventually drop the key. Consumers must skip null values. Second, when a primary key value changes, Debezium emits a delete and a tombstone for the old key, then a create for the new key.

### Snapshots first, then streaming

A new connector cannot start from the beginning of time, because old WAL is gone. With the default `snapshot.mode = initial`, Debezium first reads the current contents of each captured table, emitting `r` events, and then streams changes from the log position it recorded. Other modes include `initial_only`, `no_data` (stream only, no snapshot), `when_needed` and `always`.

## Wiring it up with Kafka Connect

Kafka Connect runs connectors as managed tasks and stores their offsets in Kafka. A Debezium PostgreSQL source connector is configured with JSON posted to the Connect REST API:

```json
{
  "name": "crm-postgres",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "crm-db",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "${file:/secrets/crm.properties:password}",
    "database.dbname": "crm",
    "topic.prefix": "crm",
    "plugin.name": "pgoutput",
    "publication.autocreate.mode": "filtered",
    "slot.name": "debezium_crm",
    "table.include.list": "public.customers,public.orders",
    "snapshot.mode": "initial",
    "heartbeat.interval.ms": "60000"
  }
}
```

This produces topics `crm.public.customers` and `crm.public.orders`. A sink connector, or a stream processor, then writes the events to the lake or warehouse. Many teams add single message transforms to flatten the envelope so that each record is just the `after` row plus `op` and the log position.

## Applying changes: the idempotent MERGE

Kafka and Debezium give you an ordered stream per key, but not a promise that each event arrives once. The Debezium documentation is clear: in normal operation it delivers each change once, but while recovering from a fault it may emit duplicates, so it provides at-least-once delivery in those cases. Your apply step must therefore be **idempotent**: applying the same batch twice must give the same result as applying it once.

Here is a micro-batch of flattened events for a `customers` table. The target currently holds customers 1, 2 and 3, each with the log position (`updated_lsn`) of its last applied change.

```sql
CREATE TABLE customers (
  id INTEGER PRIMARY KEY, email VARCHAR, tier VARCHAR, updated_lsn BIGINT);
INSERT INTO customers VALUES
  (1, 'ana@example.com', 'silver', 100),
  (2, 'ben@example.com', 'gold',   110),
  (3, 'cem@example.com', 'silver', 120);

CREATE TABLE cdc_batch (lsn BIGINT, op VARCHAR, id INTEGER, email VARCHAR, tier VARCHAR);
INSERT INTO cdc_batch VALUES
  (130, 'u', 1, 'ana@example.com',   'gold'),
  (140, 'c', 4, 'deniz@example.com', 'bronze'),
  (150, 'u', 1, 'ana.k@example.com', 'gold'),
  (160, 'd', 3, NULL, NULL),
  (170, 'u', 4, 'deniz@example.com', 'silver'),
  (125, 'u', 2, 'ben@example.com',   'gold');
```

### Step 1: keep only the latest event per key

A batch can contain several changes to the same row. Customer 1 changed twice and customer 4 was created and then updated. Applying them in one `MERGE` would match one target row to several source rows. Deduplicate first:

```sql
CREATE TABLE latest AS
SELECT * FROM cdc_batch
QUALIFY row_number() OVER (PARTITION BY id ORDER BY lsn DESC) = 1;
```

This leaves four rows: customer 1 at position 150, customer 2 at 125, the delete of customer 3 at 160, and customer 4 at 170.

This step is not optional. The DuckDB 2.0.1 release notes describe exactly this hazard: when several source rows match the same target row, `MERGE` and `UPDATE ... FROM` apply every match, so the final value can be non-deterministic. Other engines raise an error instead. Either way, one row per key is the rule.

### Step 2: merge with a position guard

```sql
MERGE INTO customers AS t
USING latest AS s
ON t.id = s.id
WHEN MATCHED AND s.op = 'd' AND s.lsn > t.updated_lsn THEN DELETE
WHEN MATCHED AND s.op IN ('c', 'u', 'r') AND s.lsn > t.updated_lsn THEN
  UPDATE SET email = s.email, tier = s.tier, updated_lsn = s.lsn
WHEN NOT MATCHED AND s.op IN ('c', 'u', 'r') THEN
  INSERT (id, email, tier, updated_lsn) VALUES (s.id, s.email, s.tier, s.lsn);
```

The result is customer 1 with the new email at position 150, customer 2 at 125, customer 3 deleted, and customer 4 inserted as `silver` at 170. The `MERGE` reports 4 affected rows.

Now replay the same batch, as would happen after a crash between applying and committing the Kafka offset. The guard `s.lsn > t.updated_lsn` is false for every matched row and the deleted key no longer exists, so the second `MERGE` changes 0 rows and the table is identical. That is idempotency.

### The resurrection problem

One gap remains. Suppose an old update for customer 3, with position 120 or lower, arrives after the delete has been applied. The row is gone, so `WHEN NOT MATCHED` inserts it again: a deleted customer comes back to life. Two common fixes:

| Approach | How it works | Trade-off |
|---|---|---|
| Soft deletes | Keep the row with `is_deleted = true` and its position, so late events fail the guard | Table keeps deleted rows; queries must filter them |
| Delete log | Record deleted keys and positions in a side table and check it before inserting | Extra join on every batch |
| Strict ordering | Partition Kafka topics by primary key and process each partition in order | Late events become rare but not impossible after replays |

Debezium already keys Kafka records by primary key, so events for one row land in one partition in order. Soft deletes cover the remaining edge cases cheaply, and they also give downstream models a way to see what was removed.

## What it means in practice

Log-based CDC moves the hard parts from extraction to application. Extraction becomes cheap and complete. Application must handle duplicates, ordering, deletes and schema changes. Teams that treat the apply step as a simple `INSERT` end up with duplicate rows, zombie records and silent drift.

A sound design has four pieces: a connector that reads the log with a monitored replication slot; a topic per table, keyed by primary key; a raw landing table that stores every event unchanged; and a `MERGE` into the current-state table guarded by log position. The raw table is your audit trail and replay source, and it feeds history tables such as slowly changing dimensions.

The site's pages on [change data capture](/tools/change-data-capture), [Kafka Connect](/tools/kafka-connect), [single message transforms](/tools/single-message-transforms) and the [schema registry](/tools/schema-registry) go deeper on each part, and the [streaming topic page](/topics/big-data/streaming) shows where CDC fits in a real-time stack. Source databases such as [PostgreSQL](/tools/postgresql) need their own care, and [Apache Kafka](/tools/apache-kafka) retention settings decide how far back you can replay.

## What to do now

1. **Choose log-based capture for tables with deletes.** Query-based extraction cannot see hard deletes.
2. **Set `plugin.name` explicitly.** Use `pgoutput` on PostgreSQL 10 or later and `publication.autocreate.mode = filtered`.
3. **Monitor replication slot lag.** Alert when retained WAL grows, and set `heartbeat.interval.ms` for low-traffic tables.
4. **Decide on `REPLICA IDENTITY` per table.** Use `FULL` where you need old values for audits or history.
5. **Land raw events before merging.** Keep every event with its `op` and log position for replay and history.
6. **Deduplicate per key inside each batch.** Keep the latest event by log position before any `MERGE`.
7. **Guard every update and delete with log position.** Apply a change only if its position is newer than the stored one.
8. **Handle tombstones and key changes.** Skip null-value records and treat a primary key change as delete plus create.
9. **Test a replay.** Re-run yesterday's batch against a copy of the table and confirm nothing changes.

## Risks and open questions

**A stalled connector can fill the source database's disk.** The replication slot keeps WAL until it is confirmed, so connector outages need alerts, not just retries.

**At-least-once delivery after faults.** Duplicates are expected during recovery, so any non-idempotent apply step will eventually double-count.

**Schema changes arrive mid-stream.** A new column or changed type shows up in events before your target table knows about it; pair CDC with schema evolution rules.

**Snapshots of large tables take time.** The initial snapshot competes with production load and must finish before streaming catches up.

**Watch next:** what the Debezium 3.8 line adds before it reaches Final, and how open table formats make it easier to apply CDC merges at lake scale.

## Frequently asked questions

### What is the difference between CDC and an incremental load?

An incremental load queries the source for rows changed since the last run, usually by a timestamp column. Log-based CDC reads the database's transaction log, so it captures every committed change, including hard deletes, with lower load on the source.

### Does Debezium guarantee exactly-once delivery?

Its documentation says it delivers each change once in normal operation, but may emit duplicates while recovering from faults, so it provides at-least-once delivery in those situations. Design consumers to be idempotent.

### Why does my PostgreSQL disk fill up after adding Debezium?

The replication slot keeps WAL until the connector confirms it. If the connector stops or the captured tables rarely change, WAL accumulates. Monitor slot lag and enable heartbeat events.

### What is a tombstone event?

It is an event with the same key as a deleted row and a null value. Kafka log compaction uses it to remove the key eventually. Consumers should skip it rather than treating it as data.

### Why deduplicate before MERGE?

A batch can contain several changes to the same row. If several source rows match one target row, some engines raise an error and others, such as DuckDB 2.0.1, apply every match with a non-deterministic final value. Keeping the latest event per key avoids both.

## Summary

Log-based change data capture reads the database's own transaction log, so it captures every insert, update and delete with low source load and seconds of latency. Debezium on Kafka Connect turns PostgreSQL WAL into keyed change events with `before`, `after`, `source` and `op` fields, starting with a snapshot and then streaming. The apply side carries the real responsibility: deduplicate per key, guard every change with its log position, handle tombstones and late events, and prove idempotency with a replay. Debezium's 3.7.0.Final release in September and 3.8.0.Alpha2 in November 2026 continue to extend connectors without changing these fundamentals.

## Sources

- [GitHub: Debezium connector for PostgreSQL documentation](https://github.com/debezium/debezium/blob/main/documentation/modules/ROOT/pages/connectors/postgresql.adoc)
- [GitHub: Debezium CHANGELOG](https://github.com/debezium/debezium/blob/main/CHANGELOG.md)
- [Debezium: Debezium connector for PostgreSQL](https://debezium.io/documentation/reference/stable/connectors/postgresql.html)
- [PostgreSQL Documentation: ALTER TABLE, REPLICA IDENTITY](https://www.postgresql.org/docs/current/sql-altertable.html)
- [DuckDB: Announcing DuckDB 2.0.1 LTS](https://duckdb.org/2026/11/20/announcing-duckdb-201.html)
- [Apache Kafka: Kafka Connect documentation](https://kafka.apache.org/documentation/#connect)
