Skip to content

    System Design

    Change Data Capture: Streaming Database Changes

    Compare query-based, trigger-based and log-based change data capture: snapshot then stream, slots and at-least-once delivery, with an in-process model lab.

    By Published 13 min read

    Share

    Standard lessonadvancedKafka labBackend System Design

    Before this: The Transactional Outbox, Kafka Internals: Partitions, Offsets, Consumer Groups and ISR

    What you'll learn: By the end of this lesson you will be able to define change data capture, compare query-based, trigger-based and log-based capture by what each can see, describe how a log-based tool takes a snapshot and then streams from a saved position, explain why delivery is at-least-once, name the risk of a replication slot, and read the output of an in-process model lab that says plainly what it does not show.

    A courtroom has two ways to keep a record. A stenographer types every word in order, including the sentence the speaker retracts a moment later. The other is a clerk who photographs the whiteboard once an hour: a figure written and wiped between two photographs never appears, and a wiped figure leaves only an empty space. A database offers the same two choices to anyone who wants to know what changed in it.

    This lesson is about change data capture (CDC): turning a database's changes into a stream of events. It builds on Kafka internals, because the stream usually lands in a topic, and it pairs with the transactional outbox lesson in this module, which decides what rows to write, and the idempotent consumers lesson, which covers the reading side. Delivery guarantees gives the underlying argument.

    Verified with Debezium 3.7 documentation, PostgreSQL 19 documentation (the latest at the time of reading), H2 documentation, Apache Kafka 4.2 and Spring Boot 4.1.2 on Java 25, on 2026-12-01. The lab runs a model, not Debezium: see "Build it".

    The core idea

    Change data capture publishes each committed change to a table (an insert, an update, a delete) as an event, in the order the database made them, so that other systems can follow the database without querying it for everything. It is a way to find out what changed; it does not by itself say what the change meant to the business.

    Three illustrations run through the lesson:

    • Minimal example: the same five writes captured three ways in the lab.
    • Realistic example: ShopStream keeping a search index and a read model in step with the orders database.
    • Failure example: a replication slot whose consumer has stopped, so the database cannot discard its log.

    Three ways to capture changes

    Three capture styles and where they sitApplication to Orders database (writes); Orders database to Polling query (select); Orders database to Trigger (row change); Orders database to Log tailer (log stream); Polling query to Topic (state); Trigger to Topic (events); Log tailer to Topic (events)Application: writes rowsApplicationwrites rowsOrders database: tables and a logOrdersdatabasetables and a logPolling query: reads tablesPolling queryreads tablesTrigger: inside the writeTriggerinside the writeLog tailer: reads the logLog tailerreads the logTopic: change eventsTopicchange eventswritesselectrow changelog streamstateeventsevents

    Figure 1. Where each style reads from. How to read this: the polling query reads the tables on a schedule and sees state. The trigger runs inside the database as part of each write. The log tailer reads the database's own record of committed changes, outside the write path.

    Style How it works Sees every change? Sees deletes? Load on the write path Needs
    Query-based Poll for rows whose updated column is above the last value seen No: only the latest state at each poll No: a deleted row is simply absent None, but repeated reads A reliable updated column that every writer sets
    Trigger-based A row trigger copies each change to a change table in the same transaction Yes Yes Yes: extra writes in every transaction A trigger per table, and something to read the change table
    Log-based Read the database's transaction log Yes, as committed Yes Close to none on the write path Database-specific access, an operated connector

    microservices.io describes the same trade for publishing events: polling an outbox table is "tricky to publish events in order"; tailing the log "requires database specific solutions" and is "tricky to avoid duplicate publishing".

    How log-based capture works

    PostgreSQL says that "logical decoding is implemented by decoding the contents of the write-ahead log, which describe changes on a storage level, into an application-specific form such as a stream of tuples or SQL statements". Debezium's PostgreSQL connector uses it: logical decoding "allows the extraction of the changes that were committed to the transaction log", and the standard output plug-in, pgoutput, is "always present so no additional libraries need to be installed" on PostgreSQL 10 and later.

    A replication slot is how the database remembers a consumer. PostgreSQL: "a slot represents a stream of changes that can be replayed to a client in the order they were made on the origin server"; slots "persist independently of the connection using them and are crash-safe"; a logical slot "will emit each change just once in normal operation". The connector creates its slot if it does not exist.

    Snapshot, then stream. A new consumer needs the rows that already exist, and then every change after them with no gap and no overlap. Debezium's connector, on first connection, "takes a consistent snapshot of all schemas", emitting each row as a READ event, then continues from the log position that snapshot started at. PostgreSQL supports this by exporting a snapshot when a slot is created, "which will show exactly the state of the database after which all changes will be included in the change stream".

    sequenceDiagram accTitle: Snapshot then stream in a log-based capture tool accDescr: On first start the tool records the current log position, copies the existing rows as read events, and saves the position. It then reads the log from that position, publishes each change event, and saves its position after each publish. After a crash it resumes from the last saved position, so the last event may be published again. participant DB as Database log participant T as Capture tool participant K as Topic T->>DB: note current log position (2) T->>K: publish READ events for existing rows T->>T: save position 2 DB->>T: change at position 3 T->>K: publish change 3 T->>T: save position 3 DB->>T: change at position 4 T->>K: publish change 4 Note over T: process dies before saving position 4 T->>DB: restart from saved position 3 DB->>T: change at position 4 T->>K: publish change 4 again

    Figure 2. Snapshot, stream and the repeat after a crash. How to read this: the tool saves its position after the publish, never before, so a crash can only lose the save, not an event. The price is that the last event is published twice.

    The shape of an event. A Debezium change event has a key built from the primary or unique key columns, and a value with before, after, a source block and an op field: c create, u update, d delete, r snapshot read. A delete is followed by a tombstone event with the same key. A table with no primary or unique key has a null event key, and without a primary key the connector "does not emit UPDATE or DELETE events for that table". How much of the old row an update or delete carries depends on the table's replica identity (DEFAULT, NOTHING or FULL).

    Ordering. Events for one row come out in the order the database committed them, because they come from one log. On a topic they stay in order only per partition, so the primary key must choose the partition, as it does in the lab.

    Delivery is at-least-once

    Notice where the position is saved in Figure 2. The Debezium FAQ says it plainly: "under normal operating scenarios, the application sees every event exactly one time. However, when things go wrong it is always possible for consuming applications to see events at least once." The connector may crash before it records its position ("When the Debezium's systems crash, they are not always able to record their last position/offset"), and the restart reads on from the last recorded one. Kafka Connect "periodically" records connector offsets, so how many events may repeat is not fixed.

    Consumers must therefore tolerate a repeat. Two forms fit: an overwrite by key (a search index document, a cache entry) is naturally repeatable, and a per-key guard on the event's log position ignores a repeat and a late older event. The lab shows the guard.

    Operational hazards

    • A stalled consumer holds the log. Slots "prevent removal of required resources even when there is no connection using them. This consumes storage because neither required WAL nor required rows from the system catalogs can be removed by VACUUM as long as they are required by a replication slot." Debezium states the other side: replication slots "are guaranteed to retain all WAL entries that are required for Debezium even during Debezium outages". Monitor the slot's lag and decide what happens when it grows.
    • One receiver per slot. "Only one receiver may consume changes from a slot at any given time."
    • Snapshots restart. "If the connector stops during a snapshot, the connector begins a new snapshot when it restarts."
    • Low-level events. A row change is not a business event: an after image of an orders row exposes your table design to every consumer. The outbox pattern writes a purpose-made event row and captures that instead.
    • Schema changes reach consumers as changed events; see schema evolution with Avro.
    flowchart TD accTitle: Choosing a change capture style accDescr: A decision tree. If missing deletes and intermediate states is acceptable and the table has a reliable updated column, polling is enough. Otherwise, if you can run a connector and read the log, use log-based capture. If not, use triggers and accept the write cost. Q1{"Can you miss deletes and
    intermediate states?"} Q2{"Can you run a connector
    and read the database log?"} A["Query-based polling"] B["Log-based capture"] C["Trigger-based capture"] Q1 -- yes --> A Q1 -- no --> Q2 Q2 -- yes --> B Q2 -- no --> C

    Figure 3. A decision for the capture style. How to read this: answer from the top. Polling is the cheapest and the least complete, the log is the most complete, and triggers are the fallback when the log is out of reach.

    Build it: three capture styles and a tailer, in process

    This lab is a model. Not Debezium: it does not read a PostgreSQL or MySQL log, uses no Kafka Connect or connector, and takes no snapshot of a real server. What runs: in-memory H2 (a real SQL engine, for the polling and trigger styles), a small Java model of a database with a write-ahead log (one entry per changed row, appended at commit; a slot is one confirmed position), a tailer that snapshots, streams from a saved position and publishes to the in-process Kafka broker, and two read models. Docker is not needed.

    Setup. From the repository:

    cd examples/spring-labs
    ./gradlew :labs:change-data-capture:test

    It runs 9 tests, one of which runs the five scenarios and compares the report with the golden file examples/spring-labs/golden/change-data-capture.txt. The code is in examples/spring-labs/labs/change-data-capture/.

    Run 1: query-based. The poller asks updated_seq > last seen. Between poll 1 and poll 2 an order is updated twice, and a second order is inserted and deleted.

    Run 2: trigger-based. An H2 row trigger (ChangeLogTrigger, implementing org.h2.api.Trigger) copies each change into change_log. H2 documents that a trigger runs "immediately when the operation occurred (before it is committed)" and that its operations "are part of the transaction"; the last line of the run shows a rolled-back transaction leaving no rows.

    Run 3: log-based (model). ModelDatabase appends a ChangeEvent with before and after values per changed row at commit.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, H2 in memory, 2026-12-01):

    Run 1. Query-based capture on H2: poll for rows with updated_seq above the last one seen.
      poll 1 : [o-1 placed]
      poll 2 : [o-1 shipped]   (after 4 writes: 2 updates, 1 insert, 1 delete)
      poll 3 : []   (after the delete of o-1)
      seen   : o-1 placed, o-1 shipped. Never seen: o-1 paid, o-2 at all, and both deletes.
    
    Run 2. Trigger-based capture on H2: a row trigger copies every change into change_log in the same transaction.
      change_log : CREATE o-1 - -> placed
      change_log : UPDATE o-1 placed -> paid
      change_log : UPDATE o-1 paid -> shipped
      change_log : CREATE o-2 - -> placed
      change_log : DELETE o-2 placed -> -
      a transaction with 2 writes, rolled back: change_log rows 5 -> 5
    
    Run 3. Log-based capture on the model: one log entry per changed row, appended when the transaction commits.
      log : lsn 1 CREATE o-1 - -> placed
      log : lsn 2 UPDATE o-1 placed -> paid
      log : lsn 3 UPDATE o-1 paid -> shipped
      log : lsn 4 CREATE o-2 - -> placed
      log : lsn 5 DELETE o-2 placed -> -
      a transaction with 2 writes, rolled back: log entries 5 (unchanged)
      one transaction, insert then update of o-4, committed: 2 new entries, [lsn 6, lsn 7]

    Polling saw two of the five changes and no deletes. The trigger and the log saw all five, and a rolled-back transaction left nothing in either. The model's log is where a real database differs most: its entries are already row-level events, whereas a real log describes storage-level changes that a decoding step turns into this shape.

    Run 4: snapshot, stream and a crash. Tailer.run is the loop of Figure 2: snapshot if it has never run, then for each entry publish, then save the position.

    for (ChangeEvent event : pending) {
        sink.publish(event);
        if (event.lsn() == crashAfterPublishing) {
            crashAfterPublishing = -1;
            throw new SimulatedCrash("process died after publishing lsn " + event.lsn() + ", before saving the position");
        }
        position.lsn = event.lsn();
        db.confirm(position.lsn);
    }

    The sink writes to a one-partition topic keyed by the row key. Two read models then apply the topic, one with a guard that ignores an event whose log position is not higher than the last applied for that key.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, in-process Kafka broker, 2026-12-01):

    Run 4. Snapshot, then stream, with a crash. Tailer to a Kafka topic (in-process broker), then two read models.
      table before the tailer starts: o-1 placed, o-2 placed (log position 2)
      process 1 snapshot: saved position 2
      3 commits follow (lsn 3, 4, 5); the next run dies after publishing lsn 4
      process 1 : DIES (process died after publishing lsn 4, before saving the position); saved position 3
      process 2 : restarts from saved position, runs to the end; saved position 5
      topic offset 0 : lsn 2 READ o-1 - -> placed
      topic offset 1 : lsn 2 READ o-2 - -> placed
      topic offset 2 : lsn 3 UPDATE o-1 placed -> paid
      topic offset 3 : lsn 4 UPDATE o-2 placed -> paid
      topic offset 4 : lsn 4 UPDATE o-2 placed -> paid
      topic offset 5 : lsn 5 UPDATE o-1 paid -> shipped
      read model without an lsn guard: applied 6, ignored 0, rows {o-1=shipped, o-2=paid}
      read model with an lsn guard: applied 5, ignored 1, rows {o-1=shipped, o-2=paid}

    Event lsn 4 is on the topic twice (offsets 3 and 4). Both read models end with the same rows because an overwrite is repeatable, but the unguarded one applied six events for five changes, which would matter for a counter.

    Run 5: the slot. The model keeps log entries the slot has not confirmed.

    Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, in-process Kafka broker, 2026-12-01):

    Run 5. A replication slot keeps log entries until the consumer confirms them (modelled as one confirmed position).
      3 commits, consumer offline, checkpoint: 3 log entries retained
      consumer catches up to lsn 3, checkpoint: 0 log entries retained

    This models the idea in a count of entries; it says nothing about how much disk a real PostgreSQL slot holds or how it is limited.

    Trade-offs

    Choice Gain Cost Wrong when
    Query-based polling No setup, works anywhere Misses intermediate states and deletes You need every change
    Trigger-based Every change, same transaction Slower writes; triggers to maintain Write latency is tight
    Log-based (a connector) Every committed change, little write-path cost A connector and a slot to operate The team cannot run and watch it
    Outbox plus CDC Business events with a stable shape An extra table and its cleanup A plain replica or search feed is all you need

    In practice: ShopStream's search index and read model

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's orders database is the source of truth. Support's order search and the shopper's "my orders" view read from a search index and a read model. The order service updates the index right after its commit, a dual write, and orders go missing or stale when the index call fails or the service restarts between the two steps.

    Starting architecture

    Orders to search index, before and afterOrder service to Orders database (one commit); Orders database to CDC connector (log); CDC connector to order-changes (events); order-changes to Search index (overwrite); order-changes to Read model (guarded)Order service: writes ordersOrder servicewrites ordersOrders database: source of truthOrdersdatabasesource of truthCDC connector: reads the logCDC connectorreads the logorder-changes: keyed by order idorder-changeskeyed by order idSearch index: upsert by idSearch indexupsert by idRead model: lsn guardRead modellsn guardone commitlogeventsoverwriteguarded

    Figure 4. The path after the change. How to read this: the service makes one write, to its own database. Everything downstream follows from the log, so there is nothing to fall out of step with the commit.

    Options considered

    Option Behaviour Risk
    A. Dual write with retries Fewer gaps A crash between the writes still loses one
    B. Poll by updated_at Simple Misses deletes and states between polls
    C. Log-based CDC into a topic Every committed change, in order per order A connector and a slot to operate

    The decision

    Option C. The topic is keyed by order id so each order's events stay in order. The index consumer upserts by id; the read-model consumer applies an event only if its log position is higher than the last for that order. The team adds an alert on slot lag and a runbook for a rebuild (a new snapshot).

    Rollout and verification

    Run the connector against a staging copy and check by counts: every order appears in the index after the snapshot, events on the topic against committed changes for a test window, and that a killed connector produces repeats the consumers ignore. After go-live, watch lag from the database to the topic and the age of the slot's oldest unconsumed position.

    The 2 a.m. failure

    The database disk is filling. The connector was stopped for a long weekend after a bad deploy, and its slot has held every log segment since. The checks are the slot's position against the current log position, and whether the connector runs. The mitigation is to restart it so it drains, or, if consumers can be rebuilt, to drop the slot and re-snapshot. The lasting fix is an alert on slot lag, a deliberate limit after which an idle slot is dropped, and treating a stopped connector as an incident.

    Architect's notes

    • Choose the style by what you must not miss. If deletes or intermediate states matter, polling is out.
    • Use the log position as the ordering and de-duplication token for consumers, and key the topic by primary key.
    • Operate the slot: lag metric, alert, and a decision about when to drop it.
    • Separate row changes from business events if the stream is a contract.

    Common mistakes

    • Polling updated_at and calling it CDC: deletes and intermediate states are lost.
    • Assuming exactly-once: restarts replay the tail.
    • Forgetting a table has no primary key: events are keyless or missing.
    • Leaving a stopped connector's slot in place: the database keeps the log.
    • Dual-writing to the database and a broker instead of capturing from the database.

    Key takeaways

    • CDC turns committed changes into an ordered event stream; it reports what changed, not why.
    • Polling sees state; triggers and logs see changes, including deletes.
    • A log-based tool snapshots, then streams from a saved position, saving it after publishing.
    • Delivery is at-least-once, so consumers overwrite by key or guard on the log position.
    • A slot is a promise to keep the log, and a stalled consumer makes the database pay for it.

    Practice exercises

    Exercise 1 (20 min). For a search index, a cache invalidation, an "orders per hour" counter and an audit trail, choose a capture style and say how repeats are handled.

    Exercise 2 (45 min). Run the lab. Predict what poll 2 of run 1 returns if o-1 is updated a third time between polls, then run it. Restore the code and re-run the tests.

    Exercise 3 (1 hour). Change the tailer to save the position before publishing and crash after the save. Predict whether an event is repeated or lost, run it, then restore the code.

    Exercise 4 (2 hours). Write the runbook for the 2 a.m. failure: what to check, drop and rebuild, and how consumers behave during the re-snapshot.

    The other side of this topic

    The front-end view is a screen fed by a feed of changes: it must handle a repeated or late update without flicker or loss, which is the same question about repeats and ordering seen from the receiving end.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments