Skip to content

Change Data Capture (CDC) ​

“Replication slots persist across crashes and know nothing about the state of their consumer(s).” — PostgreSQL 19 Documentation, 47.2.2 Replication Slots

Summary: CDC turns the committed changes in a database's own log into an ordered stream of row events that other systems can apply. Focus: PostgreSQL logical decoding and slots, the MySQL binlog, Debezium snapshots and envelopes, tombstones, schema history, three broker transports, and a sink that stays correct under duplicates. Learning goal: Operate a log-based CDC pipeline without filling the disk, and write a consumer whose result is right when events repeat, reorder or stop.

This chapter owns log capture. The transactional outbox owns publishing domain events and uses CDC as one relay; WAL and crash recovery owns what the log is; replication and failover owns physical and logical replicas; message design owns schema compatibility; the inbox pattern owns general consumer deduplication. Versions read for this page: Debezium 3.7 documentation, PostgreSQL 19 (current), MySQL 8.4, Kafka 4.4 documentation, Elasticsearch API v9.

Page map ​

Looking forGo to
Polling, triggers or the log: which capture styleCapture styles
pgoutput, publications, slots, restart_lsnPostgreSQL logical decoding
binlog_format=ROW, server-id, GTIDsMySQL binlog
before, after, op, source.lsnThe Debezium envelope
Initial vs incremental snapshots, watermarksSnapshots
Tombstones, compaction, delete.tombstone.handling.modeDeletes and tombstones
REPLICA IDENTITY, TOAST placeholders, key changesRow images
Schema history topic vs schema registrySchema changes
A version that survives duplicates and reorderingOrdering and the position contract
Slot monitoring SQL and heartbeatsMechanics
Debezium Server to RabbitMQ or Redis StreamsBroker differences
Commands with expected outputLab

Everything in one minute ​

IdeaWorking answerWhat goes wrong if ignored
Where do changes come from?The committed transaction log (PostgreSQL WAL, MySQL binlog)Polling misses deletes and intermediate states
What holds my place in the log?A PostgreSQL replication slot or a MySQL binlog file/position or GTID set, plus connector offsetsA dead consumer pins WAL until the disk fills
What does a consumer receive?An envelope: before, after, op, source, ts_msTreating it as a domain event couples consumers to table design
Is delivery exactly once?At least once after faults; duplicates are documentedA non-idempotent sink double counts
Is there one global order?Per key within one partition/stream onlyJoining two topics by arrival order is wrong
How does it start?A consistent snapshot, then streaming from the snapshot positionStarting from "now" loses existing rows
How are deletes shown?A d event, then optionally a tombstone (null value)Compaction can drop the delete before a slow reader sees it
Are schema changes in the stream?MySQL: DDL via schema history; PostgreSQL: no DDL, metadata refresh on the next rowConsumers break on a renamed column
PropertyKafka (Kafka Connect)RabbitMQ (Debezium Server)Redis Streams (Debezium Server)
UnitTopic per table, keyed recordsMessage published to an exchangeEntry appended with XADD
Record keyKafka key = primary keyNot sent (routing key only if configured)Field key (extended format)
TombstoneNull valuenull.value string (default default)null.value string (default default)
Connector offsetsKafka Connect offsets topicFile, JDBC or Redis offset storeFile, JDBC or Redis offset store
When offsets may advanceProducer acks per ConnectAfter waitForConfirmsOrDieAfter the XADD reply for each entry
Consumer progressCommitted group offsetAck per deliveryXACK per entry, PEL until then
ReplaySeek back within retentionGone once acked (classic queue)Re-read by ID until trimmed

Where it comes from ​

Databases keep an ordered log for their own crash recovery and replication. CDC reads that log from outside. PostgreSQL added logical decoding in 9.4 and the built-in pgoutput plugin in 10; logical replication uses the same slots and publications that a CDC connector uses. MySQL's binary log describes changes as events and is what replicas read; with row-based logging it carries before and after row images.

Debezium is the open-source connector family most deployments use. It runs either inside Kafka Connect (connector offsets and output in Kafka) or as Debezium Server, which Debezium describes as a ready-to-use application that streams to messaging systems "without requiring Apache Kafka". Earlier designs (polling an updated_at column, or audit tables filled by triggers) are still valid in narrow cases and are compared below.

Why it exists ​

The everyday problem is the dual write: an order service updates PostgreSQL and then calls the search index or the cache. Two systems, two commits, no shared atomicity. CDC removes the second write from the application: the database commit is the only write, and every derived copy is fed from the same log.

Dual write in the applicationLog-based CDC
Each writer must remember to publishEvery committed change is captured, from any writer
Crash between the writes leaves a silent gapThe slot or binlog position replays after a crash
Concurrent writers can publish in a different order than they committedEvents for one key follow commit order
No extra infrastructureSlots, connectors, offsets, snapshots and schema handling to operate
Publishes what the code chooses (domain events)Publishes table rows unless you add an outbox

Three misunderstandings to remove first. CDC is not free: the log is retained for you, decoded for you and shipped for you, and each step has a cost. CDC is not exactly once end to end: a connector restart re-sends recent events. CDC does not give you a single global order across tables or partitions.

What it is really about ​

A log-based CDC pipeline has four positions that must stay consistent: what the database has written, what the slot (or binlog reader) still retains, what the connector has durably recorded as sent, and what each consumer has applied. Every failure mode on this page is one of those positions moving without the others.

Log-based CDC: one ordered log, many derived copiesApplicationINSERT / UPDATECOMMITPostgreSQL WALwal_level = logicalPG 19: replica + slotLogical decodingpgoutput + publicationreplication slotDebezium connectorsnapshot, then streamenvelope: before/after/opslot keeps WAL fromrestart_lsnoffsets: Kafka Connect topicor Debezium Server storeKafka (Connect)topic per tablekey = primary keyRabbitMQDebezium Server sinkpublisher confirmsRedis StreamsDebezium Server sinkXADD per eventConsumer + sinkvalidate, compare positionupsert; ack after writeDuplicates are normal after restarts; the sink, not the transport, makes them harmless.

The sink is the last line of defence. Because the transport repeats events after faults and because some transports can reorder, the sink must compare a source position before writing, keep a marker for deleted rows, and refuse input it does not understand instead of skipping it.

An everyday picture ​

A bank statement lists every movement in the order the bank booked it. Your accountant ticks lines as they enter them into the books. If the accountant is ill for a week, the bank keeps the statement lines (that is the slot holding WAL); if the bank only keeps 30 days, a long illness means the accountant must start again from a fresh opening balance (a new snapshot). If the accountant enters the same line twice by mistake, the books are wrong unless each line has a reference number they check first (the position contract).

Concept catalogue ​

Capture styles: query, trigger and log Must-know ​

In plain words: you can ask the table what changed, make the table record what changed, or read the database's own diary.

Common misunderstanding: "Every database writes a log, so log-based CDC is always available and costs nothing." Some managed services restrict log access, logical decoding needs configuration and privileges, and the retained log and decoding work cost disk, CPU and network.

Definition: query-based CDC polls with a predicate such as updated_at > :last; trigger-based CDC writes an audit row from a trigger inside the same transaction; log-based CDC decodes committed changes from the transaction log through a replication interface.

text
1 T1 BEGIN; UPDATE stock SET qty=4 WHERE id=7;  (updated_at = 10:00:00.100)
2 T2 BEGIN; UPDATE stock SET qty=9 WHERE id=8;  (updated_at = 10:00:00.200)
3 T2 COMMIT
4 Poller: SELECT ... WHERE updated_at > 10:00:00.000  -> sees id 8 only, stores watermark 10:00:00.200
5 T1 COMMIT  (its timestamp is older than the stored watermark)
6 Poller: SELECT ... WHERE updated_at > 10:00:00.200  -> id 7 is never seen

Real scenarios: a nightly export where a missed row is reconciled tomorrow (polling is fine); an audit requirement to record who changed each row inside the transaction (a trigger); a search index, cache or warehouse that must see deletes and follow commit order (the log).

StyleSees deletesSees every intermediate committed stateWrite-path costOrdering sourceTypical trap
Query (poll)Only soft deletesNoIndex on the columnColumn value, not commit orderLate commits slip behind the watermark
Trigger (audit table)YesYesExtra insert in every transactionAudit sequenceLocks/latency in the hot path; still needs a poller
Log (Debezium)YesYes, per committed transactionWAL volume (more with REPLICA IDENTITY FULL)Log positionSlot retention, snapshot load, schema coupling

How to use it: prefer the log when correctness depends on deletes and commit order; if you must poll, poll a monotonic sequence assigned at commit (for example an outbox table written in the same transaction) and overlap the window, deduplicating on a stable ID.

PostgreSQL logical decoding, publications and slots Must-know ​

In plain words: a replication slot is a bookmark in the WAL that the server promises not to delete past, even if the reader is gone.

Common misunderstanding: "If the connector is down, nothing happens." The slot keeps pinning WAL and catalog rows; the PostgreSQL documentation warns that in extreme cases the database can shut down to prevent transaction ID wraparound.

Definition: logical decoding turns WAL into a stream of row changes through an output plugin. pgoutput is PostgreSQL's built-in plugin and sends only tables in a publication; wal2json is a third-party plugin that emits JSON (consumable with pg_recvlogical or the SQL functions); decoderbufs is Debezium's Protobuf plugin. In Debezium 3.7 the PostgreSQL connector's plugin.name default is still decoderbufs and the supported values are decoderbufs and pgoutput, so set pgoutput explicitly (it requires no server install and is what managed services provide). A logical slot streams one database; each slot has a restart_lsn (oldest WAL still needed) and a confirmed_flush_lsn (what the consumer has confirmed).

On PostgreSQL 19, logical decoding is available when wal_level = logical, or when wal_level = replica and at least one valid logical slot exists; effective_wal_level shows which applies. On earlier versions set wal_level = logical.

What a logical slot pins in pg_walWAL growsrestart_lsnoldest WAL still neededconfirmed_flush_lsnconsumer confirmed up to herecurrent LSNpg_current_wal_lsn()retained only for decoding restart(open transactions, catalog snapshot)decoded and sent, not yet confirmedreplayed after a reconnectIf current LSN - restart_lsn exceeds max_slot_wal_keep_size:wal_status reserved/extended -> unreserved -> lost; invalidation_reason = wal_removed.A lost slot cannot resume: new slot, new snapshot, new epoch.

text
1 Connector streams; confirmed_flush_lsn advances every flush
2 Connector stops (deploy failure, credentials expired)
3 Writes continue: current LSN grows, restart_lsn stays -> pg_wal grows
4 With max_slot_wal_keep_size = -1 (default): growth is unlimited until the disk fills
5 With max_slot_wal_keep_size = 50GB: wal_status becomes unreserved, then lost
6 Slot invalidated (invalidation_reason = wal_removed): connector cannot resume; re-snapshot

Real scenarios: a staging connector forgotten for a month fills a production disk; a low-traffic captured database on a busy server never confirms LSNs because no captured table changes (heartbeats solve it); an idle slot cleaned up by idle_replication_slot_timeout; a slot recreated after a failover that silently lost the changes in between.

ControlProductDefaultEffect
wal_levelPostgreSQLreplicalogical enables decoding; on 19, replica + a logical slot also does
max_replication_slotsPostgreSQL10Server start fails if set below existing slots
max_slot_wal_keep_sizePostgreSQL-1 (unlimited)Caps WAL a slot may retain; beyond it the slot can be lost
idle_replication_slot_timeoutPostgreSQL0 (off)Invalidates slots inactive longer than the value, at checkpoint
plugin.nameDebeziumdecoderbufsSet pgoutput
publication.autocreate.modeDebeziumall_tablesfiltered limits the publication to included tables
slot.name / slot.drop.on.stopDebeziumdebezium / falseOne slot per connector; never drop on stop in production
lsn.flush.modeDebeziumconnectormanual means someone else must flush or WAL accumulates

How to use it: one connector, one slot, one publication; set max_slot_wal_keep_size to a budget you can afford and alert well before it; drop slots you no longer use. The monitoring SQL is in Mechanics.

MySQL binlog, server-id and GTID Important ​

In plain words: the Debezium MySQL connector pretends to be one more replica and reads the binary log.

Common misunderstanding: "GTIDs make failover automatic." GTIDs let the connector find its place on another server only if that server has all the transactions the old one had and still holds the binlog files from that point.

Definition: Debezium requires binlog_format = ROW and binlog_row_image = FULL. The connector joins the topology with database.server.id, which must be unique among all running MySQL processes. Positions are binlog file and offset (source.file, source.pos, source.row) or a GTID (source_id:transaction_id; MySQL 8.4 also supports tagged GTIDs). binlog_expire_logs_seconds (default 2592000, 30 days) purges old files; a connector offline longer than that cannot resume, and snapshot.mode=when_needed makes it re-snapshot instead of failing. PURGE BINARY LOGS does not wait for a disconnected reader.

text
1 Connector reads mysql-bin.000042 at pos 9100, GTID set uuid-A:1-500
2 Primary fails; replica R2 promoted
3 Connector reconnects to R2 with uuid-A:1-500
4 If R2 executed uuid-A:1-500 and keeps binlogs from there -> resumes
5 If R2 lacks uuid-A:498-500 or purged the files -> stop; re-snapshot in a new epoch

Real scenarios: two connectors configured with the same database.server.id disconnect each other; a hosted MySQL without global read lock privileges forces table-level locks during the snapshot; a binlog retention of one day on a replica turns a weekend outage into a full re-snapshot.

