Replication lag
Commit in PostgreSQL to change row in Snowflake, p50 and p95
Project 03 · Change data capture
The order service writes to PostgreSQL. Debezium reads the database's write-ahead log through logical replication, so every insert, update and delete becomes a Kafka event without touching the application or querying its tables. A Flink job flattens and cleans the changes while keeping them in order per row, Snowpipe Streaming lands them in Snowflake within seconds, and Dynamic Tables merge them into copies of the source tables that stay in sync row for row.
Commit in PostgreSQL to change row in Snowflake, p50 and p95
Change events per source table today
Inserts, updates and deletes
State at 23:59
Checked every 15 minutes. The 3 inventory rows in flight matched at 00:01.
New columns land in RAW on their own
The last ten changes committed on Oct 6
Log-based capture: the source database never sees an extra query.
01 · Source
PostgreSQL 16
The order service's database. Logical replication with the pgoutput plugin; one publication covers the 12 tables.
02 · Capture
Debezium on Kafka Connect
Takes an initial snapshot, then reads the write-ahead log and emits every insert, update and delete with its LSN.
03 · Transport
Apache Kafka
One topic per table, keyed by primary key so changes to a row stay in order. Each event carries the row before and after.
04 · Normalize
Apache Flink
Reads all twelve topics and keeps what the merge needs: key, operation, LSN, commit time and the row, written exactly once.
05 · Land
Snowpipe Streaming
The Snowflake Kafka connector appends every change to RAW.CHANGES within seconds.
06 · Merge
Snowflake Dynamic Tables
One per source table: the newest version of each row, deleted rows removed, refreshed every minute.
op = 'd' and the merge removes the row, so Snowflake never keeps rows the source has deleted.The same order row at three points: the Debezium event in Kafka, the change row in Snowflake, and the merged table.
pg.public.ordersKafka topic · Debezium event (JSON)before / afterstructbefore is null for insertsopstringc insert, u update, d delete, r snapshot readsource.lsnbigintsource.ts_msbigintts_msbigintRAW.CHANGESSnowflake table · append-only, all 12 tablesrecord_content:table_name / pkvariantrecord_content:op / is_deletedvariantrecord_content:lsnvariantrecord_content:committed_msvariantrecord_content:row_jsonvariantrecord_metadatavariantCORE.ORDERSDynamic table · target lag 1 minuteorder_idnumbercustomer_idnumberstatusvarchartotal_usdnumber(12,2)updated_at / lsntimestamp_ltz / numberThe Debezium connector, the Flink SQL that normalizes changes, and the Snowflake merge.
Kafka Connect configuration for the Debezium PostgreSQL source connector. A heartbeat keeps the replication slot advancing on quiet tables.
{
"name": "debezium-orders-pg",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"tasks.max": "1",
"database.hostname": "orders-db.internal",
"database.port": "5432",
"database.user": "debezium",
"database.password": "${secrets:orders-db/debezium-password}",
"database.dbname": "orders",
"topic.prefix": "pg",
"plugin.name": "pgoutput",
"slot.name": "debezium_orders",
"publication.name": "dbz_orders",
"publication.autocreate.mode": "disabled",
"table.include.list": "public.orders,public.order_items,public.payments,public.shipments,public.inventory,public.prices,public.customers,public.addresses,public.returns,public.promotions,public.products,public.carriers",
"snapshot.mode": "initial",
"heartbeat.interval.ms": "10000",
"decimal.handling.mode": "string",
"time.precision.mode": "connect",
"tombstones.on.delete": "false",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "false",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "false"
}
}
Flink SQL: one job reads all twelve Debezium topics and writes a single, flat change stream, exactly once.
-- Debezium events from every table; the row images stay as JSON text
CREATE TABLE changes_in (
key_json STRING,
`before` STRING,
`after` STRING,
op STRING,
source ROW<`table` STRING, lsn BIGINT, ts_ms BIGINT>
) WITH (
'connector' = 'kafka',
'topic-pattern' = 'pg\.public\..*',
'properties.bootstrap.servers' = 'kafka:9092',
'properties.group.id' = 'flink-cdc-normalize',
'scan.startup.mode' = 'group-offsets',
'properties.auto.offset.reset' = 'earliest',
'key.format' = 'raw',
'key.fields' = 'key_json',
'value.format' = 'json',
'value.fields-include' = 'EXCEPT_KEY'
);
-- One flat record per change. Keyed by table + primary key, so a row's changes stay in order.
CREATE TABLE changes_out (
pk STRING,
table_name STRING,
op STRING,
is_deleted BOOLEAN,
lsn BIGINT,
committed_ms BIGINT,
row_json STRING
) WITH (
'connector' = 'kafka',
'topic' = 'cdc.changes',
'properties.bootstrap.servers' = 'kafka:9092',
'key.format' = 'raw',
'key.fields' = 'pk',
'value.format' = 'json',
'value.fields-include' = 'EXCEPT_KEY',
'sink.delivery-guarantee' = 'exactly-once',
'sink.transactional-id-prefix' = 'cdc-changes'
);
INSERT INTO changes_out
SELECT
CONCAT(source.`table`, ':', key_json),
source.`table`,
op,
op = 'd',
source.lsn,
source.ts_ms,
COALESCE(`after`, `before`) -- deletes carry the key in the before image
FROM changes_in
WHERE op IN ('c', 'u', 'd', 'r');
Snowflake: a dynamic table keeps the newest version of each order and removes deleted ones. The view feeds the lag chart.
CREATE OR REPLACE DYNAMIC TABLE core.orders
TARGET_LAG = '1 minute'
WAREHOUSE = cdc_wh
AS
WITH parsed AS (
SELECT
record_content:lsn::NUMBER AS lsn,
record_content:is_deleted::BOOLEAN AS is_deleted,
PARSE_JSON(record_content:row_json::STRING) AS r
FROM raw.changes
WHERE record_content:table_name::STRING = 'orders'
),
latest AS (
SELECT *
FROM parsed
QUALIFY ROW_NUMBER() OVER (PARTITION BY r:order_id::NUMBER ORDER BY lsn DESC) = 1
)
SELECT
r:order_id::NUMBER AS order_id,
r:customer_id::NUMBER AS customer_id,
r:status::VARCHAR AS status,
r:total_usd::NUMBER(12, 2) AS total_usd,
r:promo_code::VARCHAR AS promo_code, -- new on Oct 6, already in RAW
TO_TIMESTAMP_LTZ(r:updated_at::NUMBER, 3) AS updated_at,
lsn
FROM latest
WHERE NOT is_deleted;
-- Commit in PostgreSQL to arrival in Snowflake, per 5 minutes
CREATE OR REPLACE VIEW monitoring.cdc_lag_5min AS
SELECT
TIME_SLICE(TO_TIMESTAMP_LTZ(record_content:committed_ms::NUMBER, 3), 5, 'MINUTE') AS interval_start,
COUNT(*) AS changes,
APPROX_PERCENTILE(record_metadata:SnowflakeConnectorPushTime::NUMBER
- record_content:committed_ms::NUMBER, 0.50) / 1000 AS lag_p50_s,
APPROX_PERCENTILE(record_metadata:SnowflakeConnectorPushTime::NUMBER
- record_content:committed_ms::NUMBER, 0.95) / 1000 AS lag_p95_s
FROM raw.changes
GROUP BY 1;
A nightly job rewrote 1.2 million prices in one transaction. Throughput peaked near 1,400 events a second, p95 lag reached 7.9 s and drained within 15 minutes. The SLA held.
At 14:32 the Debezium task restarted after a network blip. It resumed from the last LSN it had confirmed to PostgreSQL, so nothing was lost and the merge ignored the few replayed events.
Each change carries the whole row as JSON, so promo_code, a wider carrier_code and marketing_opt_in reached RAW.CHANGES the moment they existed in PostgreSQL. Exposing promo_code in CORE.ORDERS took one line.
The replication slot holds about 200 MB of write-ahead log. An alert fires at 5 GB, long before a stuck consumer could fill the source database's disk.
About the data. Every number on this page is sample data from a seeded generator written for this project. It is shaped to behave like a real workload, with daily peaks, late events and the odd incident, but it does not come from any employer or client. Download it as change_events_5min.csv or read data.json.