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 withON 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 onpg_replication_slotslag plusmax_slot_wal_keep_sizeas 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?
Keep reading
Related articles from the SudoSecurity blog.
PostgreSQL 19 Is Out. REPACK Kept My Writes Running. The Docker Upgrade Will Stop Your App.
PostgreSQL 19 shipped on November 19 with REPACK (CONCURRENTLY), which removes table bloat without blocking writes. I measured it against VACUUM FULL, ran the upgrade from 18, and checked what breaks for self-hosters: Docker tags that refuse to start, a config setting that stops the server, and...
PostgreSQL Fixed 52 CVEs in One Release. The Upgrade Is the Easy Part.
PostgreSQL 18.7, 17.12, 16.16, 15.20 and 14.25 fix 52 security vulnerabilities, almost twice August's record of 28. The binary swap took under a second in my test. The post-update steps are where the work is, and one of them makes some indexes several times bigger.
What PostgreSQL 15 Changed
A new version of the popular open-source database PostgreSQL is now available, offering performance improvements over PostgreSQL 14 and new functions and capabilities for managing workloads in local and distributed deployments. Released on October 13 by the PostgreSQL Global Development Group,…
PHP API Performance: N+1 Queries, cURL, and Connection Pools
A PHP API case study: fixing an N+1 query, twenty serial cURL calls, missing connection pooling, and stats recalculated on every request with Redis caching.