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

Worked Example: Applying Changes in Order with MERGE

Consume the Debezium topic from the lab with a Python consumer, apply each batch to a replica table with one PostgreSQL MERGE that keeps the latest event per key, honours deletes with soft-delete markers and skips replayed events, then crash between the two commits, replay the partition and prove the replica matches the source row for row.

Contentsand lesson path

What you will learn

  • Apply a change stream to a target table with MERGE, preserving per-key order, honoring deletes and ignoring replayed events.

Prerequisites: Messaging & Event Streaming

01. The problem

The topic shop.public.orders from the lab holds every change to orders. You now need a replica, a table that always equals the source. Copying events one by one looks easy, but three real conditions break naive code.

  • Several events for one key in one batch. Order 1 can be updated twice within a second. Applying them in the wrong order leaves an old value.
  • Deletes. A delete must remove the row from the replica, or the replica keeps orders that no longer exist.
  • Replays. Kafka delivers at least once: after a crash, a consumer reads again from its last committed offset, and Debezium can resend events after an unclean stop. An old event applied again must not overwrite newer data.

The plan: a consumer reads a batch, copies it into a staging table and applies it with one MERGE in one transaction. MERGE compares source rows with a target table and chooses, for each source row, to update, delete, insert or do nothing. The advanced SQL lesson used it for warehouse loads; here it must also respect order, deletes and replays.

You need the three containers from the lab, still running, with the topic as the lab left it (offsets 0 to 11). The consumer was tested with Python 3.12, confluent-kafka 2.16.1 and psycopg 3.3.9.

Terminal
cd cdc-lab
python3 -m venv .venv && source .venv/bin/activate
pip install "confluent-kafka==2.16.1" "psycopg[binary]==3.3.9"
export DATABASE_URL=postgresql://postgres:postgres@localhost:25432/shop
Terminal
python -c "import confluent_kafka as k, psycopg as p; print(k.version(), p.__version__)"
Expected output
2.16.1 3.3.9

02. Step 1: A replica that remembers positions

The replica has the source columns plus three more. deleted makes a delete a soft delete: the row stays as a marker, so the replica remembers the key and the position of its last change. src_offset is the Kafka offset of the last event applied to the row. Kafka keeps records in order within a partition, and all events of a key go to one partition, so a larger offset means a later change of that row. src_lsn keeps the event's PostgreSQL LSN, when it has one. The staging table is UNLOGGED (it skips the WAL), because it is refilled on every batch.

SQL · target.sql
-- The replica, in its own schema so that one query can compare it with the source.
CREATE SCHEMA replica;
CREATE TABLE replica.orders (
  id         int PRIMARY KEY,
  customer   text,
  status     text,
  amount     numeric(8,2),
  deleted    boolean NOT NULL DEFAULT false,  -- soft delete: the row stays as a marker
  src_offset bigint  NOT NULL,                -- Kafka offset of the last event applied
  src_lsn    bigint                           -- its PostgreSQL LSN, when it has one
);
-- Each batch from Kafka is copied here first, then merged in the same transaction.
CREATE UNLOGGED TABLE replica.orders_batch (
  kafka_offset bigint NOT NULL,
  op           text   NOT NULL,
  lsn          bigint,
  id           int    NOT NULL,
  customer     text,
  status       text,
  amount       numeric(8,2)
);
Terminal
docker exec -i cdc-pg psql -U postgres -d shop -X -q -v ON_ERROR_STOP=1 < target.sql

In production the replica would live in another database or a warehouse. A separate schema on the same server lets one SQL query compare it with the source. The publication lists only public.orders, so writes to replica are not captured.

03. Step 2: One MERGE per batch

Read the statement from top to bottom; PostgreSQL uses the first WHEN clause whose condition is true for each source row.

  1. DISTINCT ON (id) ... ORDER BY id, kafka_offset DESC keeps one event per key, the one with the highest offset, which is the latest change in commit order.
  2. The first WHEN MATCHED skips the event if the row already holds the same or a later position. s.kafka_offset <= t.src_offset catches this consumer's own replays. s.lsn <= t.src_lsn catches the same database change sent again by Debezium at a new offset. When either side has no LSN the comparison gives NULL, which counts as not true, so only the offset check decides.
  3. A delete of a known row sets deleted = true and records the position; it does not remove the row.
  4. Any other event for a known row (r, c or u) overwrites its columns and clears deleted, so a key that comes back after a delete becomes live again.
  5. A delete for a key the replica has never seen still inserts a marker, so that an older event for the key, replayed later, is skipped.
  6. Everything else is a new row.

