Showing posts with label Debezium. Show all posts
Showing posts with label Debezium. Show all posts

Real-Time CDC Pipeline: Streaming PostgreSQL to Delta Lake with Debezium & Kafka

 


Zero-Downtime CDC Pipelines: Streaming PostgreSQL & SQL Server Changes to Your Data Lake with Debezium

1. Introduction

Traditional batch ETL pipelines rely on polling production relational databases (PostgreSQL, SQL Server, MySQL) every hour or night using timestamp columns (updated_at). As transaction volumes scale, this approach introduces three severe failure points:

  1. Production Database Contention: Heavy SELECT queries lock tables and spike CPU/IOPS on critical OLTP systems.

  2. Missed Hard Deletes: If an application executes a DELETE statement, a timestamp-based query never sees it—leaving ghost records in your data warehouse.

  3. High Data Latency: Business intelligence and AI models run on stale data instead of real-time events.

Change Data Capture (CDC) solves this by reading the database's native transaction log (PostgreSQL Write-Ahead Log or SQL Server Transaction Log) directly. Using Debezium and Apache Kafka, every INSERT, UPDATE, and DELETE is captured in milliseconds with near-zero overhead on your primary database.

In this guide, we’ll build a fault-tolerant CDC pipeline from PostgreSQL to Apache Kafka and sink those events into a Lakehouse table.

2. Step 1: Preparing the Source Database (Logical Replication)

To allow Debezium to stream row-level changes without querying your tables, you must enable Logical Replication on your database engine.

PostgreSQL Configuration (postgresql.conf)

Update your database parameters and restart the service:

wal_level = logical # Required for row-level change decoding
max_wal_senders = 10 # Max concurrent replication connections
max_replication_slots = 10 # Dedicated slots for Debezium connectors

Create a Dedicated Replication Role

Follow the principle of least privilege by creating a user specifically for CDC rather than using postgres or sa:

CREATE ROLE debezium_cdc WITH REPLICATION LOGIN PASSWORD 'StrongCdcPassword!';
GRANT CONNECT ON DATABASE prod_orders TO debezium_cdc;
GRANT USAGE ON SCHEMA public TO debezium_cdc;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO debezium_cdc;

-- Create a publication for target tables
CREATE PUBLICATION datatipss_cdc_pub FOR TABLE public.orders, public.customers;

(Note: For SQL Server, enable CDC at the database level via EXEC sys.sp_cdc_enable_db; and per table via sys.sp_cdc_enable_table.)

3. Step 2: Deploying the Debezium Kafka Connector

Debezium runs as a distributed connector inside Kafka Connect. When started, it takes an initial consistent snapshot of your existing tables and seamlessly transitions to streaming live WAL events.

Post this configuration to your Kafka Connect REST API (POST /connectors):

{
"name": "postgres-orders-cdc-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"tasks.max": "1",
"database.hostname": "prod-db.internal.datatipss.in",
"database.port": "5432",
"database.user": "debezium_cdc",
"database.password": "${file:/opt/kafka/secrets/db-creds.properties:password}",
"database.dbname": "prod_orders",
"topic.prefix": "cdc.prod",
"table.include.list": "public.orders,public.customers",
"plugin.name": "pgoutput",
"publication.name": "datatipss_cdc_pub",
"slot.name": "debezium_orders_slot",
"tombstones.on.delete": "true",
"transforms": "unwrap",
"transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
"transforms.unwrap.drop.tombstones": "false",
"transforms.unwrap.delete.handling.mode": "rewrite"
}
}

Key Production Flags Explained:

  • plugin.name: pgoutput: Uses PostgreSQL's native logical decoding plugin (no third-party C extensions required).

  • transforms.unwrap (ExtractNewRecordState): Flattens Debezium's verbose nested before/after JSON envelope into clean, flat records while adding a __deleted metadata flag (true/false) so downstream Lakehouse consumers can process hard deletes cleanly.

4. Step 3: Upserting CDC Events into Delta Lake / Iceberg

Once Debezium publishes events to cdc.prod.public.orders, use PySpark Structured Streaming with foreachBatch and MERGE INTO to keep your analytical Lakehouse table synchronized in real time:

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, from_json
from delta.tables import DeltaTable

spark = SparkSession.builder \
.appName("DebeziumCDCToDeltaLake") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.config("spark.sql.catalog.spark_catalog",
"org.apache.spark.sql.delta.catalog.DeltaCatalog") \
.getOrCreate()

def upsert_to_delta(micro_batch_df, batch_id):
if micro_batch_df.isEmpty():
return

# Deduplicate multiple updates to the same order_id within a single micro-batch
deduped_df = micro_batch_df.dropDuplicates(["order_id"])
delta_table = DeltaTable.forPath(spark, "s3a://datatipss-lakehouse/silver/orders/")
(delta_table.alias("target")
.merge(deduped_df.alias("source"), "target.order_id = source.order_id")
.whenMatchedDelete(condition="source.__deleted = 'true'")
.whenMatchedUpdateAll(condition="source.__deleted = 'false'")
.whenNotMatchedInsertAll(condition="source.__deleted = 'false'")
.execute()
)

# Read CDC stream from Kafka
cdc_stream = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "kafka-broker:9092") \
.option("subscribe", "cdc.prod.public.orders") \
.load()

# Parse payload (apply your StructType schema here) and write via foreachBatch
parsed_stream = cdc_stream.selectExpr("CAST(value AS STRING) as json_str")

query = parsed_stream.writeStream \
.foreachBatch(upsert_to_delta) \
.option("checkpointLocation", "s3a://datatipss-lakehouse/checkpoints/orders_cdc/") \
.trigger(processingTime="30 seconds") \
.start()

query.awaitTermination()

5. Production Pitfalls & Best Practices

  • Monitor Replication Slot Disk Usage: If Kafka Connect goes down for several days, PostgreSQL retains unconsumed WAL segments on disk—which can fill up storage and crash your primary database. Set max_slot_wal_keep_size in postgresql.conf and alert on replication lag via Prometheus.

  • Include a Heartbeat Table: Low-traffic databases don't advance their WAL LSN frequently, causing replication slots to appear stalled. Enable Debezium's heartbeat.interval.ms on a dedicated heartbeat table to keep offsets advancing smoothly.

  • Handle Schema Evolution: Pair your CDC stream with a Schema Registry (Confluent or Apicurio) so upstream ALTER TABLE ADD COLUMN changes don't break downstream Spark consumers.

Summary

Replacing legacy batch polling with log-based Change Data Capture eliminates production database load, captures hard deletes accurately, and cuts data warehouse latency from hours to seconds. By combining Debezium's pgoutput connector, Single Message Transforms (SMTs), and Delta Lake MERGE INTO operations, you get an enterprise-grade, real-time synchronization backbone.

💬 Are you still running batch ETL jobs or have you migrated to log-based CDC? What's been your biggest challenge with Debezium or replication slots in production? Let us know in the comments below!

🔔 Found this guide helpful? Share it with your data engineering team and subscribe to DataTipss for practical deep dives into Data Engineering, Databases, Cloud FinOps, and DevSecOps!

Real-Time CDC Pipeline: Streaming PostgreSQL to Delta Lake with Debezium & Kafka

  Zero-Downtime CDC Pipelines: Streaming PostgreSQL & SQL Server Changes to Your Data Lake with Debezium 1. Introduction Traditional bat...