NeedMySQL / Debezium settingNote
Row imagesbinlog_format=ROW, binlog_row_image=FULLMINIMAL breaks full before/after
Unique client identitydatabase.server.idUnique across the cluster
Failover lineagegtid_mode=ON, enforce_gtid_consistency=ONOptional for Debezium, strongly useful
Multi-source topologiesgtid.source.includes / gtid.source.excludesChoose which GTID sources count
Retentionbinlog_expire_logs_secondsMust exceed your worst outage plus margin
DDL trackingschema.history.internal.kafka.topicOne partition, never compacted away

How to use it: treat binlog retention like slot retention: alert on connector lag measured in time, and keep retention longer than any outage you would rather wait out than re-snapshot.

The Debezium envelope Must-know ​

In plain words: every event says what the row looked like before, what it looks like after, what kind of change it was, and where in the log it came from.

Common misunderstanding: "ts_ms orders events." The top-level ts_ms is when the connector processed the event; source.ts_ms is when the database made the change. Neither is a reliable ordering key; the log position is.

Definition: the value contains before, after, op (c create, u update, d delete, r read in a snapshot, t truncate, m logical decoding message), ts_ms/ts_us/ts_ns, and source. For PostgreSQL source carries name (the topic.prefix), db, schema, table, txId, lsn, snapshot, and sequence, a string holding a JSON array whose first value is the last committed LSN and second the current LSN; either may be null. The key is the primary key. With the JSON converter and schemas.enable=true, both are wrapped as {"schema": ..., "payload": ...}.

text
1 key   {"id": 42}
2 value {"before": {"id": 42, "email": "old@example.com"},
3        "after":  {"id": 42, "email": "new@example.com"},
4        "op": "u", "ts_ms": 1764140000123,
5        "source": {"name": "shop", "db": "shop", "schema": "public", "table": "customers",
6                   "txId": 771, "lsn": 24023128, "sequence": "[\"24023119\",\"24023128\"]", "snapshot": "false"}}

Real scenarios: a consumer that branches on op but forgot t silently ignores a truncate; a consumer that reads after for a delete gets null and indexes an empty document; a consumer on the wrong topic applies orders rows to the customers index.

FieldUse it forDo not use it for
opBranching: upsert, delete, snapshot read, fail-stop on t/mInferring transaction boundaries
beforeDelete key, old values (depends on REPLICA IDENTITY)Assuming full old row by default
afterNew row imageAssuming unchanged TOAST columns are present
source.name/db/schema/tableValidating the event belongs to this consumerDisplay only
source.lsn, source.sequenceThe position contractComparing across databases or restores
source.snapshotSnapshot vs stream (true, last, incremental, false)Business logic
ts_msLag: ts_ms - source.ts_msOrdering

How to use it: validate envelope, key and source strictly; the Go decoder below rejects malformed values, unknown ops, keys that disagree with the row, positions outside the signed 64-bit range, and events from another table.

Snapshots: initial, blocking and incremental Important ​

In plain words: the log only has recent history, so the connector first copies the current table contents, then switches to the log exactly where the copy was taken.

Common misunderstanding: "A snapshot row is just an insert." Snapshot rows (op = r) describe the state at snapshot time and can arrive after newer streamed changes for the same key during an incremental snapshot; a sink that lets them overwrite freely can move a row backwards.

Definition: the PostgreSQL connector's initial snapshot starts a transaction (isolation set by snapshot.isolation.mode, default serializable), reads the current log position, scans tables emitting r events, commits, records completion in offsets, and then streams from the recorded position. A failure before completion restarts the snapshot. snapshot.mode chooses when (initial default, always, initial_only, no_data, when_needed and others). Ad hoc snapshots are triggered by an execute-snapshot signal (incremental or blocking). Incremental snapshots read each table in primary-key chunks (incremental.snapshot.chunk.size, default 1024) while streaming continues; for each chunk a low and high watermark written to the signal table open and close a window, and streamed changes for a key inside the window evict the buffered snapshot row.

Incremental snapshot: one chunk window (signal table watermarks)WAL orderlow watermark (open)high watermark (close)SELECT chunk ORDER BY pk LIMIT 1024rows held in a memory buffer as READ (op r)streamed before window:emitted directlystreamed u/d for key 17 inside window:emitted; buffered READ for 17 droppedat close: emitremaining READ rowsResult per key: a READ never lands after a streamed change that superseded it inside the window.Outside the window, the sink still needs a rule: snapshot rows may create, never overwrite.

text
1 Signal row inserted: {"data-collections": ["public.customers"], "type": "incremental"}
2 Connector writes low watermark into public.debezium_signal
3 Chunk 1 read: ids 1..1024 buffered as READ
4 Stream: UPDATE customers id=17 committed -> emitted; buffered READ 17 dropped
5 Connector writes high watermark; remaining 1023 READ events emitted
6 Repeat for the next chunk; streaming never stopped

Real scenarios: adding a table to table.include.list and backfilling only that table; repairing a search index after a bug by re-reading one table; backfilling 400 million rows without a long-running read transaction.

ModeLocks / loadConcurrency with streamingDuplicatesUse for
Initial (initial)One long read transaction; serializable blocks DDL and index creationStreaming waitsRows near the switch may repeatFirst start
alwaysSame, every startStreaming waitsManyKnown lost WAL, promoted primary without failover slot
Blocking ad hocLike initial, for chosen tablesPausedRows near the switchSmall tables, maintenance windows
Incremental ad hocChunk queries, signal writesContinuesResolved per window; not across restartsLarge tables, backfills
Read-only incrementalNo signal writes (read.only=true)ContinuesAs aboveReplicas or read-only users

How to use it: let snapshot rows create documents but never overwrite streamed state; the position contract ranks every snapshot row below every streamed change. Avoid DDL during an incremental snapshot; the PostgreSQL connector does not support schema changes while one runs. Use incremental.snapshot.watermarking.strategy=insert_delete if the signal table grows too fast.

Deletes, tombstones and log compaction Must-know ​

In plain words: a delete arrives as a delete event, and on Kafka it is usually followed by an empty record that tells compaction it may forget the key.

Common misunderstanding: "A tombstone is the delete." The delete event (op = d, before set, after null) carries the deletion; the tombstone (same key, null value) exists for Kafka log compaction. On transports without null values, Debezium Server substitutes a string.

Definition: tombstones.on.delete (default true) emits the tombstone. Kafka treats a key with a null payload as a delete marker during compaction, and removes the marker itself after delete.retention.ms (default 24 hours); a consumer that lags longer can miss delete markers. The event-flattening SMT (ExtractNewRecordState) controls deletes with delete.tombstone.handling.mode: tombstone (default, keep tombstones), drop, rewrite (flattened row plus __deleted: "true", tombstones removed), rewrite-with-tombstone, delete-to-tombstone. Older configurations you may meet use delete.handling.mode and drop.tombstones; the 3.7 page documents only the newer option.

text
1 offset 100 key 9 value {op:"u", after:{id:9,...}}
2 offset 101 key 9 value {op:"d", before:{id:9}, after:null}
3 offset 102 key 9 value null                     (tombstone)
4 compaction: offsets 100 and 101 removed (102 is newer for key 9)
5 delete.retention.ms later: offset 102 removed too
6 a consumer replaying from 0 afterwards never learns that key 9 existed or was deleted

Real scenarios: rebuilding a projection from a compacted topic after 3 days misses deletes and keeps ghost documents; a RabbitMQ consumer receives the literal text default and fails to parse it; a sink that turns a delete into a real DELETE lets a late, older update resurrect the row.

TransportTombstone looks likeSafe consumer rule
KafkaRecord with null value and the keyRecognise exactly a null value; ignore after the delete was applied
Kafka with schemas.enable=trueNull value, or {"schema": ..., "payload": null}Treat both as null; anything else is malformed
Debezium Server RabbitMQdebezium.sink.rabbitmq.null.value (default default)Configure a distinctive sentinel; match bytes exactly
Debezium Server Redisdebezium.sink.redis.null.value (default default)Same; or disable tombstones for non-Kafka sinks

How to use it: keep deletes as a versioned "deleted" marker in the sink (Elasticsearch documents or SQL rows with deleted = true) so a delayed older event is rejected by position. Elasticsearch keeps a really deleted document's version only for index.gc_deletes (default 60s), which is why the example never issues a real delete. Compacted topics can rebuild state only within delete.retention.ms and only for keys whose latest event is still retained; beyond that, rebuild from a fresh snapshot.

REPLICA IDENTITY, TOAST and key changes Important ​

In plain words: PostgreSQL logs only as much of the old row as the table's replica identity asks for, and it skips large unchanged values.

Common misunderstanding: "after is always the complete row." With the default replica identity, an unchanged TOASTed column (a large value stored out of line, roughly above 8 KB) is not in the update event; Debezium puts __debezium_unavailable_value there.

Definition: ALTER TABLE ... REPLICA IDENTITY { DEFAULT | USING INDEX idx | FULL | NOTHING }. DEFAULT logs old primary-key values; USING INDEX the columns of a unique, non-partial, non-deferrable index on NOT NULL columns; FULL all old columns; NOTHING none. Debezium's unavailable.value.placeholder (default __debezium_unavailable_value) marks missing TOAST values; with FULL, TOAST values appear in before and after. A primary key update is emitted as a delete for the old key (header __debezium.newkey), its tombstone, and a create for the new key (header __debezium.oldkey).

text
1 UPDATE customers SET email='b@example.com' WHERE id=5;   -- bio is 40 KB, unchanged
2 Event after = {"id":5, "email":"b@example.com", "bio":"__debezium_unavailable_value"}
3 Naive sink replaces the document -> bio text becomes the placeholder string
4 Safe sink keeps the stored bio, or fails if it has none

Real scenarios: product descriptions in search replaced by the placeholder; a delete event whose before has only the key so a consumer cannot log the deleted email; renaming an order's primary key splitting its history across two Kafka partitions.

REPLICA IDENTITYOld values in UPDATE/DELETEUnchanged TOAST in updateWAL cost
DEFAULT (with PK)Primary keyPlaceholderLowest
USING INDEXIndex columnsPlaceholderLow
FULLAll columnsPresentHighest: whole old row logged
NOTHING / no PKNonePlaceholderUpdates/deletes cannot be identified downstream

How to use it: keep DEFAULT and merge placeholders in the sink (both examples below do), or use FULL on the few tables that need full old rows and accept the WAL volume.

Schema changes: schema history vs schema registry Important ​

In plain words: the connector must know each table's shape at each log position; consumers must know how to read each message's shape. Those are two different stores.

Common misunderstanding: "The schema history topic is where my consumers read schemas." It is an internal connector file; Debezium says it "is not intended for direct use by consuming applications". Consumers use the separate schema change topic, or a schema registry for serialized formats.

Definition: PostgreSQL logical decoding does not carry DDL; the connector notices a changed relation when the next row arrives (pgoutput refreshes metadata more eagerly). MySQL writes DDL into the binlog; the connector parses it and stores it in the internal schema history topic (schema.history.internal.kafka.topic) so it can interpret old binlog positions after a restart. Debezium: "Never partition the database schema history topic." A schema registry (Confluent, Apicurio) stores Avro/Protobuf/JSON Schema versions for consumers and enforces compatibility; it has nothing to do with connector recovery.

text
1 10:00 ALTER TABLE customers ADD COLUMN tier text;
2 10:01 MySQL connector: DDL parsed, appended to schema history (1 partition)
3 10:01 Avro converter: new value schema registered, compatibility checked by registry
4 10:02 Consumer v1 reads an event with tier; ignores the unknown field (backward compatible)
5 Connector restart: replays schema history to rebuild table shapes before reading the binlog

Real scenarios: an auto-created schema history topic with 6 partitions corrupts the connector's view of table shapes; a dropped column makes a consumer's strict decoder fail; deleting the schema history topic forces a full re-snapshot.

StoreOwnerConsumers read it?PartitioningLosing it means
Schema history topic (MySQL, others)ConnectorNoExactly 1Connector cannot interpret old binlog positions
Schema change topic (<topic.prefix>)ConnectorYes, for DDL notificationsAnyConsumers miss DDL notices
Schema registry subjectPlatformYes, via convertersNot a topic conceptOld messages cannot be decoded
PostgreSQL relation metadataConnector, from the databaseNon/aRefreshed from the database

How to use it: create the schema history topic yourself with one partition and long retention; deploy consumers that tolerate additive changes before you run DDL; see message design for compatibility modes.

Transaction metadata, ordering and the position contract Must-know ​

In plain words: within one table key you can recover the order; across tables, partitions and transports you cannot assume one.

Common misunderstanding: "Store the highest LSN applied and skip anything lower." Change LSNs are not monotonic in decoding order across interleaved transactions (a transaction that commits later can contain earlier LSNs), so a per-table or per-consumer "max LSN" checkpoint skips real changes; snapshot rows share one position; and a restored database or a new slot can reuse ranges. An LSN-only version is unsafe.

Definition: with provide.transaction.metadata=true, Debezium writes BEGIN/END events (id, event_count, data_collections) to <topic.prefix>.transaction and adds transaction.id, total_order and data_collection_order to each event. A truncate event has no key, so with multi-partition topics it has no ordering guarantee relative to row events. This page's sink uses a bounded position contract: epoch (one unbroken log lineage and one target index), a snapshot rank (snapshot rows below streamed changes), then commit = sequence[0] and change = sequence[1] (which must equal source.lsn), each within 0 to 2^63-1. A change replaces stored state only if its position is strictly greater.

Version contract used by the sink (per key, inside one epoch)position = epoch | rank (snapshot 0, stream 1) | commit = sequence[0] | change = sequence[1] = source.lsnTx A: key 7 at LSN 150, commits at 260Tx B: key 8 at LSN 200, commits at 210decoded B then A: LSNs 200, 150one max-LSN checkpoint skips key 7Per key, commit first: positions compareonly with the same key history.Same transaction, same key twice:[900, 910] then [900, 930]: second winsdifferent epoch:never compare; rebuildsnapshot vs snapshot: tie,create-only, no overwritestream greater: replaceequal or lower: no-op

