Showing posts with label Data Engineering. Show all posts
Showing posts with label Data Engineering. 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!

How to Fix the Kafka Small File Problem in Amazon S3 & GCS



1. Introduction

When building real-time streaming architectures with Apache Kafka, streaming directly into cloud storage (like Amazon S3 or Google Cloud Storage) seems straightforward. However, high-throughput topics written with low batch timeouts quickly create millions of micro-files—often under 1 MB each.

This "Small File Problem" leads to two massive issues:

  1. Exploding Cloud Costs: AWS charges per 1,000 PUT requests ($0.005 per 1,000 requests adds up fast when writing 100 files/second).

  2. Abysmal Query Speeds: Query engines like AWS Athena, Trino, and Snowflake must open, read, and close thousands of separate file footers, slowing down analytical queries from seconds to minutes.

In this guide, we’ll explore how to configure Kafka Connect (S3 Sink Connector) and PySpark Structured Streaming to batch, compress, and optimize real-time data before it hits long-term storage.

2. Solution Strategy 1: Tuning Kafka Connect S3 Sink

If you are using Kafka Connect, the key is balancing Latency vs. File Size. You should target file sizes between 128 MB and 512 MB per object.

Modify your connect-s3-sink.json configuration with these three parameters:

{
"name": "s3-sink-telemetry-optimized",
"config": {
"connector.class": "io.confluent.connect.s3.S3SinkConnector",
"tasks.max": "4",
"topics": "telemetry-events",
"s3.bucket.name": "datatipss-analytics-lake",
"s3.part.size": "67108864",
"flush.size": "100000",
"rotate.interval.ms": "300000",
"storage.class": "io.confluent.connect.s3.storage.S3Storage",
"format.class": "io.confluent.connect.s3.format.parquet.ParquetFormat",
"parquet.compression": "SNAPPY",
"schema.compatibility": "NONE"
}
}

Why these settings matter:

  • s3.part.size = 67108864 (64 MB): Sets the minimum upload buffer part size for multi-part uploads.

  • flush.size = 100000: Forces a file write only after accumulating 100,000 records.

  • rotate.interval.ms = 300000 (5 minutes): Guarantees files are committed at least every 5 minutes so low-volume topics don't leave data stuck in memory forever.

3. Solution Strategy 2: Dynamic Repartitioning in PySpark

If you consume Kafka with PySpark Structured Streaming, simply saving the stream using .writeStream without repartitioning will create one file per Kafka partition for every trigger interval.

To avoid thousands of micro-partitions, use .repartition() or configure Trigger Intervals combined with Snappy-compressed Parquet:

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, from_json
from pyspark.sql.types import StructType, StringType, TimestampType

spark = SparkSession.builder \
.appName("KafkaToS3BatchOptimizer") \
.config("spark.sql.parquet.compression.codec", "snappy") \
.getOrCreate()

# 1. Read from Kafka
kafka_stream = spark.readStream \
.format("kafka") \
.option("kafka.bootstrap.servers", "localhost:9092") \
.option("subscribe", "user-clicks") \
.option("startingOffsets", "latest") \
.load()

# 2. Process Data Payload
schema = StructType().add("user_id", StringType()).add("action", StringType())

processed_df = kafka_stream \
.selectExpr("CAST(value AS STRING) as json_payload") \
.select(from_json(col("json_payload"), schema).alias("data")) \
.select("data.*")

# 3. Write with Trigger Processing Time to enforce batching
query = processed_df.repartition(2) \
.writeStream \
.format("parquet") \
.option("path", "s3a://datatipss-data-lake/user-clicks/") \
.option("checkpointLocation", "s3a://datatipss-data-lake/checkpoints/user-clicks/") \
.trigger(processingTime="5 minutes") \
.start()

query.awaitTermination()

4. Production Best Practices: Compaction Jobs

Even with batching, spike traffic can occasionally produce sub-optimal file sizes. Implement an automated Compaction Job (using Delta Lake OPTIMIZE or PySpark) that runs overnight to rewrite micro-files into uniform 512 MB Parquet files.

The Silent Pipeline Killer: Handling Real-Time Schema Drift in Apache Spark



