Design: database to lakehouse

Part of the free LogicWiz Data Engineering course, Module 17: Pipeline design. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is Monday, 6:45 p.m., and checkout is slow again. Analysts are running reports straight on the shop's Postgres, and Dana has had enough. The CTO wants orders, lines and customers in the lakehouse within 10 minutes, with deletes included (customers can ask to be erased), and without heavy queries on the shop's database. Nora opens the review with one question: "The nightly updated_at extract from Lesson 17.2 cannot see a deleted row. What can?"

You'll learn to

  • Compare snapshots, updated_at queries and log-based CDC, and choose
  • Apply a change feed with MERGE: order by log position, keep deletes
  • Plan the first load, a replay and a schema change
  • Size the WAL that a stuck slot holds back on the source

Learn

Steps 1 to 3: every change, deletes included

The questions first. Here is what comes back.

  • Tables: orders, order_items, customers, payments from the shop's Postgres.
  • Freshness: about 10 minutes. Correctness: match the source, including deletes.
  • History: keep every change; rebuild any table without asking the source again.
  • Source load: light. Change: developers add columns now and then.

What the CTO is asking for has a name. Delivering every insert, update and delete made in a database to somewhere else, in order, is called change data capture (CDC). The design question is how you capture the changes.

Three ways to capture changes

Query the tables (snapshot or updatedat)Read the database's log (log-based CDC)
Full snapshot: copy the table, then compare with yesterday's copy (FULL OUTER JOIN on the key: one side missing = insert or delete; values differ = update)Reads the write-ahead log (WAL), where Postgres records every change
updatedat last run: cheap, but never sees a hard deleteSees every insert, update and delete, in commit order, with a log position (LSN)
Heavy reads at each run; as fresh as the scheduleAlmost no load on the tables; seconds behind
Simple: a query and a schedulerMore parts: a replication slot, a connector such as Debezium, Kafka

Step 2: size it

import math

rows = 5_000_000               # orders in the source table
bytes_per_row = 300
changes_per_day = 400_000      # inserts, updates and deletes
bytes_per_change = 1_000       # a change event carries the row plus metadata
peak_factor = 5

snapshot_gb = rows * bytes_per_row / 1e9
changes_gb = changes_per_day * bytes_per_change / 1e9
peak = changes_per_day / 86_400 * peak_factor

print(f'one full snapshot: {snapshot_gb:.1f} GB')
print(f'a month of daily snapshots: {snapshot_gb * 30:.0f} GB read from the source')
print(f'a month of change events: {changes_gb * 30:.0f} GB, read from the log')
print(f'peak changes: {peak:.0f}/s, partitions needed: {math.ceil(peak / 500)}')

Change events are bigger than rows, but there are far fewer of them than rows in the table, and they come from the log, not from queries on the tables. One partition could carry the peak; take three for room.

Step 4: the sketch, one box at a time

A nightly updated_at query is cheap, but it never sees a hard delete, and it is only as fresh as its schedule. Ten minutes and deletes both point to the right-hand column: read the database's own log.

Postgres writes every change to its write-ahead log (WAL) before it touches the tables (Lesson 6.7). The design taps that log. Step through it below, one box at a time.

Database to lakehouse, built box by box

A graph built one box at a time: the shop's Postgres primary with a replication slot, Debezium on Kafka Connect, one Kafka topic per table, a bronze change log, silver tables merged every five minutes, and last the gold models, a purge job and an alert on the slot.

  1. The source. Postgres, with logical replication switched on. A replication slot is a bookmark in the WAL: Postgres keeps everything after it until the reader has taken it.

  2. The reader. Debezium, a Kafka Connect connector. It first snapshots each table (op = r), then streams every change from the WAL. It reads the log, so the tables feel almost nothing.

  3. The log. One Kafka topic per table, keyed by the primary key. Every change to one row lands in the same partition, in order, and can be read again for 7 days.

  4. Bronze. Structured Streaming appends every change event to a Delta table, with its op and its lsn. Nothing is applied yet: this is the full history, and silver can always be rebuilt from it.

  5. Silver. Every 5 minutes, a MERGE applies the newest change per key, by lsn, deletes included. Silver now looks like the source did a few minutes ago.

  6. Gold, a purge job, and an alert. Gold models leave deleted rows out. A purge job removes them for good later. And one alert watches the WAL the slot holds back, because that buffer sits on the shop's own disk.