text
1 Tx A: BEGIN; UPDATE customers SET tier='gold' WHERE id=7;   -- change LSN 150
2 Tx B: BEGIN; UPDATE customers SET tier='gold' WHERE id=8;   -- change LSN 200
3 Tx B: COMMIT;                                                -- commit LSN 210
4 Tx A: COMMIT;                                                -- commit LSN 260
5 Decoding (commit order): B's change (200), then A's change (150)
6 Consumer with one "max LSN applied" checkpoint = 200 skips A's change at 150 -> id 7 never updated
7 Commit-first position: B = (prev 100, 200), A = (210, 150); each key compares its own history

Real scenarios: a RabbitMQ requeue delivers an older event after a newer one; a Debezium Server Redis sink retries one entry after an OOM reply while later entries already landed; a connector crash re-sends the last few seconds; two updates to one key in one transaction share a commit position.

Order you might wantProvided?By what
Per key, one Kafka partitionYesKey = primary key, one partition per key
Per table, all keysOnly with a single partitionTopic partition count 1
Across tablesNoUse transaction metadata to group, not to order topics
Across connectors/databasesNoDifferent logs; no shared clock
After a restore, new slot, lost WALNoStart a new epoch and rebuild
Within one transactionYes, in emission ordertotal_order, change LSN

How to use it: compare positions in the sink, inside one epoch; never compare across epochs; rebuild into a new index when lineage breaks. The contract was tested in Go for interleaved transactions, two changes in one transaction, snapshot ties and range limits; it was not run against a live Debezium connector (see the HANDOFF limitations).

Outbox via CDC Good to know ​

In plain words: instead of publishing raw table rows, write a domain event to an outbox table in the same transaction and let CDC publish only that table.

Common misunderstanding: "The Outbox Event Router is part of Kafka." It is a Debezium single message transformation that runs in the connector runtime.

Definition: the Debezium Outbox Event Router maps each outbox INSERT to a record: route.by.field (default aggregatetype) builds the topic through route.topic.replacement (default outbox.event.${routedByValue}), table.field.event.key (default aggregateid) becomes the Kafka key, and table.op.invalid.behavior (default warn) decides what an UPDATE on the outbox does. Details, lifecycle and cleanup live in the outbox chapter.

text
1 BEGIN; UPDATE orders ...; INSERT INTO outbox (aggregatetype='order', aggregateid='o-17', payload) ; COMMIT
2 Connector captures only public.outbox
3 Router: topic outbox.event.order, key o-17, payload expanded
4 Consumers see OrderPlaced, not the orders table layout
PublishCouplingOrderingChoose when
Raw table CDCConsumers depend on columnsPer primary keyCaches, search, warehouse owned by the same team
Outbox via CDCConsumers depend on an event contractPer aggregate keyCross-team integration

Mechanics and exact controls ​

Slot health and WAL retention Important ​

confirmed_flush_lsn regularly advancing while restart_lsn lags is normal; PostgreSQL reclaims WAL in batches. Alert on retained bytes and on wal_status leaving reserved.

sql
-- PostgreSQL: one row per slot, retained WAL and danger signals
SELECT slot_name, plugin, active, failover, synced,
       restart_lsn, confirmed_flush_lsn, wal_status, safe_wal_size, invalidation_reason, inactive_since,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots
WHERE slot_type = 'logical';

-- Publication limited to the captured tables (pgoutput)
CREATE PUBLICATION shop_customers_pub FOR TABLE public.customers, public.debezium_signal, public.debezium_heartbeat;

-- Heartbeat table so a quiet database still confirms LSNs
CREATE TABLE public.debezium_heartbeat (id int PRIMARY KEY, ts timestamptz NOT NULL);

-- Signal table for incremental snapshots (Debezium documented shape)
CREATE TABLE public.debezium_signal (id varchar(42) PRIMARY KEY, type varchar(32) NOT NULL, data varchar(2048) NULL);
INSERT INTO public.debezium_signal (id, type, data)
VALUES ('backfill-2026-11-26', 'execute-snapshot', '{"data-collections": ["public.customers"], "type": "incremental"}');

-- Projection used by the Laravel sink
CREATE TABLE customer_projection (
    id text PRIMARY KEY,
    deleted boolean NOT NULL,
    data jsonb NOT NULL,
    cdc_epoch integer NOT NULL,
    cdc_rank smallint NOT NULL,
    cdc_commit bigint NOT NULL,
    cdc_change bigint NOT NULL
);
CREATE INDEX customer_projection_live ON customer_projection (id) WHERE NOT deleted;

-- Drop a slot that no consumer will ever use again (irreversible)
SELECT pg_drop_replication_slot('old_staging_slot');
SignalMeaningResponse
wal_status = extendedSlot holds more than max_wal_sizeCheck connector lag
wal_status = unreservedRequired WAL will be removed at the next checkpointRestore the consumer now
wal_status = lost, invalidation_reason = wal_removedSlot unusableNew slot, new snapshot, new epoch
invalidation_reason = rows_removedRequired catalog rows gone (often on standbys)Recreate; check hot_standby_feedback
invalidation_reason = idle_timeoutidle_replication_slot_timeout exceededRecreate; re-snapshot
invalidation_reason = wal_level_insufficientEffective WAL level below logicalFix wal_level
active = false for longNobody streamsRestart or drop deliberately
Debezium event.processing.failure.handling.mode=fail stopA problematic event; offset loggedInvestigate; do not switch to skip casually

Heartbeats Important ​

heartbeat.interval.ms (default 0, off) emits heartbeat records to __debezium-heartbeat.<topic.prefix> (prefix topic.heartbeat.prefix). Heartbeats let offsets advance when captured tables are quiet. They do not help when the captured database itself produces no WAL the slot can confirm while another database on the same server floods shared WAL: then set heartbeat.action.query to write a heartbeat table, and add that table to the publication, or the connector never sees the write.

Failover slots Important ​

On PostgreSQL 17+, Debezium's slot.failover=true creates a failover-enabled slot. It survives promotion only if the standby has sync_replication_slots = on, a physical slot (primary_slot_name), hot_standby_feedback = on, a dbname in primary_conninfo, and the primary lists the physical slot in synchronized_standby_slots (so logical consumers cannot get ahead of the standby). Only slots with synced = true before failover can continue; after promotion the connector must connect to the new primary. On PostgreSQL 15 and earlier, slots exist only on the primary; after promotion, treat history as broken unless proven otherwise.

Debezium offsets and delivery Good to know ​

In Kafka Connect, connector offsets are written periodically to the offsets topic (offset.storage.topic, compacted, replicated). A crash re-sends events since the last offset flush; Debezium documents at-least-once delivery during faults and exactly-once only "when the system is operating normally". Kafka Connect also offers worker-level exactly.once.source.support; it covers Kafka writes and offsets, not your sink. Debezium Server stores offsets in a file by default (debezium.source.offset.storage.file.filename), or in JDBC or Redis stores; a lost offset file means a restart decides from snapshot.mode.

Solving classic problems ​

A sink that tolerates duplicates, reordering and deletes ​

ProblemSolutionAdvantageCost / limitation
Connector replays after crashCompare positions; equal or lower is a no-opNo dedup tableNeeds trustworthy positions
Transport reorders (requeue, Redis retry)Same position comparisonOrder-insensitive per keyNot across keys
Late older update after deleteKeep deleted marker with its positionNo resurrectionMarker rows accumulate
Two updates in one transactionCompare (commit, change), not commit onlyFinal state winsRelies on change LSN
Snapshot row after streamed changeRank snapshot below streamNo regressionSnapshot cannot repair a wrong stored row
TOAST placeholderMerge stored value; fail if missingNo placeholder text in dataNeeds the stored row
Elasticsearch external version is one longScripted upsert compares the compositeExact comparisonScript runs per write
Concurrent writers on a documentretry_on_conflict; typed 409 as retryableNo silent lossRetries cost latency

Elasticsearch's index API version_type=external indexes only if the supplied non-negative long is strictly higher than the stored version (HTTP 409 otherwise). It is a good fit when one monotonic long exists per document. Commit plus change LSN do not fit in one long without lossy packing, so the Go sink sends the position as script parameters to POST /<index>/_update/<id> with scripted_upsert, and the script sets ctx.op = 'noop' for stale events. A 409 then means only version_conflict_engine_exception after retry_on_conflict attempts: a concurrency signal, never "already applied". Every live document carries deleted: false, so queries filter deleted: false.

Rebuild when lineage breaks ​

When the slot is lost, the database is restored from backup, a standby without a synced slot is promoted, or a truncate arrives: start a new epoch. Create customers-e4, start a connector with a new slot and snapshot.mode=initial, let it catch up, compare counts and samples, then switch the search alias and delete customers-e3. Consumers refuse events whose epoch does not match their index.

Choosing a capture approach ​

SituationChooseExtra techniqueReason
Search index or cache from one service's tablesLog CDC, raw rowsPosition-guarded upsert, deleted markersEvery writer captured, deletes included
Integration events for other teamsOutbox via CDCEvent contract, schema registryHides table layout
Warehouse/lake ingestionLog CDC to Kafka, then a sink connectorExtractNewRecordState with rewriteBulk-friendly flattened rows
Managed DB without logical replicationPolling an outbox sequenceOverlap window, dedup by IDOnly available interface
Audit with "who changed it" in the same transactionTrigger audit tableSession variables for actorThe log lacks application context
No Kafka in the platformDebezium Server to RabbitMQ/Redis/NATS/PulsarDistinct null sentinel, durable offsets storeSmaller footprint
Tiny tables, minute-level freshnessQuery-based snapshot diffFull compareSimpler than slots
Strict cross-table consistency downstreamTransaction metadata + buffering consumerGroup by transaction.idTopics alone do not order across tables

Amazon SQS has no Debezium Server sink in the 3.7 list (Kinesis, Pub/Sub, Pulsar, NATS JetStream, RabbitMQ, Redis and others are listed); a Lambda or Kafka bridge is the usual route there.

Go ​

Before ​

The service updates PostgreSQL and then writes Elasticsearch over HTTP. The comments list the four failure windows. It is bad design, not broken code.

go
// Package before shows the dual write that CDC replaces. It compiles and
// runs, but it is bad design: two independent writes with no shared commit.
package before

import (
	"bytes"
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
)

type CustomerService struct {
	DB     *sql.DB
	Search string // e.g. http://search.internal:9200/customers
	HTTP   *http.Client
}

// Rename commits to PostgreSQL, then tells the search index.
// Failure windows:
//  1. crash after COMMIT, before the HTTP call: index keeps the old name forever;
//  2. HTTP timeout after Elasticsearch applied it: caller retries, maybe out of order;
//  3. two concurrent renames: commits A,B but index writes B,A, so A wins in search;
//  4. any other writer (SQL console, batch job, another service) bypasses this code.
func (s CustomerService) Rename(ctx context.Context, id int64, name string) error {
	if _, err := s.DB.ExecContext(ctx, `UPDATE customers SET name = $1 WHERE id = $2`, name, id); err != nil {
		return err
	}
	body, _ := json.Marshal(map[string]any{"id": id, "name": name})
	req, err := http.NewRequestWithContext(ctx, http.MethodPut, fmt.Sprintf("%s/_doc/%d", s.Search, id), bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := s.HTTP.Do(req)
	if err != nil {
		return err // the database already changed; nothing records the gap
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		return fmt.Errorf("search index: HTTP %d", resp.StatusCode)
	}
	return nil
}

After ​

The application only writes PostgreSQL. A consumer decodes the Debezium envelope strictly and derives the position. Errors are fail-stop values: the caller must not acknowledge.

go
package cdc

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
)

// Errors a consumer must treat as fail-stop: do not acknowledge, do not skip.
var (
	ErrMalformed   = errors.New("cdc: malformed change event")
	ErrWrongSource = errors.New("cdc: event from an unexpected connector, database or table")
	ErrKey         = errors.New("cdc: missing or inconsistent row key")
	ErrTruncate    = errors.New("cdc: truncate needs an operator decision (rebuild in a new epoch)")
	ErrUnknownOp   = errors.New("cdc: unsupported op")
	ErrUnavailable = errors.New("cdc: TOAST placeholder where a full row is required")
)

// Kind separates real row changes from Kafka-compaction tombstones.
type Kind int

const (
	KindChange Kind = iota + 1
	KindTombstone
)

// Config pins the single table this consumer owns and its lineage epoch.
type Config struct {
	Connector    string // source.name (Debezium topic.prefix)
	Database     string // source.db
	Schema       string // source.schema
	Table        string // source.table
	KeyField     string // primary-key column, e.g. "id"
	Epoch        uint32 // operator-assigned lineage epoch
	Placeholder  string // unavailable.value.placeholder, default __debezium_unavailable_value
	NullSentinel []byte // Debezium Server null.value for RabbitMQ/Redis; nil for Kafka
}

// Change is one validated row event.
type Change struct {
	Kind        Kind
	Op          string                     // c, u, d, r (empty for tombstones)
	Key         string                     // canonical key text; numbers are kept as digits, never cast
	Deleted     bool                       // explicit live/deleted marker for the sink
	Row         map[string]json.RawMessage // after image; nil for deletes and tombstones
	Unavailable []string                   // columns carrying the TOAST placeholder (updates only)
	Position    Position
}

type source struct {
	Name     string          `json:"name"`
	DB       string          `json:"db"`
	Schema   string          `json:"schema"`
	Table    string          `json:"table"`
	LSN      json.Number     `json:"lsn"`
	Sequence *string         `json:"sequence"`
	Snapshot json.RawMessage `json:"snapshot"`
}