In modern data engineering, the only constant is change—and nowhere is that more true than in source data schemas. Upstream application teams release new features, modify API payloads or rename database columns without giving data teams a heads-up. 

When your ETL or ELT pipeline expects a rigid schema and encounters an unexpected field or a modified data type, the result is usually a catastrophic failure: broken jobs at 3:00 AM, corrupted data warehouses, and inaccurate executive dashboards.

This phenomenon—Schema Drift—is one of the most common causes of silent pipeline failures. In this guide, we’ll explore how to handle real-time schema drift in Apache Spark using Delta Lake, showing you how to implement Schema Evolution, enforce data quality gates, and route un-parseable records to a Dead Letter Queue (DLQ) without bringing down your entire data infrastructure.

1. The Nightmare: "Column 'user_id' Not Found"

Imagine waking up to a broken production pipeline at 3:00 AM because an upstream team changed user_id to userId or added a new JSON field to their API response. Traditional rigid schemas break instantly when source data changes.

2. The Strategy: Schema Enforcement vs. Schema Evolution

  • Schema Enforcement (Gatekeeper): Rejects any data that doesn't strictly match the target schema to protect warehouse integrity.

  • Schema Evolution (Adaptability): Automatically updates the target Delta table schema when new columns are introduced in the source.

3. The Implementation: PySpark & Delta Lake

from pyspark.sql import SparkSession

spark = SparkSession.builder \
.appName("SchemaDriftHandler") \
.config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
.getOrCreate()

# Read streaming or batch data with schema inference
df_incoming = spark.readStream \
.format("json") \
.option("cloudFiles.schemaLocation", "/path/to/schema/checkpoint") \
.load("/path/to/incoming/data/")

# Write with Schema Evolution enabled (.option("mergeSchema", "true"))
df_incoming.writeStream \
.format("delta") \
.option("mergeSchema", "true") \
.option("checkpointLocation", "/path/to/checkpoint") \
.start("/path/to/delta/table")

4. Handling Bad Data: The "Dead Letter Queue" (DLQ) Pattern

When schema changes are destructive (e.g., changing a data type from Integer to String), mergeSchema isn't enough. The professional best practice is routing malformed records to a Corrupt Record Path / Dead Letter Queue so valid records keep processing uninterrupted.


Conclusion

Handling schema drift isn't about blocking changes—it's about building resilient, self-healing pipelines that gracefully adapt to evolving business logic. By combining Delta Lake’s mergeSchema capabilities with proactive schema tracking and Dead Letter Queue (DLQ) patterns,you transform pipeline-breaking schema changes into manageable, automated background workflows.

Automate PII Redaction: Building Privacy-First Data Pipelines in Python


 

The "Privacy-First" Pipeline: How to Auto-Redact PII with Python

As a Data Engineer, you are the gatekeeper. If an email address, phone number, or credit card digit slips into your Snowflake or BigQuery environment unmasked, you’ve just created a major compliance risk.

In 2026, manually searching for sensitive columns is impossible. We need an automated way to Detect and Redact PII before it ever hits the storage layer.

1. The Tool: Microsoft Presidio

While many use basic Regex, the professional standard in 2026 is Microsoft Presidio. It uses a mix of pattern matching and AI (NLP) to find sensitive data even in "unstructured" text like support tickets or chat logs.

2. The Solution: A "Cleaner" Function

Instead of writing complex logic for every pipeline, we create a reusable "Cleaner" that can be dropped into any ETL script.

from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

# Initialize the engines
analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()

def redact_sensitive_data(text):
    # 1. Analyze the text to find PII (Emails, Phones, Names)
    results = analyzer.analyze(text=text, entities=["PHONE_NUMBER",
"EMAIL_ADDRESS","PERSON"], language='en')

    # 2. Anonymize (Replace with <REDACTED> or a placeholder)
    anonymized_result = anonymizer.anonymize(
        text=text,
        analyzer_results=results
    )
    return anonymized_result.text

# Example: Incoming dirty data from a support ticket
raw_comment = "Hello, my name is John Doe. My phone is 555-0123. Help!"
clean_comment = redact_sensitive_data(raw_comment)

print(clean_comment)
# Output: "Hello, my name is <PERSON>. My phone is <PHONE_NUMBER>. Help!"