Grey boxes are not drawn yet. Each step colours in the next box and gives the reason for it. Nothing in this picture runs a query on the shop's tables after the first snapshot.

The finished design, end to end

A graph from the shop's Postgres primary and its replication slot, through Debezium on Kafka Connect, one Kafka topic per table keyed by primary key, a bronze change log, a silver MERGE every five minutes with tombstones and a purge job, to gold models, with a dashed monitoring arrow watching the slot.

Follow the arrows from Postgres to gold. Three buffers sit in a row: the WAL held by the slot, the Kafka topics and bronze. The first one lives on the shop's own disk, which is why the red alert points at it.

One Debezium change event: order 1003 is delivered

Runs on a Kafka cluster:

{
  "before": null,
  "after": {
    "order_id": 1003,
    "customer_id": 10,
    "status": "delivered",
    "updated_at": 1749026723000000
  },
  "source": {
    "connector": "postgresql",
    "db": "shop",
    "schema": "public",
    "table": "orders",
    "txId": 5521,
    "lsn": 24023128,
    "ts_ms": 1749026723120
  },
  "op": "u",
  "ts_ms": 1749026723456
}

op is c, u, d or r (snapshot read); lsn is the WAL position, the true order of changes; updated_at arrives as microseconds since 1970, and the ts_ms fields are milliseconds. before is null on updates unless the table has REPLICA IDENTITY FULL; a delete has the key in before and null after. Some source fields are left out.

The design, component by component

ComponentTool I would pickWhy
CaptureDebezium on Kafka Connect (or AWS DMS, Fivetran, Lakeflow Connect)Reads the WAL: every change, deletes included, light on the source
LogOne Kafka topic per table, keyed by primary key, 7 daysPer-key order; replay after a failure
BronzeDelta table of change events, appended by Structured StreamingFull history; rebuild silver from it
SilverMERGE of the newest change per key by lsn, soft deletesMatches the source; idempotent
GoldModels that filter out deleted rowsAnalysts never see deleted data
ScheduleavailableNow every 5 minutes, nightly OPTIMIZEAbout 10 minutes fresh without a cluster running all day
MonitoringReplication slot lag on Postgres, connector status, row counts against the sourceA stuck slot fills the source's disk

Debezium is the common open-source choice; AWS DMS, Google Datastream, Fivetran and Databricks Lakeflow Connect offer managed CDC. On Databricks, Lakeflow Declarative Pipelines has an AUTO CDC (formerly APPLY CHANGES) step that does this lesson's MERGE: sequence by a column, deletes, and SCD type 1 or 2.

Apply the changes: the newest by LSN wins

Bronze now holds a stream of change events. Silver has to turn them back into tables that match the source. Nora asks: "Two events for the same order. Which one wins?"

  1. Order by lsn, never by arrival. The LSN is the position in the WAL: the order in which the database made the changes. Connectors are at-least-once: after a restart they send changes again, so an old change can arrive late.
  2. Newest per key wins. Cut the batch down to the highest lsn per key, and update a row only if the incoming lsn is higher. Duplicates and replays then change nothing.

That leaves deletes, and they hide a trap.

Order 1006: remove the row, or mark it deleted?

Three boxes over three steps: the event that arrives, silver with a hard delete and silver with a tombstone; after a delete and then a late older update, the hard-delete table has the order back while the tombstone table still shows it deleted.

  1. Before. Silver holds order 1006, shipped, last changed at LSN 103. Both designs start the same.

  2. The delete arrives, LSN 230. One design removes the row. The other keeps it, marked is_deleted = true, with the delete's LSN. That marked row is called a tombstone.

  3. An older update arrives late, LSN 225. The connector restarted and sent it again. With the row gone there is nothing to compare 225 with, so the MERGE inserts it: the deleted order is back. The tombstone remembers 230, so 225 loses.