type envelope struct {
	Op     string                     `json:"op"`
	Before map[string]json.RawMessage `json:"before"`
	After  map[string]json.RawMessage `json:"after"`
	Source *source                    `json:"source"`
}

// Decode validates key and value bytes. key may be nil when the transport
// does not carry it (Debezium Server RabbitMQ sink); then the row key is used.
func Decode(cfg Config, key, value []byte) (Change, error) {
	if isNull(cfg, value) {
		k, err := keyFromKeyBytes(cfg, key)
		if err != nil && key != nil {
			return Change{}, err
		}
		return Change{Kind: KindTombstone, Key: k}, nil
	}
	raw, err := unwrap(value)
	if err != nil {
		return Change{}, err
	}
	if raw == nil { // {"schema":...,"payload":null}: a wrapped null value
		k, err := keyFromKeyBytes(cfg, key)
		if err != nil && key != nil {
			return Change{}, err
		}
		return Change{Kind: KindTombstone, Key: k}, nil
	}
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.UseNumber()
	var env envelope
	if err := dec.Decode(&env); err != nil {
		return Change{}, fmt.Errorf("%w: %v", ErrMalformed, err)
	}
	if err := checkSource(cfg, env.Source); err != nil {
		return Change{}, err
	}
	ch := Change{Kind: KindChange, Op: env.Op}
	var image map[string]json.RawMessage
	switch env.Op {
	case "c", "u", "r":
		if env.After == nil {
			return Change{}, fmt.Errorf("%w: op %q without after", ErrMalformed, env.Op)
		}
		image, ch.Row = env.After, env.After
	case "d":
		if env.Before == nil || env.After != nil {
			return Change{}, fmt.Errorf("%w: delete needs before and a null after", ErrMalformed)
		}
		image, ch.Deleted = env.Before, true
	case "t":
		return Change{}, ErrTruncate
	default:
		return Change{}, fmt.Errorf("%w: %q", ErrUnknownOp, env.Op)
	}
	rowKey, err := keyText(image[cfg.KeyField])
	if err != nil {
		return Change{}, err
	}
	if key != nil {
		k, err := keyFromKeyBytes(cfg, key)
		if err != nil {
			return Change{}, err
		}
		if k != rowKey {
			return Change{}, fmt.Errorf("%w: record key %s, row key %s", ErrKey, k, rowKey)
		}
	}
	ch.Key = rowKey
	if ch.Row != nil {
		ph, _ := json.Marshal(placeholder(cfg))
		for col, v := range ch.Row {
			if bytes.Equal(bytes.TrimSpace(v), ph) {
				ch.Unavailable = append(ch.Unavailable, col)
			}
		}
		if len(ch.Unavailable) > 0 && env.Op != "u" {
			return Change{}, fmt.Errorf("%w: op %q", ErrUnavailable, env.Op)
		}
	}
	ch.Position, err = position(cfg, env.Op, env.Source)
	return ch, err
}

func isNull(cfg Config, value []byte) bool {
	if value == nil {
		return true
	}
	return cfg.NullSentinel != nil && bytes.Equal(value, cfg.NullSentinel)
}

func placeholder(cfg Config) string {
	if cfg.Placeholder == "" {
		return "__debezium_unavailable_value"
	}
	return cfg.Placeholder
}

// unwrap removes the JsonConverter {"schema","payload"} wrapper when present.
func unwrap(b []byte) (json.RawMessage, error) {
	var top map[string]json.RawMessage
	if err := json.Unmarshal(b, &top); err != nil || top == nil {
		return nil, fmt.Errorf("%w: value is not a JSON object", ErrMalformed)
	}
	p, wrapped := top["payload"]
	if _, hasSchema := top["schema"]; !wrapped || !hasSchema || len(top) != 2 {
		return b, nil
	}
	if bytes.Equal(bytes.TrimSpace(p), []byte("null")) {
		return nil, nil
	}
	return p, nil
}

func checkSource(cfg Config, s *source) error {
	if s == nil {
		return fmt.Errorf("%w: no source block", ErrMalformed)
	}
	if s.Name != cfg.Connector || s.DB != cfg.Database || s.Schema != cfg.Schema || s.Table != cfg.Table {
		return fmt.Errorf("%w: %s/%s/%s.%s", ErrWrongSource, s.Name, s.DB, s.Schema, s.Table)
	}
	return nil
}

func keyFromKeyBytes(cfg Config, key []byte) (string, error) {
	if key == nil {
		return "", fmt.Errorf("%w: no record key", ErrKey)
	}
	raw, err := unwrap(key)
	if err != nil || raw == nil {
		return "", fmt.Errorf("%w: unreadable record key", ErrKey)
	}
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.UseNumber()
	var m map[string]json.RawMessage
	if err := dec.Decode(&m); err != nil || len(m) != 1 {
		return "", fmt.Errorf("%w: key must have exactly the primary-key field", ErrKey)
	}
	return keyText(m[cfg.KeyField])
}

// keyText returns digits for integer keys and the string for text keys.
// It never converts to int64, so a NUMERIC(30) key cannot be truncated.
func keyText(v json.RawMessage) (string, error) {
	v = bytes.TrimSpace(v)
	if len(v) == 0 || bytes.Equal(v, []byte("null")) {
		return "", fmt.Errorf("%w: key field absent or null", ErrKey)
	}
	if v[0] == '"' {
		var s string
		if err := json.Unmarshal(v, &s); err != nil || s == "" || len(s) > 512 {
			return "", fmt.Errorf("%w: bad text key", ErrKey)
		}
		return s, nil
	}
	s := string(v)
	start := 0
	if s[0] == '-' {
		start = 1
	}
	if start == len(s) || len(s) > 64 {
		return "", fmt.Errorf("%w: bad integer key %q", ErrKey, s)
	}
	for _, c := range s[start:] {
		if c < '0' || c > '9' {
			return "", fmt.Errorf("%w: key %q is not an integer", ErrKey, s)
		}
	}
	return s, nil
}

func position(cfg Config, op string, s *source) (Position, error) {
	p := Position{Epoch: cfg.Epoch}
	snap, err := snapshotFlag(s.Snapshot)
	if err != nil {
		return Position{}, err
	}
	if op == "r" {
		if !snap {
			return Position{}, fmt.Errorf("%w: read event outside a snapshot", ErrMalformed)
		}
		p.Snapshot = true
		return p, nil
	}
	if s.Sequence == nil {
		return Position{}, fmt.Errorf("%w: source.sequence missing", ErrPosition)
	}
	var seq []*string
	if err := json.Unmarshal([]byte(*s.Sequence), &seq); err != nil || len(seq) != 2 || seq[0] == nil || seq[1] == nil {
		return Position{}, fmt.Errorf("%w: sequence %q", ErrPosition, *s.Sequence)
	}
	if p.Commit, err = parseLSN(*seq[0]); err != nil {
		return Position{}, err
	}
	if p.Change, err = parseLSN(*seq[1]); err != nil {
		return Position{}, err
	}
	if lsn, err := parseLSN(s.LSN.String()); err != nil || lsn != p.Change {
		return Position{}, fmt.Errorf("%w: source.lsn %q disagrees with sequence", ErrPosition, s.LSN)
	}
	return p, nil
}

// snapshotFlag accepts Debezium's boolean and string forms of source.snapshot.
func snapshotFlag(raw json.RawMessage) (bool, error) {
	raw = bytes.TrimSpace(raw)
	if len(raw) == 0 || bytes.Equal(raw, []byte("null")) || bytes.Equal(raw, []byte("false")) {
		return false, nil
	}
	if bytes.Equal(raw, []byte("true")) {
		return true, nil
	}
	var s string
	if err := json.Unmarshal(raw, &s); err != nil {
		return false, fmt.Errorf("%w: source.snapshot %s", ErrMalformed, raw)
	}
	switch s {
	case "false":
		return false, nil
	case "true", "first", "first_in_data_collection", "last_in_data_collection", "last", "incremental":
		return true, nil
	}
	return false, fmt.Errorf("%w: source.snapshot %q", ErrMalformed, s)
}

The position type holds the contract and its bounds:

go
// Package cdc decodes Debezium PostgreSQL change events into a strict,
// bounded contract that an idempotent sink can apply in any delivery order.
package cdc

import (
	"errors"
	"fmt"
	"math"
	"strconv"
)

// ErrPosition reports a missing, malformed or out-of-range source position.
var ErrPosition = errors.New("cdc: invalid source position")

// Position orders changes for ONE key inside ONE lineage epoch.
//
// Contract (see the chapter text for its limits):
//   - Epoch identifies an unbroken log lineage: one database history, one
//     slot (or a failover slot that stayed synced), one target index. Any
//     restore, slot loss, or re-snapshot after lost WAL starts a new epoch
//     and a new target; positions from different epochs are never compared.
//   - Snapshot rows (op "r") rank below every streamed change and tie with
//     each other: they may create a missing document but never overwrite.
//   - Streamed changes compare by (Commit, Change) taken from Debezium's
//     source.sequence ["<last committed LSN>", "<current LSN>"]. Commit is
//     constant inside one decoded transaction and grows between them; Change
//     grows inside a transaction, so two updates of one key in one
//     transaction stay distinct.
//   - Both values must fit a signed 64-bit integer, so a sink that stores
//     them as "long" (Elasticsearch, PostgreSQL bigint) cannot overflow.
type Position struct {
	Epoch    uint32
	Snapshot bool
	Commit   uint64
	Change   uint64
}

// Compare returns -1, 0 or +1. It panics if epochs differ: callers must
// check SameEpoch first, because cross-epoch order does not exist.
func (p Position) Compare(q Position) int {
	if p.Epoch != q.Epoch {
		panic("cdc: comparing positions from different epochs")
	}
	if p.Snapshot != q.Snapshot {
		if p.Snapshot {
			return -1
		}
		return 1
	}
	if p.Snapshot {
		return 0
	}
	switch {
	case p.Commit < q.Commit:
		return -1
	case p.Commit > q.Commit:
		return 1
	case p.Change < q.Change:
		return -1
	case p.Change > q.Change:
		return 1
	}
	return 0
}

// SameEpoch reports whether two positions belong to one lineage.
func (p Position) SameEpoch(q Position) bool { return p.Epoch == q.Epoch }

// Rank is the sink-facing tuple [snapshotRank, commit, change]; every element
// is within the signed 64-bit range by construction.
func (p Position) Rank() [3]int64 {
	if p.Snapshot {
		return [3]int64{0, 0, 0}
	}
	return [3]int64{1, int64(p.Commit), int64(p.Change)}
}

// parseLSN accepts only a plain decimal integer in [0, MaxInt64].
func parseLSN(s string) (uint64, error) {
	if s == "" || len(s) > 19 {
		return 0, fmt.Errorf("%w: %q", ErrPosition, s)
	}
	for _, c := range s {
		if c < '0' || c > '9' {
			return 0, fmt.Errorf("%w: %q", ErrPosition, s)
		}
	}
	v, err := strconv.ParseUint(s, 10, 64)
	if err != nil || v > math.MaxInt64 {
		return 0, fmt.Errorf("%w: %q out of range", ErrPosition, s)
	}
	return v, nil
}

The Elasticsearch sink sends a scripted upsert with the composite position, an explicit deleted marker, and TOAST merge. It decodes 2xx results and typed 409 errors:

go
// Package elastic applies validated CDC changes to an Elasticsearch index
// with a composite source-position guard evaluated inside a scripted upsert.
package elastic

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	"academy/change-data-capture/after/cdc"
)

// Outcome tells the caller what happened; both outcomes are safe to ack.
type Outcome int

const (
	Applied Outcome = iota + 1 // document created or replaced
	Stale                      // stored position is newer or equal: no-op
)

var (
	// ErrConflict means concurrent writers exhausted retry_on_conflict.
	// It is retryable, never "already applied".
	ErrConflict = errors.New("elastic: version conflict after retries")
	// ErrRejected covers every other non-2xx answer: stop and investigate.
	ErrRejected = errors.New("elastic: request rejected")
)

// The script enforces: one epoch per index; snapshot rows create only;
// streamed rows replace only when [rank, commit, change] is strictly greater;
// TOAST placeholder columns keep their stored value or fail.
const script = `
def p = params.pos;
if (ctx.op == 'create') {
  if (params.unavailable.size() > 0) { throw new IllegalArgumentException('unavailable column on a missing document'); }
} else {
  if (ctx._source.cdc_epoch != params.epoch) { throw new IllegalStateException('epoch mismatch'); }
  def s = ctx._source.cdc_pos;
  int c = 0;
  for (int i = 0; i < 3 && c == 0; i++) { c = p[i] > s[i] ? 1 : (p[i] < s[i] ? -1 : 0); }
  if (c <= 0) { ctx.op = 'noop'; return; }
}
Map n = new HashMap();
if (!params.deleted) { n.putAll(params.row); }
for (def f : params.unavailable) {
  if (!ctx._source.containsKey(f)) { throw new IllegalArgumentException('unavailable column has no stored value'); }
  n.put(f, ctx._source.get(f));
}
n.put('deleted', params.deleted);
n.put('cdc_epoch', params.epoch);
n.put('cdc_pos', p);
ctx._source.clear();
ctx._source.putAll(n);
`

// Sink writes to one index per lineage epoch, e.g. "customers-e3".
type Sink struct {
	BaseURL string
	Index   string
	Epoch   uint32
	HTTP    *http.Client
}