RETURNING lists one action for each row that MERGE changed; rows that hit DO NOTHING are not returned, which is how the consumer counts skipped events. merge_action() and RETURNING in MERGE need PostgreSQL 17 or later.

SQL · merge.sql
MERGE INTO replica.orders AS t
USING (SELECT DISTINCT ON (id) *               -- the latest event for each key
         FROM replica.orders_batch
        ORDER BY id, kafka_offset DESC) AS s
   ON t.id = s.id
WHEN MATCHED AND (s.kafka_offset <= t.src_offset    -- this consumer has seen it
                  OR s.lsn <= t.src_lsn) THEN       -- the same change, sent again
  DO NOTHING
WHEN MATCHED AND s.op = 'd' THEN
  UPDATE SET deleted = true, src_offset = s.kafka_offset,
             src_lsn = coalesce(s.lsn, t.src_lsn)
WHEN MATCHED THEN
  UPDATE SET customer = s.customer, status = s.status, amount = s.amount,
             deleted = false, src_offset = s.kafka_offset,
             src_lsn = coalesce(s.lsn, t.src_lsn)
WHEN NOT MATCHED AND s.op = 'd' THEN
  INSERT (id, deleted, src_offset, src_lsn)
  VALUES (s.id, true, s.kafka_offset, s.lsn)
WHEN NOT MATCHED THEN
  INSERT VALUES (s.id, s.customer, s.status, s.amount, false, s.kafka_offset, s.lsn)
RETURNING CASE WHEN s.op = 'd' THEN 'DELETE' ELSE merge_action() END;

04. Step 3: The consumer loop

The consumer turns off automatic offset commits. For each batch it skips tombstones (the delete event before them carries the key and the position), takes the row from before for a delete and from after otherwise, and copies the rows into staging and runs the MERGE in one database transaction. Only after that commit does it commit the Kafka offsets.

That order is the core of the design. If the process dies between the two commits, Kafka does not know the batch is done, so the next run reads it again and the MERGE skips it. The reverse order could mark a batch as read whose database transaction then failed, and those changes would be lost. Reading at least once and applying idempotently gives the same end result as applying each change exactly once. --crash-after-batches simulates the crash, and --from-beginning rewinds the partition to offset 0.

Python · apply.py
"""Apply Debezium change events to replica.orders: one MERGE per batch, then commit."""
import argparse
import json
import os
import sys
from pathlib import Path

import psycopg
from confluent_kafka import OFFSET_BEGINNING, Consumer

TOPIC = "shop.public.orders"
MERGE = Path(__file__).with_name("merge.sql").read_text()


def to_row(msg):
    """One Debezium event as a staging row, or None for a tombstone."""
    if msg.value() is None:
        return None
    event = json.loads(msg.value())
    image = event["before"] if event["op"] == "d" else event["after"]
    return (msg.offset(), event["op"], event["source"]["lsn"], image["id"],
            image.get("customer"), image.get("status"), image.get("amount"))