Compare the two silver boxes at each step. Analysts never see a tombstone, because gold reads WHERE NOT is_deleted. A purge job removes tombstones later, which also completes an erasure request.

Apply the batch, then apply it again

MERGE INTO silver_orders AS t
USING (
  SELECT lsn, op, order_id, status, updated_at
  FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY lsn DESC) AS rn
    FROM cdc_orders
  ) ranked
  WHERE rn = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.lsn > t.lsn THEN
  UPDATE SET status = s.status, updated_at = s.updated_at, lsn = s.lsn, is_deleted = (s.op = 'd')
WHEN NOT MATCHED THEN
  INSERT (order_id, status, updated_at, lsn, is_deleted)
  VALUES (s.order_id, s.status, s.updated_at, s.lsn, s.op = 'd');

MERGE INTO silver_orders AS t
USING (
  SELECT lsn, op, order_id, status, updated_at
  FROM (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY lsn DESC) AS rn
    FROM cdc_orders
  ) ranked
  WHERE rn = 1
) AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.lsn > t.lsn THEN
  UPDATE SET status = s.status, updated_at = s.updated_at, lsn = s.lsn, is_deleted = (s.op = 'd')
WHEN NOT MATCHED THEN
  INSERT (order_id, status, updated_at, lsn, is_deleted)
  VALUES (s.order_id, s.status, s.updated_at, s.lsn, s.op = 'd');

SELECT order_id, status, lsn, is_deleted
FROM silver_orders
ORDER BY order_id;

Seven events, two of them the same change sent twice, arrive out of order. Applying the batch twice gives the same five rows: 1006 is kept as a tombstone, 1016 is new. Analysts read WHERE NOT is_deleted.

The first load, a replay, a new column

Three more questions come up in every review of this design.

The first load. The tables already hold 5 million orders. Debezium snapshots each table, notes the WAL position where it began, then streams from there, so nothing falls in the gap. Snapshot rows go through the same MERGE.

A replay. If silver's logic had a bug, rebuild silver by replaying bronze through the fixed MERGE. Newest-wins and idempotent means the same result however often you replay.

A new column. Bronze stores events as they come. Silver adds a new column on purpose (Delta schema evolution, or a contract that alerts). A renamed or dropped column should stop the pipeline.

Snapshot, then stream, with no gap

A sequence between Postgres, Debezium and Kafka in three steps: Debezium creates the slot, reads every row in the slot's snapshot as op r events, then streams changes after the slot's position and confirms each flushed position so Postgres can recycle older WAL.

  1. Mark the spot. Debezium creates the replication slot. Postgres answers with the slot's starting position in the WAL, and a snapshot: a view of the tables as they are at exactly that position.

  2. Copy what is there. Debezium reads every row as of that snapshot and sends each one to Kafka as an op = r event.

  3. Then follow the log. Streaming starts from the slot's position, so a change made during the copy is not lost. Debezium confirms what it has flushed, and Postgres can recycle the WAL before that point.

Read it top to bottom. The snapshot and the stream meet at one log position, so a change committed during the snapshot is either in the snapshot or in the stream, never in neither.

The buffer on the shop's own disk

Now the arrow Dana cares about: the one that touches her database. Three numbers.

  • Changes: 400,000 a day is 4.6 a second on average and 23 at a 5x peak. Tiny for Kafka.
  • WAL: Postgres writes WAL for every table, not only the four you capture, plus full-page images after each checkpoint. Measure it: read pg_current_wal_lsn() twice, an hour apart, and take pg_wal_lsn_diff of the two. Say it is 2 GB an hour.
  • The slot's risk: a stopped connector makes its slot keep all WAL from its restart_lsn. At 2 GB an hour, a 60-hour weekend outage is 120 GB. With 150 GB free, Monday morning is close to an outage of the shop itself.