// Apply is idempotent and order-insensitive per document id.
// Tombstones are ignored: the preceding delete already wrote a deleted
// marker document, which must be kept so late older events stay rejected.
func (s Sink) Apply(ctx context.Context, ch cdc.Change) (Outcome, error) {
	if ch.Kind == cdc.KindTombstone {
		return Stale, nil
	}
	if ch.Position.Epoch != s.Epoch {
		return 0, fmt.Errorf("%w: change epoch %d, index epoch %d", ErrRejected, ch.Position.Epoch, s.Epoch)
	}
	unavailable := ch.Unavailable
	if unavailable == nil {
		unavailable = []string{}
	}
	body, err := json.Marshal(map[string]any{
		"scripted_upsert": true,
		"upsert":          map[string]any{},
		"script": map[string]any{
			"lang":   "painless",
			"source": script,
			"params": map[string]any{
				"epoch":       s.Epoch,
				"pos":         ch.Position.Rank(),
				"deleted":     ch.Deleted,
				"row":         ch.Row,
				"unavailable": unavailable,
			},
		},
	})
	if err != nil {
		return 0, err
	}
	u := strings.TrimRight(s.BaseURL, "/") + "/" + url.PathEscape(s.Index) +
		"/_update/" + url.PathEscape(ch.Key) + "?retry_on_conflict=3"
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(body))
	if err != nil {
		return 0, err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := s.HTTP.Do(req)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	if err != nil {
		return 0, err
	}
	return decode(resp.StatusCode, raw)
}

func decode(status int, raw []byte) (Outcome, error) {
	if status == http.StatusOK || status == http.StatusCreated {
		var ok struct {
			Result string `json:"result"`
		}
		if err := json.Unmarshal(raw, &ok); err != nil {
			return 0, fmt.Errorf("%w: unreadable success body", ErrRejected)
		}
		switch ok.Result {
		case "created", "updated":
			return Applied, nil
		case "noop":
			return Stale, nil
		}
		return 0, fmt.Errorf("%w: unexpected result %q", ErrRejected, ok.Result)
	}
	var failure struct {
		Error struct {
			Type   string `json:"type"`
			Reason string `json:"reason"`
		} `json:"error"`
	}
	_ = json.Unmarshal(raw, &failure)
	if status == http.StatusConflict && failure.Error.Type == "version_conflict_engine_exception" {
		return 0, ErrConflict
	}
	return 0, fmt.Errorf("%w: HTTP %d type %q", ErrRejected, status, failure.Error.Type)
}

The tests pin the contract: interleaved transactions, two updates in one transaction, snapshot ranking, exact tombstones, truncate fail-stop, key mismatch, large numeric keys kept as text, and LSN range.

go
package cdc

import (
	"errors"
	"fmt"
	"strings"
	"testing"
)

var cfg = Config{Connector: "shop", Database: "shop", Schema: "public", Table: "customers", KeyField: "id", Epoch: 3}

func event(op, before, after, snapshot, seq string, lsn int) []byte {
	return []byte(fmt.Sprintf(`{"before":%s,"after":%s,"op":%q,"ts_ms":1,
	 "source":{"name":"shop","db":"shop","schema":"public","table":"customers",
	 "snapshot":%s,"sequence":%s,"lsn":%d,"txId":7}}`, before, after, op, snapshot, seq, lsn))
}

func TestStreamedUpdateUsesCommitThenChange(t *testing.T) {
	v := event("u", `{"id":42}`, `{"id":42,"email":"a@example.com"}`, `"false"`, `"[\"500\",\"620\"]"`, 620)
	ch, err := Decode(cfg, []byte(`{"id":42}`), v)
	if err != nil {
		t.Fatal(err)
	}
	if ch.Key != "42" || ch.Deleted || ch.Position.Commit != 500 || ch.Position.Change != 620 {
		t.Fatalf("unexpected %+v", ch)
	}
}

func TestTwoUpdatesInOneTransactionStayOrdered(t *testing.T) {
	a, _ := Decode(cfg, nil, event("u", `{"id":1}`, `{"id":1,"n":1}`, `false`, `"[\"900\",\"910\"]"`, 910))
	b, _ := Decode(cfg, nil, event("u", `{"id":1}`, `{"id":1,"n":2}`, `false`, `"[\"900\",\"930\"]"`, 930))
	if a.Position.Compare(b.Position) != -1 {
		t.Fatal("second change in the same transaction must be newer")
	}
}

func TestInterleavedTransactionsOrderByCommitNotChange(t *testing.T) {
	// Comparator rule: a later commit wins even with a lower change LSN.
	b, _ := Decode(cfg, nil, event("u", `{"id":1}`, `{"id":1}`, `false`, `"[\"100\",\"200\"]"`, 200))
	a, _ := Decode(cfg, nil, event("u", `{"id":1}`, `{"id":1}`, `false`, `"[\"250\",\"150\"]"`, 150))
	if b.Position.Compare(a.Position) != -1 {
		t.Fatal("later commit must win even with a lower change LSN")
	}
}

func TestSnapshotRowsRankBelowStreaming(t *testing.T) {
	r, err := Decode(cfg, nil, event("r", `null`, `{"id":5}`, `"true"`, `"[null,\"77\"]"`, 77))
	if err != nil {
		t.Fatal(err)
	}
	u, _ := Decode(cfg, nil, event("u", `{"id":5}`, `{"id":5}`, `false`, `"[\"1\",\"2\"]"`, 2))
	if r.Position.Compare(u.Position) != -1 || r.Position.Compare(r.Position) != 0 {
		t.Fatal("snapshot must rank below streaming and tie with snapshots")
	}
}

func TestDeleteCarriesExplicitMarker(t *testing.T) {
	ch, err := Decode(cfg, []byte(`{"id":9}`), event("d", `{"id":9}`, `null`, `false`, `"[\"5\",\"6\"]"`, 6))
	if err != nil || !ch.Deleted || ch.Row != nil {
		t.Fatalf("got %+v %v", ch, err)
	}
}

func TestTombstoneRecognitionIsExact(t *testing.T) {
	if ch, err := Decode(cfg, []byte(`{"id":9}`), nil); err != nil || ch.Kind != KindTombstone {
		t.Fatalf("nil value must be a tombstone: %+v %v", ch, err)
	}
	sentinel := cfg
	sentinel.NullSentinel = []byte("__debezium_null__")
	if ch, err := Decode(sentinel, nil, []byte("__debezium_null__")); err != nil || ch.Kind != KindTombstone {
		t.Fatalf("sentinel must be a tombstone: %v", err)
	}
	for _, bad := range []string{"", "default", "[]", "42", `"x"`} {
		if _, err := Decode(sentinel, nil, []byte(bad)); !errors.Is(err, ErrMalformed) {
			t.Fatalf("%q must be malformed, got %v", bad, err)
		}
	}
	if ch, err := Decode(cfg, []byte(`{"id":9}`), []byte(`{"schema":{},"payload":null}`)); err != nil || ch.Kind != KindTombstone {
		t.Fatalf("wrapped null payload must be a tombstone: %v", err)
	}
}

func TestFailStopCases(t *testing.T) {
	cases := map[string]struct {
		key, value []byte
		want       error
	}{
		"truncate":      {nil, event("t", `null`, `null`, `false`, `"[\"1\",\"2\"]"`, 2), ErrTruncate},
		"message":       {nil, event("m", `null`, `null`, `false`, `"[\"1\",\"2\"]"`, 2), ErrUnknownOp},
		"other table":   {nil, []byte(strings.Replace(string(event("c", `null`, `{"id":1}`, `false`, `"[\"1\",\"2\"]"`, 2)), "customers", "orders", 1)), ErrWrongSource},
		"key mismatch":  {[]byte(`{"id":2}`), event("c", `null`, `{"id":1}`, `false`, `"[\"1\",\"2\"]"`, 2), ErrKey},
		"float key":     {nil, event("c", `null`, `{"id":1.5}`, `false`, `"[\"1\",\"2\"]"`, 2), ErrKey},
		"null commit":   {nil, event("c", `null`, `{"id":1}`, `false`, `"[null,\"2\"]"`, 2), ErrPosition},
		"lsn mismatch":  {nil, event("c", `null`, `{"id":1}`, `false`, `"[\"1\",\"2\"]"`, 3), ErrPosition},
		"lsn too large": {nil, event("c", `null`, `{"id":1}`, `false`, `"[\"9223372036854775808\",\"2\"]"`, 2), ErrPosition},
		"no after":      {nil, event("c", `null`, `null`, `false`, `"[\"1\",\"2\"]"`, 2), ErrMalformed},
		"bad snapshot":  {nil, event("r", `null`, `{"id":1}`, `"maybe"`, `null`, 0), ErrMalformed},
		"toast on read": {nil, event("r", `null`, `{"id":1,"bio":"__debezium_unavailable_value"}`, `"true"`, `null`, 0), ErrUnavailable},
	}
	for name, c := range cases {
		if _, err := Decode(cfg, c.key, c.value); !errors.Is(err, c.want) {
			t.Errorf("%s: want %v, got %v", name, c.want, err)
		}
	}
}

func TestToastPlaceholderIsReportedOnUpdate(t *testing.T) {
	ch, err := Decode(cfg, nil, event("u", `{"id":1}`, `{"id":1,"bio":"__debezium_unavailable_value"}`, `false`, `"[\"1\",\"2\"]"`, 2))
	if err != nil || len(ch.Unavailable) != 1 || ch.Unavailable[0] != "bio" {
		t.Fatalf("got %+v %v", ch, err)
	}
}

func TestLargeNumericKeyIsNotCast(t *testing.T) {
	ch, err := Decode(cfg, nil, event("c", `null`, `{"id":123456789012345678901234567890}`, `false`, `"[\"1\",\"2\"]"`, 2))
	if err != nil || ch.Key != "123456789012345678901234567890" {
		t.Fatalf("got %q %v", ch.Key, err)
	}
}

func TestComparePanicsAcrossEpochs(t *testing.T) {
	defer func() {
		if recover() == nil {
			t.Fatal("expected panic")
		}
	}()
	Position{Epoch: 1}.Compare(Position{Epoch: 2})
}

The Go angle ​

The core takes bytes and returns a value or an error; each broker adapter only decides when to acknowledge. encoding/json with UseNumber and json.RawMessage keeps large keys as digits. net/http with httptest tests the sink without a cluster. Reading the WAL yourself is possible with github.com/jackc/pglogrepl over the replication protocol, but then you own the slot, standby status updates and the snapshot handoff; letting Debezium own them keeps the Go service small. Run go test ./... in docs/snippets/messaging/change-data-capture/go; it needs no broker.

Laravel ​

Before ​

The same dual write in Laravel: query builder update, then an HTTP call. A failed HTTP call after the update leaves search stale with no record of the gap.

php
<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

// Bad design on purpose: a database commit followed by a separate HTTP write.
// A crash, timeout or concurrent rename between the two leaves search wrong,
// and every writer that bypasses this method is invisible to the index.
final class CustomerService
{
    public function rename(int $id, string $name): void
    {
        DB::table('customers')->where('id', $id)->update(['name' => $name]);

        Http::timeout(2)
            ->put("http://search.internal:9200/customers/_doc/{$id}", ['id' => $id, 'name' => $name])
            ->throw();
    }
}

After ​

ChangeEvent validates the envelope, keeps keys and LSNs as strings (JSON_BIGINT_AS_STRING, decimal comparison without casts) and rejects missing fields, truncates and unknown ops:

php
<?php

namespace App\Cdc;

use JsonException;