def apply_batch(conn, msgs):
    rows = [r for r in map(to_row, msgs) if r is not None]
    with conn.transaction():                       # all of the batch, or nothing
        conn.execute("TRUNCATE replica.orders_batch")
        with conn.cursor().copy("COPY replica.orders_batch FROM STDIN") as copy:
            for row in rows:
                copy.write_row(row)
        actions = [a for (a,) in conn.execute(MERGE).fetchall()]
    n = {a: actions.count(a) for a in ("INSERT", "UPDATE", "DELETE")}
    keys = len({r[3] for r in rows})
    print(f"offsets {msgs[0].offset()}-{msgs[-1].offset()}: {len(msgs)} records,"
          f" {len(msgs) - len(rows)} tombstones, {keys} keys -> insert {n['INSERT']},"
          f" update {n['UPDATE']}, delete {n['DELETE']}, skip {keys - len(actions)}",
          flush=True)


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--batch-size", type=int, default=100)
    p.add_argument("--from-beginning", action="store_true")
    p.add_argument("--crash-after-batches", type=int)
    args = p.parse_args()

    def on_assign(consumer, partitions):
        if args.from_beginning:                    # replay the whole partition
            for tp in partitions:
                tp.offset = OFFSET_BEGINNING
        consumer.assign(partitions)

    consumer = Consumer({"bootstrap.servers": "localhost:29092",
                         "group.id": "replica-apply",
                         "enable.auto.commit": False,
                         "auto.offset.reset": "earliest",
                         "session.timeout.ms": 6000})
    consumer.subscribe([TOPIC], on_assign=on_assign)
    batches = 0
    with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
        while True:
            msgs = []
            while len(msgs) < args.batch_size:
                msg = consumer.poll(5.0 if batches or msgs else 20.0)
                if msg is None:
                    break
                if msg.error():
                    sys.exit(f"Kafka error: {msg.error()}")
                msgs.append(msg)
            if not msgs:
                break
            apply_batch(conn, msgs)                # 1. the database commit
            batches += 1
            if batches == args.crash_after_batches:
                print("crash: database committed, offsets not committed", flush=True)
                os._exit(1)
            consumer.commit(asynchronous=False)    # 2. then the Kafka offsets
    consumer.close()
    print(f"done: {batches} batches")


if __name__ == "__main__":
    main()

session.timeout.ms is lowered to 6 seconds, the broker's default minimum, so that after a simulated crash the dead consumer's partition is soon given to the next one. The first poll waits up to 20 seconds while the consumer joins the group. These are settings of the classic consumer group protocol, the default in confluent-kafka; with the protocol from KIP-848, generally available since Kafka 4.0, the broker sets the session timeout.

05. Step 4: First run and a row-by-row comparison

Run the consumer, then compare. The first query uses EXCEPT in both directions: source rows the live replica lacks, and live replica rows the source lacks. Both must be empty. The second lists every key the replica knows, so you can check that deleted orders are markers, not live rows.

SQL · compare.sql
-- Rows that differ between the source and the live rows of the replica, both ways.
(SELECT 'missing in replica' AS problem, id, customer, status, amount
   FROM public.orders
 EXCEPT
 SELECT 'missing in replica', id, customer, status, amount
   FROM replica.orders WHERE NOT deleted)
UNION ALL
(SELECT 'extra in replica', id, customer, status, amount
   FROM replica.orders WHERE NOT deleted
 EXCEPT
 SELECT 'extra in replica', id, customer, status, amount
   FROM public.orders)
ORDER BY id;
-- Every key ever seen: live rows match the source, deleted keys stay as markers.
SELECT r.id, r.deleted, o.id IS NOT NULL AS in_source
  FROM replica.orders r LEFT JOIN public.orders o ON o.id = r.id
 ORDER BY r.id;
Terminal
python apply.py
docker exec -i cdc-pg psql -U postgres -d shop -X -q < compare.sql
Expected output
offsets 0-11: 12 records, 2 tombstones, 5 keys -> insert 3, update 0, delete 2, skip 0
done: 1 batches
 problem | id | customer | status | amount 
---------+----+----------+--------+--------
(0 rows)

 id | deleted | in_source 
----+---------+-----------
  1 | f       | t
  2 | f       | t
  3 | t       | f
  4 | t       | f
  5 | f       | t
(5 rows)

Twelve records, two of them tombstones, reduced to one event per key for five keys. Orders 3 and 4 were inserted and deleted within the batch, so they arrive directly as markers. Orders 1 and 2 had several events each, and only the latest was applied.

06. Step 5: Why one event per key

It is tempting to skip the DISTINCT ON and give MERGE the whole batch. See what PostgreSQL does with two source rows for the same target row:

Terminal
docker exec cdc-pg psql -U postgres -d shop -X -q -c "
  MERGE INTO replica.orders AS t
  USING (VALUES (2, 'paid'), (2, 'shipped')) AS s (id, status) ON t.id = s.id
  WHEN MATCHED THEN UPDATE SET status = s.status"
