Snapshots, Schema Changes and Slot Lag
Check the hand-off from the initial snapshot to the stream by log position, add a column at the source and backfill it with an incremental snapshot, watch a forgotten replication slot fill the WAL until PostgreSQL invalidates it, and set recovery bounds from slot limits and Kafka topic retention.
Contentsand lesson path
On this page
- Why it matters
- The initial snapshot and the hand-off to the stream
- A schema change at the source
- Backfill with an incremental snapshot
- Slot lag and a full disk
- Deletes, retention and the recovery bound
- Check your understanding
- Apply it
- Review prompt
Lessons of Change Data Capture
- Three Ways to Detect That Data Changed Concept · 20 min
- Logical Decoding and the Write-Ahead Log Concept · 20 min
- Lab: PostgreSQL to Kafka with Debezium Lab · 30 min
- Worked Example: Applying Changes in Order with MERGE Worked example · 25 min
- Snapshots, Schema Changes and Slot Lag Concept · 20 min
- Check: CDC Failure Modes Knowledge check · 8 questions
What you will learn
- Handle the initial snapshot, source schema changes and replication-slot lag without losing or duplicating changes.
Prerequisites: Messaging & Event Streaming
01. Why it matters
A CDC pipeline that works on its first day can still fail later, usually at one of three moments: at the start, when existing rows must be copied without losing or repeating the changes made meanwhile; at a schema change at the source, which arrives without warning; and during a long consumer outage, when the database and Kafka must keep what has not been read, within limits.
This lesson uses the containers, topic and replica from the worked example, so run that first. Work in the cdc-lab folder, with the virtual environment active and DATABASE_URL set. A separate small PostgreSQL container shows the slot limits.
02. The initial snapshot and the hand-off to the stream
With the default snapshot.mode=initial, a new connector with no stored offset opens a transaction that sees one consistent state of the database, notes the current LSN, reads every captured row as an r event, and commits. Then it streams from the LSN it noted. A change committed before that LSN is in the snapshot rows; a change committed after it comes from the stream. So snapshot and stream meet at one log position. If the connector stops during the snapshot, it starts the snapshot again.
Other modes change when a snapshot runs. no_data never takes one and streams from where the slot was created; use it only when the target already has the data. when_needed takes one if there is no offset or the stored LSN is no longer on the server. always takes one on every start. You can check the hand-off in the topic: the script groups all events by op, snapshot marker and LSN compared with the first snapshot event.
#!/usr/bin/env bash
# Group the change events (not tombstones) by op, snapshot marker and LSN position.
docker exec cdc-kafka /opt/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:29092 --topic shop.public.orders \
--from-beginning --timeout-ms 5000 2>/dev/null |
jq -sr '
map(select(. != null)) as $events
| $events[0].source.lsn as $snap
| $events
| map({op, s: .source.snapshot,
pos: (if .source.lsn == null then "no LSN"
elif .source.lsn == $snap then "LSN = snapshot LSN"
elif .source.lsn > $snap then "LSN > snapshot LSN"
else "LSN < snapshot LSN" end)})
| group_by([.op, .s, .pos]) | .[]
| "\(length) x op=\(.[0].op) snapshot=\(.[0].s): \(.[0].pos)"
'chmod +x handoff.sh
./handoff.sh4 x op=c snapshot=false: LSN > snapshot LSN
3 x op=d snapshot=false: LSN > snapshot LSN
1 x op=r snapshot=first: LSN = snapshot LSN
1 x op=r snapshot=last: LSN = snapshot LSN
1 x op=r snapshot=true: LSN = snapshot LSN
5 x op=u snapshot=false: LSN > snapshot LSNThe snapshot rows carry the snapshot LSN and every streamed change a larger one. None is smaller: that is a clean hand-off. Repeat the check whenever you rebuild a connector or move it to another server.
03. A schema change at the source
Logical decoding does not decode DDL statements such as ALTER TABLE, so no event announces a new column. pgoutput sends a new relation message with the next change to the table, and Debezium refreshes its picture of the table from it. Add a column with a default, count the records, then insert an order.
ALTER TABLE orders ADD COLUMN currency text NOT NULL DEFAULT 'EUR';./events.sh | wc -l
docker exec -i cdc-pg psql -U postgres -d shop -X -q < add-column.sql
sleep 3
./events.sh | wc -l
docker exec cdc-pg psql -U postgres -d shop -X -q \
-c "INSERT INTO orders VALUES (7, 'gus', 'placed', 30.00, 'GBP')"
sleep 3
./events.sh | tail -n 1
python apply.py18
18
18 key={"id":7} op=c snapshot=false before=null after=7,gus,placed,30.00,GBP
offsets 18-18: 1 records, 0 tombstones, 1 keys -> insert 1, update 0, delete 0, skip 0
done: 1 batchesThe ALTER TABLE produced no record. The insert carries the new field as the fifth value, while older events keep their old shape, because Kafka never rewrites records. apply.py applied order 7 without complaint, because it reads only the fields it knows. That is the danger: the replica has no currency column, and nothing failed. A consumer should either fail loudly on unknown fields or be changed before the source sends them.
With a schema registry and Avro, the connector registers a new version of the value schema when the table changes, and the registry checks it against a compatibility mode. Confluent Schema Registry's default, BACKWARD, means consumers with the new schema can read data written with the old one. Adding an optional field, or one with a default, passes; renaming a column or changing its type incompatibly does not. Under BACKWARD, upgrade consumers before producers use the new schema. At the source, the safe order is the same in every format: add columns as optional or with a default, change the consumers, backfill, and only then drop or rename old columns.
04. Backfill with an incremental snapshot
Old events have no currency, so a consumer that needs it must read the current rows again. Repeating the initial snapshot would pause the stream. An incremental snapshot reads the table in chunks (1,024 rows by default) while streaming continues. Debezium writes an open and a close marker for each chunk into a signalling table and reads the chunk in between; if a streamed change hits a row of the chunk, the streamed event wins and the read is dropped. You request one by inserting a row into the signalling table. The connector names the table in signal.data.collection, and the connector user must be able to write to it. The request reaches Debezium through the change stream, so with pgoutput the table must also be in the publication.
-- Debezium reads requests from this table and writes its chunk markers into it.
CREATE TABLE debezium_signal (id text PRIMARY KEY, type text NOT NULL, data text);
GRANT SELECT, INSERT, UPDATE, DELETE ON debezium_signal TO debezium;
-- pgoutput only sends tables in the publication, so the signals must be in it too.
ALTER PUBLICATION dbz_publication ADD TABLE debezium_signal;INSERT INTO debezium_signal (id, type, data) VALUES (
'backfill-currency', 'execute-snapshot',
'{"data-collections": ["public.orders"], "type": "incremental"}');docker exec -i cdc-pg psql -U postgres -d shop -X -q -v ON_ERROR_STOP=1 < signal.sql
jq '. + {"signal.data.collection": "public.debezium_signal"}' \
orders-connector.json > orders-connector-signal.json
curl -s -X PUT -H 'Content-Type: application/json' \
--data @orders-connector-signal.json localhost:28083/connectors/orders-cdc/config \
| jq -r '.config["signal.data.collection"]'
sleep 5
until curl -s localhost:28083/connectors/orders-cdc/status \
| grep -q '"tasks":\[{"id":0,"state":"RUNNING"'; do sleep 2; done
docker exec -i cdc-pg psql -U postgres -d shop -X -q < backfill.sql
sleep 5
./events.sh | tail -n 5
./handoff.sh | grep incremental
python apply.py
docker exec -i cdc-pg psql -U postgres -d shop -X -q < compare.sql | head -n 3public.debezium_signal
19 key={"id":1} op=r snapshot=incremental before=null after=1,ana,shipped,22.00,EUR
20 key={"id":2} op=r snapshot=incremental before=null after=2,ben,shipped,35.00,EUR
21 key={"id":3} op=r snapshot=incremental before=null after=3,chen,placed,14.00,EUR
22 key={"id":6} op=r snapshot=incremental before=null after=6,fay,placed,42.00,EUR
23 key={"id":7} op=r snapshot=incremental before=null after=7,gus,placed,30.00,GBP
5 x op=r snapshot=incremental: no LSN
offsets 19-23: 5 records, 0 tombstones, 5 keys -> insert 0, update 5, delete 0, skip 0
done: 1 batches
problem | id | customer | status | amount
---------+----+----------+--------+--------
(0 rows)The five live orders arrived again as r events with currency, marked snapshot=incremental. Unlike the initial snapshot, these reads carry no LSN (source.lsn is null in Debezium 3.7.1). An apply step that orders or de-duplicates by LSN alone cannot place them. The worked example's guard falls back to the Kafka offset, so it applied all five as updates, and the replica still matches. To keep currency, add it to the replica and merge.sql first, then signal again; that is the exercise below.
05. Slot lag and a full disk
A replication slot promises its reader that PostgreSQL keeps every WAL file from the slot's restart_lsn onwards. If the reader stops, the WAL grows until the disk is full and the database stops accepting writes. max_slot_wal_keep_size limits the promise: past that size, a checkpoint may remove the WAL anyway, and the slot becomes unusable. The default, -1, means no limit. pg_replication_slots.wal_status shows the state: reserved (within max_wal_size), extended (more, still kept), unreserved (will be removed at the next checkpoint) and lost. safe_wal_size is how many more bytes can be written before the slot is lost.
The demonstration uses a separate container with a 128 MB limit and a slot nobody reads. Each round writes about 30 MB of WAL. Sizes are rounded to 10 MB; other versions may differ slightly, but the states come in the same order.
-- How much WAL the slot holds back, and whether any headroom is left.
SELECT :'round' AS round, active, wal_status,
round(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) / 10485760) * 10
AS retained_mb,
safe_wal_size > 0 AS headroom
FROM pg_replication_slots
WHERE slot_name = 'lagging';-- Roughly 30 MB of WAL per run: 40,000 rows inserted and deleted again.
INSERT INTO filler SELECT g, repeat('x', 500) FROM generate_series(1, 40000) AS g;
DELETE FROM filler;docker run -d --name cdc-lag --tmpfs /var/lib/postgresql/data \
-e POSTGRES_PASSWORD=lag postgres:17-alpine -c wal_level=logical \
-c max_wal_size=64MB -c max_slot_wal_keep_size=128MB > /dev/null
until docker exec cdc-lag pg_isready -h 127.0.0.1 -U postgres >/dev/null; do
sleep 1
done
docker exec cdc-lag psql -U postgres -X -q -At \
-c "CREATE TABLE filler (id int PRIMARY KEY, pad text)" \
-c "SELECT slot_name
FROM pg_create_logical_replication_slot('lagging', 'test_decoding')"
for round in 1 2 3 4 5 6; do
docker exec -i cdc-lag psql -U postgres -X -q < write-wal.sql
docker exec -i cdc-lag psql -U postgres -X -q -At -F ' | ' -v round=$round \
< lag-status.sql
done
docker exec cdc-lag psql -U postgres -X -q \
-c "SELECT count(*) FROM pg_logical_slot_get_changes('lagging', NULL, NULL)"lagging
1 | f | reserved | 30 | t
2 | f | reserved | 60 | t
3 | f | reserved | 90 | t
4 | f | extended | 120 | t
5 | f | unreserved | 150 | f
6 | f | lost | |
ERROR: can no longer get changes from replication slot "lagging"
DETAIL: This slot has been invalidated because it exceeded the maximum reserved size.Up to 90 MB the slot is reserved, although max_wal_size is 64 MB: PostgreSQL decides the state in whole 16 MB WAL segments, with one extra segment of slack, and the lag column here is rounded to 10 MB, so the switch comes between about 80 and 96 MB rather than exactly at 64 MB. At 120 MB it is extended: more WAL than max_wal_size, kept only for the slot. At 150 MB it is past the limit, without headroom, unreserved. During round 6 a checkpoint removed the WAL and the slot became lost; reading it fails. For Debezium, this is when its stored LSN no longer exists. The disk is safe, but the connector cannot resume: it needs a new slot and a new snapshot (for example with snapshot.mode=when_needed), and the replica must be compared again.
So choose: without a limit, a dead connector can stop the database; with one, the database survives and the pipeline needs a rebuild. Most teams set a limit and alert well before it, on wal_status leaving reserved, on safe_wal_size, or on pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn). PostgreSQL 18 adds idle_replication_slot_timeout, which invalidates slots inactive for too long. One more cause of lag: heavy writes to tables that are not captured. The connector receives nothing, so it confirms nothing, and WAL piles up. Debezium's heartbeat.interval.ms with heartbeat.action.query, writing to a small captured table, gives it something to confirm.
06. Deletes, retention and the recovery bound
Kafka has limits too. Look at the settings of the orders topic, which Connect created with the broker defaults:
docker exec cdc-kafka /opt/kafka/bin/kafka-configs.sh \
--bootstrap-server localhost:29092 --describe --all \
--entity-type topics --entity-name shop.public.orders \
| grep -E '^ *(cleanup.policy|retention.ms|delete.retention.ms)=' | cut -d ' ' -f 3cleanup.policy=delete
delete.retention.ms=86400000
retention.ms=604800000With cleanup.policy=delete, Kafka removes old segments after retention.ms, here 7 days. A consumer down for longer finds its offset gone and misses changes, deletes included. Many teams compact CDC topics instead (cleanup.policy=compact), so the latest event of every key stays and a new consumer can rebuild the table from the topic. Then delete.retention.ms (1 day by default) matters. After a delete, the tombstone lets compaction remove all earlier records of the key, the delete event included, and after delete.retention.ms the tombstone can go too. A consumer more than that far behind may never see the delete, so its replica keeps a row that no longer exists.
Write these limits down as your recovery bounds: the longest consumer outage that the slot limit, retention.ms and delete.retention.ms allow, and what you do after a longer one: a new snapshot into the replica, then the EXCEPT comparison from the worked example. Remove all containers when you finish:
docker rm -f -v cdc-lag cdc-connect cdc-pg cdc-kafkacdc-lag
cdc-connect
cdc-pg
cdc-kafka07. Check your understanding
08. Apply it
Finish the skill practice. Add currency to replica.orders, to the staging table, to to_row in apply.py and to both UPDATE and INSERT branches of merge.sql, then send a new signal (use a new id) and extend compare.sql to compare currency too. Then measure the two kinds of lag separately. Pause the connector (curl -X PUT localhost:28083/connectors/orders-cdc/pause), make changes, and watch pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) for debezium_orders grow; resume it. Stop apply.py, make changes, and watch the consumer lag in kafka-consumer-groups.sh --describe --group replica-apply; the slot is not affected by this one. Then write one paragraph with your recovery bounds: the slot limit, the topic retention, and how you rebuild the replica when an outage is longer.
09. Review prompt
Without looking back, explain: how the initial snapshot and the stream meet at one LSN; why an added column appears only with the next change, and in what order to change source and consumers; how an incremental snapshot avoids overwriting newer changes and what position its reads carry; what reserved, extended, unreserved and lost mean for a slot; and how retention.ms and delete.retention.ms limit how long a consumer may be down.
References
- Debezium: PostgreSQL Connector (snapshots, incremental snapshots, WAL disk space)
- Debezium: Sending signals to a Debezium connector
- PostgreSQL Documentation: pg_replication_slots
- PostgreSQL Documentation: Replication settings (max_slot_wal_keep_size)
- Apache Kafka: Topic configs (retention.ms, delete.retention.ms)
- Confluent Schema Registry: Schema evolution and compatibility
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.