3. Scaling for Big Data (Spark/Pandas)

In a real-world scenario, you wouldn't just do this for one string. You’d apply it to a whole DataFrame:

# Apply to a Pandas Column
df['comments_clean'] = df['comments'].apply(redact_sensitive_data)


Prevent Pipeline Crashes: Real-Time Data Validation with Pydantic



Stop Broken Pipelines: Real-Time Data Validation with Pydantic

In modern data engineering, "Garbage In, Garbage Out" is no longer just a saying—it's a financial risk. If your Python ETL script expects a price as a float but receives a null or a string, your pipeline crashes, and your downstream stakeholders lose trust.

The solution? Contract-driven development using Pydantic.

1. What is Pydantic?

Pydantic is a data validation library for Python that enforces type hints at runtime. Instead of writing 50 if/else statements to check your data, you define a Schema (a Class), and Pydantic does the heavy lifting.

2. The Problem: The "Silent Fail"

Look at this standard dictionary from an API. If price is missing or id is a string instead of an int, your SQL database might reject it.

raw_data = {"id": "101", "name": "Sensor_A", "price": "None"}
# This will break your DB!

3. The Solution: Defining a Data Contract

With Pydantic, we create a "Gatekeeper" for our data.

from pydantic import BaseModel, field_validator
from typing import Optional

class UserData(BaseModel):
id: int
name: str
price: float
status: Optional[str] = "active"

# We can even add custom logic!
@field_validator('price')
def price_must_be_positive(cls, v):
if v < 0:
raise ValueError('Price cannot be negative')
return v

# Now, let's validate the "dirty" data
try:
clean_data = UserData(**raw_data)
print(clean_data.model_dump())
except Exception as e:
print(f"Data Validation Failed: {e}")

4. Integrating with Airflow or Kafka

In 2026, the best practice is to put this validation at the very start of your pipeline (the Ingestion layer).

  • If validation fails: Route the "dirty" data to a Dead Letter Queue (DLQ) for manual review.

  • If validation passes: Load the data into your Warehouse (Snowflake/BigQuery).

Build a Self-Healing Airflow Pipeline: Using AI Agents to Auto-Fix Errors



Traditional Airflow DAGs are "brittle." If the source data changes from a comma (,) to a pipe (|) delimiter, the task fails, the pipeline stops, and you have to fix it manually.

In this guide, we’ll build a "Try-Heal-Retry" loop. We will use a Python agent that intercepts failures, asks an LLM (like GPT-4o or Claude 3.5) for a fix, and automatically retries the task with the new logic.

1. The Architecture: The "Healer" Loop

Instead of a standard PythonOperator, we use a custom logic where the "Retry" phase is actually an "AI Repair" phase.

2. The Secret Sauce: The on_failure_callback

Airflow allows you to run a function whenever a task fails. This is where our AI Agent lives.

The Agent Logic:

  1. Capture: Grab the last 50 lines of the task log and the failing code.

  2. Consult: Send that "context" to an LLM with a strict prompt: "Find the error and return only the corrected Python parameters."

  3. Execute: Update the Airflow Variable and trigger a retry.

3. Step-by-Step Implementation

Step A: The "Healer" Function

This function acts as your 24/7 on-call engineer.

import openai
from airflow.models import Variable

def ai_healer_agent(context):
task_instance = context['ti']
error_log = task_instance.xcom_pull(task_ids=task_instance.task_id,
key='error_msg')
prompt = f"The following Airflow task failed: {error_log}. Suggest a
fix in JSON format."
# AI identifies if it's a schema change, connection issue, or syntax error
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
# Store the 'fix' in an Airflow Variable for the next retry
Variable.set("last_ai_fix", response.choices[0].message.content)

Step B: The Self-Healing DAG

We use the tenacity library or Airflow's native retries to loop back after the agent suggests a fix.

from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime

def my_data_task(**kwargs):
# Check if the AI Agent left a 'fix' for us
fix = Variable.get("last_ai_fix", default_var=None)
# ... use the fix to run the code (e.g., change the delimiter) ...
raise ValueError("Delimiter mismatch detected!") # Example failure

