Skip to content

Lesson 12 of 13 · 16m

Incremental Sync and Change Data Capture

Watermark syncs drop rows committed out of order and CDC replay is at-least-once — overlap, dedup, and watch pg_replication_slots before it eats the disk.

The first incremental sync everyone writes is WHERE updated_at > :last_watermark ORDER BY updated_at. It works for exactly as long as nothing interesting happens. Then a long transaction lands: a batch update opened at 14:00 with updated_at = 14:00 stamps commits at 14:45. Your watermark already passed 14:30. The committed rows have updated_at values behind your watermark — they exist, they changed, and your sync will never see them again.

The wrong model: updated_at is a reliable cursor

updated_at is a timestamp, not a sequence. Transaction commit order and updated_at order are not the same order, because MVCC lets a slow transaction finish after faster ones while carrying older timestamps. Any watermark sync that treats > last_seen as airtight is guaranteed to silently drop rows — not often, which is worse than never, because the drop is invisible until someone reconciles counts.

The working fix has two parts: overlap and dedup. Set the next watermark to max(updated_at) minus a safety margin — seconds, scaled to your longest plausible transaction — and accept that you'll re-read some rows. Then make the consumer idempotent: INSERT ... ON CONFLICT (id) DO UPDATE upserts by primary key, so re-reads are harmless rewrites instead of duplicates. And the watermark query needs its own index on updated_at — every incremental pull is a range scan, and without the index it's a seq scan every time.

Ties need a second sort key: (updated_at, id) as the cursor pair, WHERE (updated_at, id) > (:w_ts, :w_id) using row comparison — a plain > on updated_at alone loses rows that share a timestamp at the page boundary.

CDC: reading the WAL instead of the table

Logical decoding skips updated_at entirely: the database writes every change to the write-ahead log, and a replication slot lets a consumer decode that WAL stream into row changes. Postgres 10 (October 2017) shipped native logical replication — CREATE PUBLICATION on the source, CREATE SUBSCRIPTION on the target — and the same machinery underpins Debezium, pglogical, and every "stream Postgres to Kafka" stack. Requirements: wal_level = logical (needs a restart to change) and a replication slot per consumer.

The production-critical fact about slots is the one nobody reads until the incident: a slot holds its WAL. If the consumer dies, the slot doesn't release the WAL it's owed — pg_wal accumulates every change since the slot's restart_lsn, and it grows until the disk fills and Postgres halts. "Kafka connector died quietly on Friday" becomes "database outage on Tuesday," and the on-call has to connect those dots. Postgres 13 added max_slot_wal_keep_size to cap retained WAL — the trade being that a slot exceeding it is invalidated, so you choose between losing the replica's position and losing the disk. Monitor pg_replication_slots — active, restart_lsn, confirmed_flush_lsn lag — like you'd monitor disk space, because it's the same emergency.

Exactly-once is the lie pipelines tell

CDC is at-least-once. A consumer that crashes after applying a change but before confirming the flush gets that change again on restart. The wrong model — "the stream can't duplicate" — produces pipelines that double-count revenue the first time they hiccup. Idempotency is the entire answer: every consumer writes through ON CONFLICT upserts keyed on the source's primary key, or tracks applied LSNs, so replayed changes are no-ops. Design for replay and the duplicates stop existing as a category.

Deletes come through the stream too, as tombstones — if your warehouse needs them, consume them; if it doesn't, know you're accumulating rows the source already dropped.

What to actually do

  • Watermark syncs: overlap the watermark by your longest transaction plus slack, sort by (updated_at, id), dedupe with ON CONFLICT — never trust > alone.
  • Index updated_at; every pull is a range scan.
  • For true CDC: wal_level = logical, publications, one slot per consumer — and alerting on pg_replication_slots lag plus max_slot_wal_keep_size as the disk-full backstop.
  • Every consumer is idempotent. At-least-once plus idempotent writes is the honest version of exactly-once.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.