// A validated Debezium PostgreSQL row event. LSNs and keys stay strings:
// nothing is cast to int, so values above PHP_INT_MAX cannot wrap.
final readonly class ChangeEvent
{
    /**
     * @param  array<string, mixed>|null  $row
     * @param  list<string>  $unavailable
     */
    private function __construct(
        public bool $tombstone,
        public string $op,
        public string $key,
        public bool $deleted,
        public ?array $row,
        public array $unavailable,
        public int $epoch,
        public bool $snapshot,
        public string $commit,
        public string $change,
    ) {
    }

    public static function decode(CdcConfig $cfg, ?string $key, ?string $value): self
    {
        if ($value === null || ($cfg->nullSentinel !== null && $value === $cfg->nullSentinel)) {
            return new self(true, '', $key === null ? '' : self::keyFromKey($cfg, $key), false, null, [], $cfg->epoch, false, '0', '0');
        }

        $env = self::unwrap(self::json($value));
        if ($env === null) {
            return new self(true, '', $key === null ? '' : self::keyFromKey($cfg, $key), false, null, [], $cfg->epoch, false, '0', '0');
        }

        $source = self::field($env, 'source');
        foreach (['name' => $cfg->connector, 'db' => $cfg->database, 'schema' => $cfg->schema, 'table' => $cfg->table] as $f => $want) {
            if (! is_array($source) || ($source[$f] ?? null) !== $want) {
                throw InvalidChangeEvent::because("unexpected source.{$f}");
            }
        }

        $op = self::field($env, 'op');
        [$image, $row, $deleted] = match ($op) {
            'c', 'u', 'r' => [self::object($env, 'after'), self::object($env, 'after'), false],
            'd' => self::deleteImages($env),
            't' => throw InvalidChangeEvent::because('truncate requires a rebuild in a new epoch'),
            default => throw InvalidChangeEvent::because('unsupported op'),
        };

        $rowKey = self::keyText($image[$cfg->keyField] ?? null);
        if ($key !== null && self::keyFromKey($cfg, $key) !== $rowKey) {
            throw InvalidChangeEvent::because('record key and row key differ');
        }

        $unavailable = [];
        foreach ($row ?? [] as $column => $v) {
            if ($v === $cfg->placeholder) {
                $unavailable[] = (string) $column;
            }
        }
        if ($unavailable !== [] && $op !== 'u') {
            throw InvalidChangeEvent::because('TOAST placeholder outside an update');
        }

        $snapshot = self::snapshotFlag($source['snapshot'] ?? null);
        if ($op === 'r') {
            if (! $snapshot) {
                throw InvalidChangeEvent::because('read event outside a snapshot');
            }

            return new self(false, $op, $rowKey, false, $row, [], $cfg->epoch, true, '0', '0');
        }

        $seq = is_string($source['sequence'] ?? null) ? self::json($source['sequence']) : null;
        if (! is_array($seq) || count($seq) !== 2 || ! is_string($seq[0] ?? null) || ! is_string($seq[1] ?? null)) {
            throw InvalidChangeEvent::because('source.sequence must hold two LSN strings');
        }
        $commit = self::lsn($seq[0]);
        $change = self::lsn($seq[1]);
        $lsn = $source['lsn'] ?? null;
        if (! (is_int($lsn) || is_string($lsn)) || self::lsn((string) $lsn) !== $change) {
            throw InvalidChangeEvent::because('source.lsn disagrees with sequence');
        }

        return new self(false, $op, $rowKey, $deleted, $row, $unavailable, $cfg->epoch, false, $commit, $change);
    }

    /** Returns -1, 0 or 1 by [snapshot rank, commit, change] inside one epoch. */
    public function compareTo(int $epoch, bool $snapshot, string $commit, string $change): int
    {
        if ($epoch !== $this->epoch) {
            throw InvalidChangeEvent::because('stored row belongs to another epoch');
        }

        return (($this->snapshot ? 0 : 1) <=> ($snapshot ? 0 : 1))
            ?: ($this->snapshot ? 0 : (self::decimalCmp($this->commit, $commit) ?: self::decimalCmp($this->change, $change)));
    }

    /** Compares canonical decimal strings without converting them to numbers. */
    private static function decimalCmp(string $a, string $b): int
    {
        return (strlen($a) <=> strlen($b)) ?: (strcmp($a, $b) <=> 0);
    }

    private static function json(string $text): mixed
    {
        try {
            return json_decode($text, true, 64, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
        } catch (JsonException) {
            throw InvalidChangeEvent::because('not JSON');
        }
    }

    /** @return array<string, mixed>|null */
    private static function unwrap(mixed $decoded): ?array
    {
        if (! is_array($decoded) || array_is_list($decoded)) {
            throw InvalidChangeEvent::because('value is not a JSON object');
        }
        if (count($decoded) === 2 && array_key_exists('schema', $decoded) && array_key_exists('payload', $decoded)) {
            $payload = $decoded['payload'];
            if ($payload !== null && (! is_array($payload) || array_is_list($payload))) {
                throw InvalidChangeEvent::because('payload is not an object');
            }

            return $payload;
        }

        return $decoded;
    }

    private static function keyFromKey(CdcConfig $cfg, string $key): string
    {
        $k = self::unwrap(self::json($key));
        if ($k === null || count($k) !== 1 || ! array_key_exists($cfg->keyField, $k)) {
            throw InvalidChangeEvent::because('record key must contain only the primary key');
        }

        return self::keyText($k[$cfg->keyField]);
    }

    private static function keyText(mixed $v): string
    {
        if (is_int($v)) {
            return (string) $v;
        }
        if (is_string($v) && $v !== '' && strlen($v) <= 512) {
            return $v;
        }

        throw InvalidChangeEvent::because('primary key missing, null or not an integer/string');
    }

    private static function lsn(string $s): string
    {
        if (preg_match('/^(0|[1-9][0-9]{0,18})$/', $s) !== 1
            || (strlen($s) === 19 && strcmp($s, '9223372036854775807') > 0)) {
            throw InvalidChangeEvent::because('LSN is not a decimal in the signed 64-bit range');
        }

        return $s;
    }

    private static function snapshotFlag(mixed $v): bool
    {
        return match ($v) {
            null, false, 'false' => false,
            true, 'true', 'first', 'first_in_data_collection', 'last_in_data_collection', 'last', 'incremental' => true,
            default => throw InvalidChangeEvent::because('unknown source.snapshot value'),
        };
    }

    /** @param array<string, mixed> $env */
    private static function field(array $env, string $name): mixed
    {
        if (! array_key_exists($name, $env)) {
            throw InvalidChangeEvent::because("missing {$name}");
        }

        return $env[$name];
    }

    /**
     * @param  array<string, mixed>  $env
     * @return array<string, mixed>
     */
    private static function object(array $env, string $name): array
    {
        $v = self::field($env, $name);
        if (! is_array($v) || ($v !== [] && array_is_list($v))) {
            throw InvalidChangeEvent::because("{$name} must be an object");
        }

        return $v;
    }

    /**
     * @param  array<string, mixed>  $env
     * @return array{0: array<string, mixed>, 1: null, 2: true}
     */
    private static function deleteImages(array $env): array
    {
        if (self::field($env, 'after') !== null) {
            throw InvalidChangeEvent::because('delete with a non-null after');
        }

        return [self::object($env, 'before'), null, true];
    }
}

CustomerProjector uses one injected connection for everything: transaction(), lockForUpdate() on the projection row, position comparison, TOAST merge, then upsert() on that same connection. A stale event returns false and is safe to acknowledge.

php
<?php

namespace App\Cdc;

use Illuminate\Database\ConnectionInterface;

// Applies a validated event to customer_projection on ONE connection:
// lock the row, compare positions, merge TOAST placeholders, then write.
final class CustomerProjector
{
    public function __construct(private readonly ConnectionInterface $db)
    {
    }

    /** Returns true when the row changed, false for a stale or duplicate event. */
    public function apply(ChangeEvent $e): bool
    {
        if ($e->tombstone) {
            return false; // the preceding delete already wrote deleted = true
        }

        return $this->db->transaction(function () use ($e): bool {
            $stored = $this->db->table('customer_projection')
                ->where('id', $e->key)
                ->lockForUpdate()
                ->first();

            $data = $e->row ?? [];
            if ($stored === null) {
                if ($e->unavailable !== []) {
                    throw InvalidChangeEvent::because('TOAST placeholder for a row we never stored');
                }
            } else {
                if ($e->compareTo((int) $stored->cdc_epoch, (string) $stored->cdc_rank === '0', (string) $stored->cdc_commit, (string) $stored->cdc_change) <= 0) {
                    return false;
                }
                $old = json_decode((string) $stored->data, true, 64, JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING);
                foreach ($e->unavailable as $column) {
                    if (! is_array($old) || ! array_key_exists($column, $old)) {
                        throw InvalidChangeEvent::because("no stored value for unavailable column {$column}");
                    }
                    $data[$column] = $old[$column];
                }
            }

            $this->db->table('customer_projection')->upsert([[
                'id' => $e->key,
                'deleted' => $e->deleted,
                'data' => json_encode($e->deleted ? new \stdClass() : $data, JSON_THROW_ON_ERROR),
                'cdc_epoch' => $e->epoch,
                'cdc_rank' => $e->snapshot ? 0 : 1,
                'cdc_commit' => $e->commit,
                'cdc_change' => $e->change,
            ]], ['id'], ['deleted', 'data', 'cdc_epoch', 'cdc_rank', 'cdc_commit', 'cdc_change']);

            return true;
        });
    }
}

The Laravel angle ​

Laravel 13's built-in queue drivers are, in its words, "database, Amazon SQS, Redis, and Beanstalkd drivers" plus sync and null. Debezium produces raw JSON, not Laravel job payloads, so the queue worker and its RabbitMQ/Kafka driver packages are the wrong abstraction; the transports below use php-rdkafka, php-amqplib and the Redis facade directly and run as long-lived Artisan commands. DB::transaction accepts an attempts argument for deadlocks; an InvalidChangeEvent must escape the command so the message is not acknowledged. Use decimal.handling.mode=string on the connector so NUMERIC columns arrive as strings, not base64 bytes or doubles. The .php files pass php -l; they were not run inside a Laravel application.

Broker differences ​

RabbitMQ ​

Debezium Server's rabbitmq sink publishes over AMQP 0-9-1 to an exchange (default: the topic name, or debezium.sink.rabbitmq.exchange) with deliveryMode 2 (persistent) by default. Reading the sink source at commit ae234f1 (2026-11-26): it calls confirmSelect, publishes the batch, waits with waitForConfirmsOrDie(ackTimeout), and only then marks each record processed, so offsets cannot advance past unconfirmed messages. It does not set the mandatory flag. RabbitMQ confirms an unroutable message once the exchange finds no queue, so a missing binding means confirmed and lost. Declare and bind a durable quorum queue before starting the server, consider an alternate exchange, and monitor unroutable counts. The record key is not sent (only usable as the routing key with routingKey.source=key), so the consumer takes the key from the row. A tombstone becomes the null.value string (default default); set a distinctive value or tombstones.on.delete=false.

properties
# Debezium Server -> RabbitMQ (AMQP 0-9-1). Expected, not run.
debezium.sink.type=rabbitmq
debezium.sink.rabbitmq.connection.host=rabbit.shop.internal
debezium.sink.rabbitmq.connection.port=5672
# One durable exchange; deployment binds the quorum queue BEFORE start-up.
# The sink publishes without the mandatory flag: an unroutable message is
# still confirmed by the broker, so missing bindings lose events silently.
debezium.sink.rabbitmq.exchange=cdc.shop
debezium.sink.rabbitmq.routingKey=shop.public.customers
debezium.sink.rabbitmq.deliveryMode=2
debezium.sink.rabbitmq.ackTimeout=30000
# Distinct, non-JSON tombstone sentinel instead of the default "default".
debezium.sink.rabbitmq.null.value=__debezium_null__
debezium.format.value=json
debezium.format.value.schemas.enable=false
debezium.source.connector.class=io.debezium.connector.postgresql.PostgresConnector
debezium.source.plugin.name=pgoutput
debezium.source.topic.prefix=shop
debezium.source.table.include.list=public.customers
debezium.source.tombstones.on.delete=false
debezium.source.skipped.operations=none
# Offsets are local to this process: back the file up, or use the JDBC or
# Redis offset store, or a restart re-snapshots / replays from the slot.
debezium.source.offset.storage.file.filename=/var/lib/debezium/offsets.dat
debezium.source.offset.flush.interval.ms=0

The Go consumer acks after the sink returns, and on any error returns without settling. Closing the channel requeues unacked deliveries to their original position where possible; position comparison makes the inevitable redelivery harmless. Use x-single-active-consumer if you want queue order, but correctness does not depend on it.

go
// Package rabbitmq consumes Debezium Server RabbitMQ-sink messages from a
// durable quorum queue. The sink sends only the value (no record key), and
// a configured null.value string for tombstones.
package rabbitmq

import (
	"context"
	"errors"
	"fmt"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/change-data-capture/after/cdc"
	"academy/change-data-capture/after/elastic"
)

// Applier is the sink; elastic.Sink satisfies it.
type Applier interface {
	Apply(context.Context, cdc.Change) (elastic.Outcome, error)
}

// Handle decides one delivery. It returns nil only when acking is safe.
func Handle(ctx context.Context, cfg cdc.Config, sink Applier, body []byte) error {
	ch, err := cdc.Decode(cfg, nil, body)
	if err != nil {
		return err
	}
	_, err = sink.Apply(ctx, ch)
	return err
}

// Run acks after a successful apply. On any failure it returns WITHOUT
// settling; closing the channel requeues every unacked delivery to its
// original position where possible. Nothing is nacked into a loop.
func Run(ctx context.Context, url, queue string, cfg cdc.Config, sink Applier) error {
	if cfg.NullSentinel == nil {
		return errors.New("rabbitmq: set NullSentinel to debezium.sink.rabbitmq.null.value")
	}
	conn, err := amqp.Dial(url)
	if err != nil {
		return err
	}
	defer conn.Close()
	chn, err := conn.Channel()
	if err != nil {
		return err
	}
	defer chn.Close()
	// The queue is declared by deployment as a quorum queue with
	// x-single-active-consumer=true so one consumer sees queue order.
	if err := chn.Qos(50, 0, false); err != nil {
		return err
	}
	deliveries, err := chn.ConsumeWithContext(ctx, queue, "cdc-projector", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range deliveries {
		if err := Handle(ctx, cfg, sink, d.Body); err != nil {
			return fmt.Errorf("delivery %d (redelivered=%t): %w", d.DeliveryTag, d.Redelivered, err)
		}
		if err := d.Ack(false); err != nil {
			return fmt.Errorf("ack %d: %w", d.DeliveryTag, err)
		}
	}
	if ctx.Err() != nil {
		return ctx.Err()
	}
	return amqp.ErrClosed
}
php
<?php

namespace App\Cdc\Transport;

use App\Cdc\CdcConfig;
use App\Cdc\ChangeEvent;
use App\Cdc\CustomerProjector;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

// php-amqplib directly: Debezium Server publishes raw JSON, not Laravel jobs,
// so the Laravel RabbitMQ queue driver is the wrong abstraction here.
final class RabbitMqCdcConsumer
{
    public function __construct(
        private readonly CdcConfig $cfg,
        private readonly CustomerProjector $projector,
    ) {
    }

    public function run(AMQPStreamConnection $connection, string $queue): void
    {
        $channel = $connection->channel();
        $channel->basic_qos(0, 50, false);
        $channel->basic_consume($queue, 'cdc-projector', false, false, false, false, function (AMQPMessage $message): void {
            // The RabbitMQ sink sends no record key; the row key is used.
            $event = ChangeEvent::decode($this->cfg, null, $message->getBody());
            $this->projector->apply($event); // an exception escapes unacked
            $message->ack();
        });

        try {
            $channel->consume();
        } finally {
            // Closing requeues every unacked delivery; the worker exits.
            $channel->close();
            $connection->close();
        }
    }
}

A classic queue deletes acked messages, so RabbitMQ is not a replay source: rebuilds come from a new snapshot, not from the queue. RabbitMQ streams are replayable, but Debezium Server's native stream sink is the separate rabbitmqstream type.

Kafka ​

Debezium on Kafka Connect writes one topic per table (<topic.prefix>.<schema>.<table>), keyed by primary key, so per-key order holds within a partition. Configure topic cleanup.policy=compact only if you accept the caveats: compaction keeps the latest record per key, removes tombstones after delete.retention.ms, and never covers events you need older than that; compact,delete adds time-based loss. A rebuild from a compacted topic is complete only if the consumer reaches the head within delete.retention.ms; otherwise rebuild from a snapshot. Debezium recommends single-partition topics when you need ordering between truncates and row events.

json
{
  "name": "shop-customers",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "pg-primary.shop.internal",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "${file:/secrets/pg.properties:password}",
    "database.dbname": "shop",
    "topic.prefix": "shop",
    "table.include.list": "public.customers,public.debezium_signal,public.debezium_heartbeat",
    "plugin.name": "pgoutput",
    "slot.name": "shop_customers",
    "slot.failover": "true",
    "publication.name": "shop_customers_pub",
    "publication.autocreate.mode": "filtered",
    "snapshot.mode": "initial",
    "snapshot.isolation.mode": "serializable",
    "skipped.operations": "none",
    "tombstones.on.delete": "true",
    "decimal.handling.mode": "string",
    "provide.transaction.metadata": "true",
    "heartbeat.interval.ms": "10000",
    "heartbeat.action.query": "INSERT INTO public.debezium_heartbeat (id, ts) VALUES (1, now()) ON CONFLICT (id) DO UPDATE SET ts = EXCLUDED.ts",
    "signal.data.collection": "public.debezium_signal",
    "incremental.snapshot.chunk.size": "1024",
    "event.processing.failure.handling.mode": "fail",
    "key.converter": "org.apache.kafka.connect.json.JsonConverter",
    "key.converter.schemas.enable": "false",
    "value.converter": "org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false"
  }
}

The Go consumer disables auto-commit, blocks rebalances during processing, applies records in fetch order, commits exactly the prefix that succeeded, and returns on the first failure. The process must then exit or rebuild its client: continuing with the next poll would let a later commit overtake the failed record. FetchIsolationLevel(ReadCommitted) matters if the topic carries transactional writes (Kafka Connect exactly-once source).

go
// Package kafka consumes one Debezium table topic from Kafka Connect.
// It commits only a prefix of successfully applied records and stops on the
// first failure, so no later commit can overtake an unapplied record.
package kafka

import (
	"context"
	"errors"
	"fmt"

	"github.com/twmb/franz-go/pkg/kgo"

	"academy/change-data-capture/after/cdc"
	"academy/change-data-capture/after/elastic"
)

// Applier is the sink; elastic.Sink satisfies it.
type Applier interface {
	Apply(context.Context, cdc.Change) (elastic.Outcome, error)
}

// Process decodes and applies records in fetch order. It returns the
// records that are safe to commit: everything before the first failure.
func Process(ctx context.Context, cfg cdc.Config, sink Applier, recs []*kgo.Record) ([]*kgo.Record, error) {
	for i, r := range recs {
		ch, err := cdc.Decode(cfg, r.Key, r.Value)
		if err != nil {
			return recs[:i], fmt.Errorf("%s/%d@%d: %w", r.Topic, r.Partition, r.Offset, err)
		}
		if _, err := sink.Apply(ctx, ch); err != nil {
			return recs[:i], fmt.Errorf("%s/%d@%d: %w", r.Topic, r.Partition, r.Offset, err)
		}
	}
	return recs, nil
}

// Run polls, applies and commits until ctx ends or anything fails. On
// failure it commits the applied prefix and returns: the process must exit
// (or rebuild its client) so the next session resumes at the failed record.
func Run(ctx context.Context, brokers []string, group, topic string, cfg cdc.Config, sink Applier) error {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.ConsumerGroup(group),
		kgo.ConsumeTopics(topic),
		kgo.DisableAutoCommit(),
		kgo.BlockRebalanceOnPoll(),
		kgo.FetchIsolationLevel(kgo.ReadCommitted()),
	)
	if err != nil {
		return err
	}
	defer cl.Close()
	for {
		fetches := cl.PollRecords(ctx, 500)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return ctx.Err()
		}
		if errs := fetches.Errors(); len(errs) > 0 {
			cl.AllowRebalance()
			return fmt.Errorf("fetch: %w", errs[0].Err)
		}
		done, procErr := Process(ctx, cfg, sink, fetches.Records())
		var commitErr error
		if len(done) > 0 {
			commitErr = cl.CommitRecords(ctx, done...)
		}
		cl.AllowRebalance()
		if err := errors.Join(procErr, commitErr); err != nil {
			return err
		}
	}
}