with DAG('self_healing_pipeline', start_date=datetime(2026, 1, 1),
schedule='@daily') as dag:
run_etl = PythonOperator(
task_id='run_etl',
python_callable=my_data_task,
on_failure_callback=ai_healer_agent, # The Agent kicks in here!
retries=1
)

4. Why this is the "Future" 

  • MTTR (Mean Time To Recovery): You reduce your recovery time from hours to seconds.

  • Cost: You only pay for the LLM API call when a failure actually happens.

  • Human-in-the-loop: You can set the agent to "Suggest" a fix via Slack for you to approve with one click, rather than fully auto-fixing.


How to Hide API Keys in Python: Stop Leaking Secrets to GitHub


 

Whether you are building a data pipeline in Airflow or a simple AI bot, you should never hard-code your API keys directly in your Python script. If you push that code to a public repository, hackers will find it in seconds using automated scanners.

Here is the professional way to handle secrets using Environment Variables and .env files.

1. The Tool: python-dotenv

The industry standard for managing local secrets is a library called python-dotenv. It allows you to store your keys in a separate file that never gets uploaded to the internet.

Install it via terminal:

pip install python-dotenv

2. Create your .env File

In your project’s root folder, create a new file named exactly .env. Inside, add your secrets like this:

# .env file
DATABASE_URL=postgres://user:password@localhost:5432/mydb
OPENAI_API_KEY=sk-your-secret-key-here
AWS_SECRET_ACCESS_KEY=your-aws-key

3. Access Secrets in Python

Now, you can load these variables into your script without ever typing the actual key in your code.

import os
from dotenv import load_dotenv

# Load the variables from .env into the system environment
load_dotenv()

# Access them using os.getenv
api_key = os.getenv("OPENAI_API_KEY")
db_url = os.getenv("DATABASE_URL")

print(f"Successfully connected to the database!")

4. The Most Important Step: .gitignore

This is where the "Security" part happens. You must tell Git to ignore your .env file so it never leaves your computer.

Create a file named .gitignore and add this line:

.env

Why this is a "DevSecOps" Win:

  • Security: Your keys stay on your machine.

  • Flexibility: You can use different keys for "Development" and "Production" without changing a single line of code.

  • Collaboration: Your teammates can create their own local .env files with their own credentials.

Why is my Airflow Task stuck in "Queued" state? (5 Quick Fixes)


 

You’ve triggered your DAG, the UI shows the task as grey (Queued), but nothing happens for minutes—or hours. This is a classic Airflow bottleneck. Here is how to diagnose and fix it.

1. Check the "Concurrency" Limits

Airflow has several "safety brakes" to prevent your server from crashing. If you hit these limits, tasks will stay queued until others finish.

  • parallelism: The max number of task instances that can run across your entire Airflow environment.

  • dag_concurrency: The max number of tasks that can run for a single DAG.

  • max_active_runs_per_dag: If you have too many "Backfills" running, new tasks won't start.

The Fix: Check your airflow.cfg or your DAG definition. Increase max_active_tasks if your hardware can handle it.

2. Is the Scheduler actually alive?

Sometimes the Airflow UI looks fine, but the Scheduler process has died or hung.

  • Check the UI: Look at the top of the Airflow page. If there is a red banner saying "The scheduler does not appear to be running," that’s your answer.

  • The Fix: Restart the scheduler service:

  • systemctl restart airflow-scheduler
    # OR if using Docker:
    docker restart airflow-scheduler

3. "No Slots Available" in Pools

Airflow uses Pools to manage resources (like limiting how many tasks can hit a specific database at once). If your task belongs to a pool with 5 slots and 5 tasks are already running, your 6th task will stay Queued forever.

The Fix: Go to Admin -> Pools in the UI. Check if the "Default Pool" or your custom pool is full. Increase the slots if necessary.

4. Celery Worker Issues (For Production Setups)

If you are using the CeleryExecutor, the task is queued in Redis or RabbitMQ, but the Worker might not be picking it up.

  • The Check: Run airflow celery inspect_short to see if workers are online.

  • The Fix: Ensure your workers are pointed to the same Metadata DB and Broker as your Scheduler.

5. Resource Starvation (OOM)

If your worker node is out of RAM or CPU, it might accept the task but fail to initialize it, leading to a loop where the task stays queued.

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...