Expected output
ERROR:  MERGE command cannot affect row a second time
HINT:  Ensure that not more than one source row matches any one target row.

PostgreSQL refuses and rolls back the whole statement. And even an engine that accepts it cannot know which source row is newer. Reducing the batch to the latest event per key, by log position, makes the order explicit.

07. Step 6: Crash between the two commits

Make five more changes, including an order that comes back after it was deleted. Apply them in batches of three and crash after the first batch.

SQL · more-changes.sql
UPDATE orders SET status = 'paid' WHERE id = 1;
UPDATE orders SET status = 'shipped' WHERE id = 1;
INSERT INTO orders VALUES (3, 'chen', 'placed', 14.00);   -- a deleted key comes back
DELETE FROM orders WHERE id = 5;
INSERT INTO orders VALUES (6, 'fay', 'placed', 42.00);
Terminal
docker exec -i cdc-pg psql -U postgres -d shop -X -q < more-changes.sql
sleep 3
python apply.py --batch-size 3 --crash-after-batches 1; echo "exit code $?"
python apply.py --batch-size 3
Expected output
offsets 12-14: 3 records, 0 tombstones, 2 keys -> insert 0, update 2, delete 0, skip 0
crash: database committed, offsets not committed
exit code 1
offsets 12-14: 3 records, 0 tombstones, 2 keys -> insert 0, update 0, delete 0, skip 2
offsets 15-17: 3 records, 1 tombstones, 2 keys -> insert 1, update 0, delete 1, skip 0
done: 2 batches

The first run applied offsets 12 to 14 (order 1 twice, so one update, and order 3 back from the dead) and died before committing offsets. The second run started again at offset 12, the last committed position. The guard skipped both keys, and the run went on with the delete of order 5 and the new order 6.

08. Step 7: Replay the whole partition

A deliberate replay is the harder test: after a bug fix, teams often re-read a topic from the start. Rewind to offset 0, apply everything again, and compare.

Terminal
python apply.py --from-beginning
docker exec -i cdc-pg psql -U postgres -d shop -X -q < compare.sql
Expected output
offsets 0-17: 18 records, 3 tombstones, 6 keys -> insert 0, update 0, delete 0, skip 6
done: 1 batches
 problem | id | customer | status | amount 
---------+----+----------+--------+--------
(0 rows)

 id | deleted | in_source 
----+---------+-----------
  1 | f       | t
  2 | f       | t
  3 | f       | t
  4 | t       | f
  5 | t       | f
  6 | f       | t
(6 rows)

All 18 records were read, all six keys skipped, and the replica still matches the source row for row. Orders 4 and 5 are markers; order 3 is live again. Keep the containers and the replica for the last lesson.

09. Check your understanding

Practice check · 3 questions

Order, deletes and replays

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

Q1. A colleague moves `consumer.commit()` before `apply_batch()` "so Kafka knows sooner". The process then dies while the MERGE runs. What happens to that batch?
Q2. You change the delete branch to remove the row instead of setting `deleted`. Later you replay only offsets 0 to 5 after a fix. What can happen to order 4, created at offset 3 and deleted at offset 8?
Q3. Order 7 is updated to `paid` at offset 40 and to `shipped` at offset 41. Batch A ends at offset 40 and batch B starts at 41. What is the replica row after both batches?
Practice only: not graded, not saved, not evidence.

10. Apply it

This is the second half of the skill practice. Run apply.py in one terminal with --batch-size 1 while a loop in another terminal updates random orders for a minute, stop it with Ctrl+C half-way, start it again, and finish with --from-beginning. Then run compare.sql and save its output as evidence. Finally, write two sentences for your runbook: how long delete markers are kept and why, and what you do if a replay must start before that point (rebuild the replica from a new snapshot).

11. Review prompt

Without looking back, explain: why the batch is reduced to one event per key before the MERGE; what the first WHEN MATCHED clause protects against and why it checks both the offset and the LSN; why deletes become markers rather than removed rows; why the database commit must come before the offset commit; and how the EXCEPT comparison proves the replica matches the source.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

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