The PHP version uses php-rdkafka with enable.auto.commit=false and a synchronous commit($message) after each apply; an exception stops the loop before the next commit.

php
<?php

namespace App\Cdc\Transport;

use App\Cdc\CdcConfig;
use App\Cdc\ChangeEvent;
use App\Cdc\CustomerProjector;
use RdKafka\Conf;
use RdKafka\KafkaConsumer;
use RuntimeException;

// php-rdkafka directly: auto commit off, commit each message after apply,
// and throw on the first failure so no later commit overtakes it.
final class KafkaCdcConsumer
{
    public function __construct(
        private readonly CdcConfig $cfg,
        private readonly CustomerProjector $projector,
    ) {
    }

    public function run(string $brokers, string $group, string $topic): never
    {
        $conf = new Conf();
        $conf->set('metadata.broker.list', $brokers);
        $conf->set('group.id', $group);
        $conf->set('enable.auto.commit', 'false');
        $conf->set('auto.offset.reset', 'earliest');
        $conf->set('isolation.level', 'read_committed');

        $consumer = new KafkaConsumer($conf);
        $consumer->subscribe([$topic]);

        while (true) {
            $message = $consumer->consume(1000);
            if ($message->err === RD_KAFKA_RESP_ERR__TIMED_OUT || $message->err === RD_KAFKA_RESP_ERR__PARTITION_EOF) {
                continue;
            }
            if ($message->err !== RD_KAFKA_RESP_ERR_NO_ERROR) {
                throw new RuntimeException($message->errstr());
            }

            // A Kafka tombstone arrives with a null payload.
            $event = ChangeEvent::decode($this->cfg, $message->key, $message->payload);
            $this->projector->apply($event);
            $consumer->commit($message); // synchronous; throws on failure
        }
    }
}

Redis Streams ​

Debezium Server's redis sink appends each event with XADD to a stream named after the topic. In extended format an entry has fields key and value (plus upper-cased headers); in compact format the key itself is the field name. Reading the sink source at commit ae234f1: it pipelines a batch of XADDs, marks each record processed as its reply returns, and retries only the entries that got an OOM reply. Retried entries therefore land after later ones (an inference from the code, not documented behaviour), which the position contract absorbs. wait.enabled=true adds a Redis WAIT for replicas; without it, an acknowledged entry can be lost on failover of an asynchronous replica. Heartbeats are skipped by default (skip.heartbeat.messages=true). Tombstones become null.value (default default); keyless rows get null.key.

properties
# Debezium Server -> Redis Streams. Expected, not run.
debezium.sink.type=redis
debezium.sink.redis.address=redis.shop.internal:6379
debezium.sink.redis.message.format=extended
debezium.sink.redis.null.key=default
debezium.sink.redis.null.value=__debezium_null__
# Ask a replica to acknowledge before the entry counts as written.
debezium.sink.redis.wait.enabled=true
debezium.sink.redis.wait.timeout.ms=1000
debezium.sink.redis.memory.threshold.percentage=85
debezium.sink.redis.skip.heartbeat.messages=true
debezium.format.value=json
debezium.format.value.schemas.enable=false
debezium.source.connector.class=io.debezium.connector.postgresql.PostgresConnector
debezium.source.plugin.name=pgoutput
debezium.source.topic.prefix=shop
debezium.source.table.include.list=public.customers
debezium.source.skipped.operations=none
debezium.source.offset.storage=io.debezium.storage.redis.offset.RedisOffsetBackingStore
debezium.source.offset.storage.redis.address=redis.shop.internal:6379

The consumer reads its own pending entries (0) before new ones (>), and XACKs only after the sink succeeds. Do not trim casually: with the default KEEPREF, XTRIM removes bodies still referenced in a group's PEL, so a pending entry can come back with no fields; Redis 8.2's XTRIM ... ACKED only removes entries every group has acknowledged. The Go consumer stops on such an entry, because its content is gone.

go
// Package redis consumes a Debezium Server Redis-sink stream written in the
// "extended" message format (fields "key" and "value"). It drains its own
// pending entries first, then reads new ones, and XACKs only after apply.
package redis

import (
	"context"
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"

	"academy/change-data-capture/after/cdc"
	"academy/change-data-capture/after/elastic"
)

// ErrFormat means the entry is not an extended-format Debezium entry.
var ErrFormat = errors.New("redis: entry lacks string fields key and value")

// Applier is the sink; elastic.Sink satisfies it.
type Applier interface {
	Apply(context.Context, cdc.Change) (elastic.Outcome, error)
}

// Handle validates one stream entry and applies it.
func Handle(ctx context.Context, cfg cdc.Config, sink Applier, values map[string]any) error {
	k, okK := values["key"].(string)
	v, okV := values["value"].(string)
	if !okK || !okV {
		return ErrFormat
	}
	key := []byte(k)
	if cfg.NullSentinel != nil && k == "default" {
		key = nil // debezium.sink.redis.null.key for keyless rows
	}
	ch, err := cdc.Decode(cfg, key, []byte(v))
	if err != nil {
		return err
	}
	_, err = sink.Apply(ctx, ch)
	return err
}

// Run never trims the stream: trimming entries that are still pending
// (default KEEPREF) leaves PEL references whose bodies are gone.
func Run(ctx context.Context, rdb *redis.Client, stream, group, consumer string, cfg cdc.Config, sink Applier) error {
	if cfg.NullSentinel == nil {
		return errors.New("redis: set NullSentinel to debezium.sink.redis.null.value")
	}
	err := rdb.XGroupCreateMkStream(ctx, stream, group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	start := "0" // first our own PEL (entries read but never acked), then ">"
	for ctx.Err() == nil {
		res, err := rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group: group, Consumer: consumer, Streams: []string{stream, start}, Count: 100, Block: 5 * time.Second,
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue // block timed out with nothing new
		}
		if err != nil {
			return err
		}
		n := 0
		for _, s := range res {
			for _, m := range s.Messages {
				n++
				if len(m.Values) == 0 { // pending ID whose body was trimmed away
					return fmt.Errorf("entry %s: body deleted while pending; rebuild in a new epoch", m.ID)
				}
				if err := Handle(ctx, cfg, sink, m.Values); err != nil {
					return fmt.Errorf("entry %s: %w", m.ID, err)
				}
				if err := rdb.XAck(ctx, stream, group, m.ID).Err(); err != nil {
					return fmt.Errorf("xack %s: %w", m.ID, err)
				}
			}
		}
		if start == "0" && n == 0 {
			start = ">"
		}
	}
	return ctx.Err()
}
php
<?php

namespace App\Cdc\Transport;

use App\Cdc\CdcConfig;
use App\Cdc\ChangeEvent;
use App\Cdc\CustomerProjector;
use App\Cdc\InvalidChangeEvent;
use Illuminate\Support\Facades\Redis;

// Raw Redis Streams through the facade (phpredis argument order assumed).
// Expects debezium.sink.redis.message.format=extended: fields key and value.
final class RedisCdcConsumer
{
    public function __construct(
        private readonly CdcConfig $cfg,
        private readonly CustomerProjector $projector,
    ) {
    }

    public function run(string $stream, string $group, string $consumer): never
    {
        $redis = Redis::connection('cdc');
        $start = '0'; // our own pending entries first, then new ones

        while (true) {
            $batch = $redis->command('xreadgroup', [$group, $consumer, [$stream => $start], 100, 5000]);
            $entries = is_array($batch) ? ($batch[$stream] ?? []) : [];

            foreach ($entries as $id => $fields) {
                if (! is_array($fields) || ! is_string($fields['key'] ?? null) || ! is_string($fields['value'] ?? null)) {
                    throw InvalidChangeEvent::because("stream entry {$id} is not extended format or its body was trimmed");
                }
                $event = ChangeEvent::decode($this->cfg, $fields['key'], $fields['value']);
                $this->projector->apply($event);
                $redis->command('xack', [$stream, $group, [$id]]);
            }

            if ($start === '0' && $entries === []) {
                $start = '>';
            }
        }
    }
}

In production systems ​

  • PostgreSQL documents that slots retain WAL and catalog rows with no consumer attached, that max_slot_wal_keep_size defaults to -1, and that invalidated slots report invalidation_reason; slot monitoring is not optional.
  • Debezium documents at-least-once delivery during faults and tells consumers to "anticipate some duplicate events"; that is a design input for every sink.
  • Debezium's MySQL connector requires a single-partition schema history topic; an auto-created multi-partition topic is a documented misconfiguration.
  • Kafka documents that consumers lagging beyond delete.retention.ms can miss delete markers on compacted topics.
  • RabbitMQ documents that unroutable messages are confirmed; Debezium Server's RabbitMQ sink waits for confirms but does not publish as mandatory.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A shop monolith keeps orders in PostgreSQL and a product search in Elasticsearch. Instead of calling the index after each save, one Debezium connector captures products, one Go consumer applies changes with the position guard. The application code loses all search calls; the operations team gains a slot to monitor.