Measure what each slot holds back

-- on a real primary: FROM pg_replication_slots, and pg_current_wal_lsn() instead of the literal
SELECT slot_name, active,
       pg_size_pretty(pg_wal_lsn_diff('1A/00000000', restart_lsn)) AS retained_wal
FROM slots
ORDER BY pg_wal_lsn_diff('1A/00000000', restart_lsn) DESC;

An LSN is a 64-bit byte position in the WAL, printed as two hex halves. pg_wal_lsn_diff subtracts two of them in bytes: the inactive Debezium slot holds back 16 GB, the healthy one 16 MB. Alert on the bytes, not on active alone.

A weekend with the connector down

One bar of the 150 GB that were free on the primary on Friday: 120 GB taken by WAL the stuck slot kept over 60 hours, and 30 GB left on Monday.

The red part grows by 2 GB for every hour the connector is down. Since Postgres 13, max_slot_wal_keep_size caps what a slot may keep (default -1, no cap). Past the cap the slot's wal_status becomes lost and the connector must snapshot again: the shop survives, the pipeline pays.

When Kafka slows down, Postgres fills up

Lesson 17.1 said to follow back-pressure to the place where the data waits. Do it here, backwards from Kafka.

Kafka slows down. Kafka Connect's producer blocks. Debezium's internal queue fills. Debezium stops reading the slot. Postgres keeps the WAL. Nothing is lost, and nothing is free: in log-based CDC, the buffer of last resort is the shop's disk.

So the design does three things. It alerts on retained WAL early, say at 20% of free disk. It sets max_slot_wal_keep_size as the hard stop. And it turns on Debezium's heartbeats for quiet databases, so that a slot on a database where the captured tables rarely change still moves forward.

The pressure travels backwards

Four boxes in the direction the data flows: Postgres, Debezium, the Kafka Connect producer and Kafka; step by step the slowdown moves from Kafka back to the producer, to Debezium's queue, and finally to the WAL on the Postgres disk.

  1. Kafka slows down. For whatever reason, it accepts events more slowly than they arrive.

  2. The producer blocks. Kafka Connect's producer cannot hand its events over, so it stops taking new ones from Debezium.

  3. The queue fills. Debezium's internal queue holds 8,192 events by default (max.queue.size), handed over in batches of 2,048 (max.batch.size). Once it is full, Debezium stops reading the slot.

  4. Postgres keeps the WAL. The slot does not move, so every WAL file after it stays on the primary's disk. The pressure has reached the one place you promised to protect.

The data flows from the first box to the last. Press Next step and watch the trouble move the other way, one box at a time.

Order is per key, not per transaction

One promise the design makes, and one it does not.

Order is guaranteed per key: every change to order 1003 goes to the same partition of the orders topic, in LSN order. Across tables there is no such promise. An order and its lines, committed together, arrive on two topics and can reach silver minutes apart. If a consumer needs whole transactions, set provide.transaction.metadata: Debezium then emits transaction boundaries and tags every event with its transaction id.

To reprocess one table without stopping the stream, send Debezium an execute-snapshot signal for an incremental snapshot (since Debezium 1.6). It reads the table again in chunks while changes keep flowing, and resolves the overlap between a chunk and live changes to the same key.

A topic with three partitions where every message with the same key lands in the same partition, in order, read by a consumer group that splits the partitions between its consumers.

Press Send 5 events and follow one key: all of its messages land in the same partition, in order. In this design the key is the primary key, so every change to order 1003 stays in order. Messages with different keys have no order between them.

The day Postgres fails over

Last, the day the shop's Postgres fails over to a standby. What happens to the slot?

