Skip to main content

Worked design: CDC from Postgres to the lakehouse

Replicate a production Postgres into the lakehouse with CDC

System designmediummid · senior · lead45 min
#cdc#lakehouse#schema-evolution

The orders service runs on Postgres: about 200 tables, the largest with 2 billion rows and 5,000 writes per second. Today a nightly SELECT * dump feeds the warehouse, and it now takes 9 hours and slows the primary.

Design a change data capture (CDC) pipeline that keeps lakehouse tables within 10 minutes of the source, without hurting production. Cover the initial load, deletes, schema changes and how you know the copy is correct.

Hint 1

How do you take a consistent initial snapshot and then switch to the change stream without gaps or duplicates?

Hint 2

What happens to a downstream table when someone adds or renames a column?

Show solution

Postgres logical replication (a publication plus a replication slot) → Debezium → Kafka (one topic per table, keyed by primary key) → a merge job writes Iceberg/Delta tables: an append-only change log (_bronze) and a current-state table (_silver) maintained by MERGE on the primary key, ordered by the source LSN.

The main points: use an incremental snapshot so the initial load doesn't lock tables, and so snapshot and stream overlap safely (dedup by PK + LSN); deletes arrive as tombstones and become soft deletes or physical deletes by policy; watch replication slot lag, because a stuck consumer makes WAL fill the primary's disk; handle additive schema changes automatically and send breaking ones through a contract and review; prove correctness with row counts and checksums per table versus the source.

What a strong answer covers

  • Uses log-based CDC (WAL/logical replication) rather than query polling, and says why (weight 2)
  • Explains initial snapshot + stream handoff without gaps or duplicates (ordering by LSN/PK) (weight 3)
  • MERGE into current-state table plus an append-only change history (weight 2)
  • Handles deletes, and schema evolution (additive vs breaking) (weight 2)
  • Calls out replication slot / WAL growth risk on the primary and monitors lag (weight 2)
  • Reconciliation: counts/checksums vs source (weight 2)
  • Small-file compaction and MERGE cost at scale (weight 1)

Follow-ups

  • A developer runs an UPDATE on 300 million rows in one transaction. What happens to your pipeline?

    Debezium emits 300 million change events once the transaction commits, so the pipeline sees a burst: Kafka lag spikes, the merge into the lakehouse table becomes huge and slow, and the WAL may grow on the source while the connector catches up. Mitigate by scaling consumers, merging in batches, alerting on lag and WAL size, and asking for large updates to be batched or coordinated in advance.

  • The business wants "orders as they looked yesterday at 09:00". Which table answers it?

    A history table: either the raw change log (every version with its commit timestamp) or an SCD2 table built from it, queried with valid_from <= '... 09:00' < valid_to. Table time travel can also answer it if snapshots are kept that long.

Further reading

1. Requirements​

  • Sources: about 200 tables in one Postgres cluster; the largest has 2B rows; 5k writes/s at peak.
  • Freshness: at most 10 minutes behind.
  • Hard constraint: don't hurt production. No long-running scans on the primary during business hours.
  • Consumers: analytics (current state), finance (history: "what did this order look like on date D").
  • Correctness: exact. The copy must match the source.

2. Data contracts​

Every replicated table must have a primary key. Without one, updates and deletes can't be applied. Source teams agree to: announce breaking changes (renames, type changes) in advance, use additive changes by default, and never reuse a dropped column name with a different meaning.

3. Ingestion: log-based CDC​

Postgres WAL → logical replication slot → Debezium (Kafka Connect) → Kafka (topic per table, key = PK)
→ merge job → Iceberg/Delta

Why log-based, not polling (WHERE updated_at > last_run)? Polling misses deletes, misses updates where nobody set updated_at, and puts query load on the source. The WAL already records every change, in commit order, at almost no extra cost.

Initial snapshot: Debezium's incremental snapshot reads each table in primary-key chunks while the stream is already running, so there's no long lock and no gap. Snapshot rows and streamed changes can overlap; ordering by the source position (LSN) per key resolves it. The newest change wins.

4. Storage and format​

Two tables per source table:

  • orders_changes (bronze) is append-only: every change event with op (c/u/d), before/after images, source_lsn and commit_ts. This is the history and the replay source.
  • orders (silver) is the current state, maintained by MERGE on the primary key.

Iceberg or Delta give atomic MERGE, schema evolution and time travel on object storage.

5. Transform: applying changes​

Every few minutes, per table:

  1. Read new change events since the last committed offset.
  2. Keep only the last change per key in the batch (highest source_lsn).
  3. MERGE into the current table: insert new keys, update existing ones, and delete (or set is_deleted) on op = d.
  4. Commit the Kafka offset after the table commit. If the job crashes between the two, the batch is reapplied. That's harmless because MERGE by key with "newest LSN wins" is idempotent.

6. Serving​

Analysts query the current-state tables. Finance's "as of date D" uses table time travel for recent history, or a history model built from orders_changes (SCD2 with valid_from / valid_to from commit_ts) for anything older than snapshot retention.

7. Quality​

  • Row counts and checksums per table versus the source, daily, at a consistent point (for example from a read replica).
  • Freshness: lag between source commit_ts and the lakehouse commit, alerted above 10 minutes.
  • Contract checks: a schema change event that isn't additive pauses that table's pipeline and pages the owner, instead of corrupting data.

8. Orchestration and backfill​

The merge jobs run continuously (or every few minutes) under an orchestrator that tracks per-table offsets. To re-snapshot one table (after a bug or a breaking change), trigger an incremental snapshot for just that table. The stream keeps flowing for the others.

9. Failure modes​

FailureWhy it's dangerousMitigation
Consumer stops readingThe replication slot keeps WAL, and the primary's disk fills upAlert on slot lag; set max_slot_wal_keep_size; runbook to drop and re-snapshot
Huge transaction (300M-row UPDATE)Burst of events, MERGE takes hoursAutoscale merge job; for planned bulk changes, re-snapshot instead
Column renamedOld column stops updating silentlyContract: rename = add + backfill + drop; schema-change alert
Table without PKCan't apply updates/deletesBlock at onboarding; use REPLICA IDENTITY FULL only as a last resort
Primary failoverSlot may be lostUse failover-aware slots where supported; otherwise re-snapshot

10. Cost​

Frequent MERGEs create many small files and delete files. Schedule compaction and snapshot expiry. Tune merge frequency per table: hot tables every few minutes, quiet tables hourly. Kafka retention only needs to cover recovery time; bronze holds long-term history.

11. What changes at 10×​

At 50k writes/s: more Kafka partitions per hot table, merge jobs split by table and partition, and maybe merge-on-read tables (deletes applied at read time, then compacted) to keep commits cheap. Cross-service rollout becomes the main problem, so build a self-serve onboarding with the contract checks built in.