Modular monolith: explicit owners ​

Catalog and Pricing share a database but own different tables. Each module's derived views get their own connector and slot (or one connector with clear topic ownership), and each projection has an owner who decides re-snapshots. Raw table events stay inside the module; another module consumes them only through an outbox contract.

Microservices: events cross boundaries, tables do not ​

The Orders service writes orders and an outbox row in one transaction; Debezium's Outbox Event Router publishes outbox.event.order; Billing and Shipping consume it with inbox deduplication. Orders' own search index, owned by the Orders team, may still use raw table CDC. A dashboard joining orders and payments topics by arrival time is wrong; it must join by keys and tolerate lag.

Distributed data: replicas, failover and regions ​

Logical decoding normally runs on the primary; a standby can host a logical slot only with hot_standby_feedback and preferably a physical slot. Failover without a synced failover slot breaks lineage: start a new epoch. Multi-region replication of the CDC topic does not create a global order: each region's consumers see the same per-key order but at different times. A restored database reuses LSN ranges; never compare positions across the restore.

Scaling path ​

LoadDesignExample
1xOne connector, one slot, one consumer per sink50 changes/s into one search index
10xPartitioned topics by key, consumer group per sink, slot and lag alerts, incremental snapshots for backfills5,000 changes/s, three derived stores
100xSeveral connectors per table group, separate slots, a platform team owning offsets, schema registry and rebuild epochs; batched sink writes50,000 changes/s across many services; rebuilds run as routine operations

At 100x the WAL decoder itself becomes a cost: each slot decodes the WAL independently, so ten connectors on one database mean ten decoders. Consolidate tables per connector where ownership allows.

Lab ​

Expected, not run. Commands assume an existing disposable PostgreSQL 17+ with wal_level=logical, and a Kafka Connect cluster with the Debezium PostgreSQL connector; this chapter starts no containers. The Go tests run without any server.

1. Run the contract tests ​

bash
cd docs/snippets/messaging/change-data-capture/go
go test ./...
# expected: ok  academy/change-data-capture/after/cdc
#           ok  academy/change-data-capture/after/elastic
#           ok  academy/change-data-capture/after/kafka   (prefix-only commit)
#           ok  academy/change-data-capture/after/rabbitmq
#           ok  academy/change-data-capture/after/redis

2. Watch a slot pin WAL ​

bash
psql -c "SELECT pg_create_logical_replication_slot('lab_slot', 'pgoutput');"
pgbench -i -s 10 && pgbench -T 60
psql -c "SELECT slot_name, wal_status, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) FROM pg_replication_slots;"
# expected: lab_slot | reserved | 180 MB (grows with pgbench, nobody consumes)
psql -c "SELECT pg_drop_replication_slot('lab_slot');"

3. Peek at decoded changes with wal2json or test_decoding ​

bash
psql -c "SELECT pg_create_logical_replication_slot('peek', 'test_decoding');"
psql -c "UPDATE customers SET email='lab@example.com' WHERE id=1;"
psql -c "SELECT lsn, xid, data FROM pg_logical_slot_peek_changes('peek', NULL, NULL);"
# expected: BEGIN 771 / table public.customers: UPDATE: id[integer]:1 email[text]:'lab@example.com' ... / COMMIT 771
psql -c "SELECT pg_drop_replication_slot('peek');"
# wal2json variant (plugin installed): pg_recvlogical -d shop --slot w2j --create-slot -P wal2json
#                                      pg_recvlogical -d shop --slot w2j --start -o format-version=2 -f -
# expected: {"action":"U","schema":"public","table":"customers",...} per change

4. TOAST placeholder ​

bash
psql -c "ALTER TABLE customers ADD COLUMN bio text; UPDATE customers SET bio = repeat('x', 100000) WHERE id = 1;"
psql -c "UPDATE customers SET email='toast@example.com' WHERE id = 1;"
kcat -C -b kafka.lab:9092 -t shop.public.customers -o -1 -e | jq '.after.bio'
# expected: "__debezium_unavailable_value"
psql -c "ALTER TABLE customers REPLICA IDENTITY FULL;"   # repeat the update: bio is present

5. Incremental snapshot signal ​

bash
psql -c "INSERT INTO debezium_signal (id, type, data) VALUES ('lab-1', 'execute-snapshot', '{\"data-collections\": [\"public.customers\"], \"type\": \"incremental\"}');"
kcat -C -b kafka.lab:9092 -t shop.public.customers -e | jq -c '[.op, .source.snapshot]' | sort | uniq -c
# expected: N ["r","incremental"] plus any concurrent ["u","false"] events

6. Truncate fail-stop ​

bash
psql -c "TRUNCATE customers;"   # connector has skipped.operations=none
# expected consumer log: cdc: truncate needs an operator decision (rebuild in a new epoch); no offset committed

Common misconceptions ​

BeliefReality
Log-based CDC only reads a log that exists anywayIt retains WAL/binlog for you, decodes it, snapshots tables and ships events; all cost resources
Debezium's PostgreSQL default plugin is pgoutputIn 3.7 the default is decoderbufs; set pgoutput explicitly
A stopped connector is harmlessIts slot pins WAL (unlimited by default) and catalog rows
CDC is exactly onceAt least once after faults; duplicates are documented
A "max LSN applied" checkpoint deduplicates safelyInterleaved transactions decode lower LSNs later; snapshots share a position; restores reuse ranges
Topics give a global orderOrder exists per key within one partition only
The tombstone is the delete eventThe d event is the delete; the tombstone serves compaction
A compacted topic can always rebuild a sinkNot after delete.retention.ms or retention loss
after is the full rowUnchanged TOAST columns arrive as a placeholder with REPLICA IDENTITY DEFAULT
Schema history is the schema registryHistory is internal connector state; the registry serves consumers
GTIDs make every failover safeOnly if the new server has the transactions and the binlog files
A RabbitMQ confirm means a queue got itUnroutable messages are confirmed too
Trimming a Redis stream is housekeepingPending entries can lose their bodies
Truncates are captured by defaultDebezium's skipped.operations default is t

Cheat sheet ​

TopicRemember
PostgreSQL setupwal_level=logical, pgoutput, filtered publication, one slot per connector
Slot safetymax_slot_wal_keep_size, alert on retained WAL and wal_status
Two LSNsrestart_lsn = oldest needed; confirmed_flush_lsn = consumer confirmed
Quiet databasesheartbeat.interval.ms + heartbeat.action.query on a published table
FailoverPG 17+: slot.failover, sync_replication_slots, synchronized_standby_slots
MySQLROW, FULL, unique database.server.id, GTIDs, retention longer than outages
Schema historyOne partition, internal; not the schema registry
EnvelopeValidate source table, key vs row, op set; fail-stop on the rest
DeletesKeep deleted markers with positions; tombstones only for compaction
TOASTMerge placeholders from stored state or use REPLICA IDENTITY FULL
OrderingPer key per partition; compare (epoch, rank, commit, change) in the sink
Snapshotsr rows create, never overwrite; incremental snapshots use watermarks and the signal table
Truncateskipped.operations=none, then fail-stop and rebuild
RabbitMQ sinkBind queues first; confirms do not prove routing; distinct null.value
Redis sinkextended format, wait.enabled, never trim pending entries
Kafka consumerCommit the applied prefix only; stop on failure

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a stopped Debezium connector bring down a PostgreSQL server? Important ​

Answer

Answer: Its replication slot keeps WAL from restart_lsn and catalog rows; with max_slot_wal_keep_size = -1 retention is unlimited until the disk fills, and held catalog rows can in extreme cases force a shutdown to avoid transaction ID wraparound.

2 — What is the difference between restart_lsn and confirmed_flush_lsn? Good to know ​

Answer

Answer: restart_lsn is the oldest WAL the slot may still need to restart decoding; confirmed_flush_lsn is how far the consumer has confirmed receiving. Data committed before confirmed_flush_lsn will not be sent again.

3 — Why is "skip every event with an LSN at or below the highest one applied" unsafe? Important ​

Answer

Answer: Logical decoding emits transactions in commit order, but a later-committing transaction can contain changes with lower LSNs than an earlier-committing one, so a shared checkpoint skips them. Snapshot rows also share one position, and restores or new slots break lineage. Compare a commit-first position per key, inside one epoch.

4 — Which Debezium setting must you change to make a consumer fail on truncates? Good to know ​

Answer

Answer: skipped.operations, whose default is t; set it to none so op = t events reach the consumer, which then stops for a rebuild.

5 — A RabbitMQ consumer receives the bytes default. What happened? Good to know ​

Answer

Answer: Debezium Server's RabbitMQ sink replaced a tombstone's null value with null.value, whose default is default. Configure a distinctive sentinel and match it exactly, or disable tombstones for that sink.

6 — Why does the sink keep a deleted marker instead of deleting the document? Must-know ​

Answer

Answer: A delayed older update would otherwise recreate the row. The marker keeps the delete's position so later-arriving older events compare lower; Elasticsearch keeps a real delete's version only for index.gc_deletes.

7 — When can a compacted Kafka topic not rebuild a projection? Important ​

Answer

Answer: When the rebuild takes longer than delete.retention.ms (tombstones removed), when time retention removed records, or when the needed history predates the topic; then take a new snapshot.

8 — What do the low and high watermarks do in an incremental snapshot? Good to know ​

Answer

Answer: They open and close a window around each chunk read. Streamed changes for keys in the buffered chunk during the window evict the stale READ rows, and the rest are emitted at the high watermark.

9 — Why must the schema history topic have one partition? Important ​

Answer

Answer: The connector replays it in order to rebuild table shapes for old binlog positions; Debezium requires a consistent global order, which multiple partitions do not provide.

10 — Why does the Kafka consumer stop after a failed record instead of continuing? Must-know ​

Answer

Answer: Kafka commits a position, not individual records. Any later commit in that partition would pass the failed record, so the consumer commits only the applied prefix and exits.

11 — What does HTTP 409 mean for the Elasticsearch sink? Good to know ​

Answer

Answer: Only version_conflict_engine_exception after the retry_on_conflict retries counts as a concurrency conflict, and it is retryable. Stale events return result: noop. Any other 409 type is an unexpected rejection.

Glossary ​

TermMeaning
CDC (Change Data Capture)Capturing committed changes from a database for other systems
Query-based CDCPolling a table with a change predicate
Trigger-based CDCTriggers writing changes to an audit table
Log-based CDCDecoding changes from the transaction log
WALPostgreSQL write-ahead log
Logical decodingPostgreSQL feature turning WAL into row changes via an output plugin
pgoutputPostgreSQL's built-in logical decoding plugin, driven by publications
wal2jsonThird-party plugin emitting JSON changes
decoderbufsDebezium's Protobuf plugin; Debezium 3.7's plugin.name default
PublicationPostgreSQL set of tables (and operations) a pgoutput stream carries
Replication slotCrash-safe server-side position that retains WAL for one consumer
restart_lsnOldest WAL a slot may still need
confirmed_flush_lsnPosition up to which the slot's consumer confirmed receipt
max_slot_wal_keep_sizeCap on WAL retained by slots; default -1 (unlimited)
idle_replication_slot_timeoutInvalidates slots idle longer than this; default off
Slot invalidationSlot becoming unusable (wal_removed, rows_removed, idle_timeout, wal_level_insufficient)
Failover slotsLogical slots synchronized to standbys (PostgreSQL 17+)
synchronized_standby_slotsPhysical slots logical senders wait for before sending
REPLICA IDENTITYTable setting for which old column values are logged
TOASTPostgreSQL out-of-line storage for large values
unavailable.value.placeholderDebezium marker for unchanged TOAST values not in the event
binlogMySQL binary log of change events
binlog_row_imageMySQL row image size; Debezium needs FULL
GTIDMySQL global transaction identifier source_id:transaction_id
server-idUnique ID the connector uses to join a MySQL topology (database.server.id)
DebeziumOpen-source CDC connector family
Kafka ConnectKafka's connector runtime hosting Debezium connectors and offsets
Debezium ServerStandalone runtime sending Debezium events to non-Kafka sinks
EnvelopeEvent value with before, after, op, source, ts_ms
before/afterRow images before and after the change
opOperation code: c, u, d, r, t, m
ts_msConnector processing time (top level) or source change time (source.ts_ms)
source.lsnWAL position of a PostgreSQL change; source.sequence adds last committed LSN
SnapshotConsistent copy of existing rows emitted as op = r
Incremental snapshotChunked snapshot running alongside streaming
WatermarkSignal-table marker opening or closing an incremental snapshot window
Signal tableTable (signal.data.collection) through which signals such as execute-snapshot are sent
Schema historyInternal connector topic of DDL used for recovery (single partition)
Schema registryService storing serialized-format schemas and compatibility rules for consumers
Transaction metadataBEGIN/END events and transaction fields when provide.transaction.metadata=true
HeartbeatPeriodic connector record (and optional heartbeat.action.query) to advance offsets
TombstoneKafka record with a key and null value marking a key for compaction removal
Log compactionKafka retention keeping the latest record per key
delete.retention.msHow long Kafka keeps tombstones on compacted topics
delete.tombstone.handling.modeEvent-flattening SMT option for deletes and tombstones
Outbox event routerDebezium SMT mapping outbox inserts to routed, keyed records
Idempotent sinkSink whose result does not change when an event is applied again
UpsertInsert-or-update by key
External versionElasticsearch version_type=external: write only if a supplied long is higher
ElasticsearchSearch engine used here as the example sink
Epoch (lineage)This page's name for one unbroken log history plus its target index
Null sentinelString Debezium Server sends instead of a null value (null.value)

References ​

Built by Morteza Negahi