Before Postgres 17, logical replication slots are not carried to the standby. The new primary has no slot, and the safe recovery is a new slot plus a new snapshot (Debezium's docs call it manual intervention). From 17, a logical slot created with failover enabled is synchronised to standbys that set sync_replication_slots, so the connector can continue after a failover.

If the lakehouse is in another region, let the change stream cross regions once (replicate Kafka or write bronze remotely, not both): transfer between regions is billed per GB.

The SLOs: p95 commit-to-silver lag under 10 minutes, retained WAL under 20% of free disk at all times, and every erasure request purged within the deadline your legal team sets.

A stuck replication slot can take down the shop. Postgres keeps every WAL file until the slot's reader confirms it. If the connector stops for a weekend, the WAL piles up until the disk is full. Monitor slot lag and alert early.

Remember: see deletes by reading the log. Order changes by LSN, never by arrival. Keep deletes as tombstones, so the newest-wins MERGE stays safe to replay.

Numbers to remember

NumberValueNote
Full snapshot of orders1.5 GB5 million rows x 300 bytes; 45 GB read from the source in a month of nightly copies
Change events400,000 a day, 12 GB a month4.6 a second on average, 23 at a 5x peak
Debezium opc, u, d, rcreate, update, delete, snapshot read
before on an updatenullunless the table has REPLICA IDENTITY FULL
Debezium max.queue.size8,192 eventshanded over in batches of max.batch.size, 2,048
maxslotwalkeepsize-1, no cap (the setting exists since Postgres 13)past the cap the slot's walstatus is lost: snapshot again
Logical slots and failoversynchronised to standbys from Postgres 17before 17: a new slot and a new snapshot
Incremental snapshotsince Debezium 1.6started with an execute-snapshot signal
Silver scheduleavailableNow every 5 minutesabout 10 minutes fresh without a cluster running all day

What changed at SwiftKart

The analysts move off the shop's database. Their tables in the lakehouse are about 10 minutes behind checkout, and a customer who asks to be erased disappears from them too: first as a tombstone, then for good when the purge job runs.

Dana gets two things in return. Almost no load on her tables, and an alert that fires long before a stuck slot can fill her disk.

You have now defended four designs. In each one Nora asked "how many?" and "how much?". Lesson 17.5 is about answering those on the spot: the numbers a senior engineer gives without opening a spreadsheet.

In one line

Database to lakehouse: log-based CDC (Debezium) keyed by primary key, every change kept in bronze, and a newest-by-LSN MERGE with tombstones into silver; watch the replication slot.

Interview corner

How would you replicate a production Postgres database into a lakehouse?

"I'd use log-based CDC: enable logical replication, and run Debezium to snapshot each table and then stream every change from the WAL into Kafka, one topic per table keyed by primary key. A streaming job appends the change events to a bronze Delta table, and every few minutes I MERGE the newest change per key, ordered by LSN, into silver, keeping deletes as tombstones. I'd monitor the replication slot lag on the source, because a stuck slot fills its disk."

The CDC connector was down all weekend. What happened on the source, and what do you do on Monday?

"The replication slot kept every WAL file since its restart_lsn, so the primary's disk filled at the WAL rate: at 2 GB an hour, 60 hours is about 120 GB. First I check pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) and free disk. If there is room, I restart the connector and let it drain, watching the lag fall. If the disk is close to full, protecting the shop comes first: drop the slot and re-snapshot later. Then I fix the gap in the design: alert on retained WAL at 20% of free disk, set max_slot_wal_keep_size as a hard stop, and enable heartbeats."

How do you capture deletes if all you have is an updated_at column?

"An updated_at query cannot see hard deletes, because the row is gone. Options are: ask for soft deletes in the source (a deleted_at column), compare a full snapshot of the keys with the previous one using a FULL OUTER JOIN, or move to log-based CDC. For a big table I'd snapshot only the primary keys daily to find deletes cheaply."

How do you make applying CDC events idempotent and order-safe?

"Each event carries the source's log position. I dedup each batch to the highest LSN per key, and MERGE with an update only when the incoming LSN is higher than the stored one. Deletes become tombstones with their LSN, so a late, older update cannot resurrect a row. Then replays, duplicates and out-of-order delivery all end in the same table."