Showing posts with label postgreSQL. Show all posts
Showing posts with label postgreSQL. 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 Prevent SQL Injection & Bulk Data Exfiltration in Production Databases

 


Defending Production Databases: Preventing SQL Injection and Bulk Data Exfiltration

1. Introduction

If you inspect the raw access logs or analytics referrers of almost any public-facing domain, you will see automated bots firing obfuscated payloads like -1157"))/**/uniON/**/ALL/**/SElEct/**/69,69,69,69--. Automated scanners like sqlmap continuously probe web applications, APIs, and headers looking for unsanitized inputs that pass directly to a backend database.

While static blogs on managed platforms are immune to these probes, any application backed by PostgreSQL, SQL Server, or MySQL faces two catastrophic risks if an injection flaw or compromised API key slips into production:

  1. Authentication Bypass & Data Manipulation via classic SQL Injection (SQLi).

  2. Silent Bulk Exfiltration, where an attacker dumps millions of customer rows (SELECT * FROM users) before security alerts ever trigger.

In this guide, we’ll walk through how to build defense-in-depth at both the application layer and the database engine layer.

2. Layer 1: Parameterized Queries (Eliminating SQLi at the Root)

String concatenation is the root cause of SQL injection. Even if you strip out keywords like UNION or SELECT, attackers bypass blacklists using inline comments (/**/), hex encoding, and mixed casing.

❌ Vulnerable Pattern (Never Do This)

# Attacker passes: "101 OR 1=1; DROP TABLE orders;--"
query = f"SELECT order_id, total FROM orders WHERE customer_id = {user_input}"
cursor.execute(query)

✅ Secure Pattern (Parameterized Execution)

When using parameterized queries (prepared statements), the database engine compiles the SQL execution plan before inserting parameter values. User input is strictly treated as a literal value, never executable SQL syntax.

import psycopg2

conn = psycopg2.connect("dbname=prod_db user=app_reader password=***")
cursor = conn.cursor()

# The database treats user_input strictly as a literal string/integer
query = "SELECT order_id, total FROM orders WHERE customer_id = %s"
cursor.execute(query, (user_input,))
records = cursor.fetchall()

3. Layer 2: Database Principle of Least Privilege

Most production breaches escalate because the web application connects to the database using a superuser or db_owner account. If an attacker finds a single injection flaw, they can execute OS-level commands (like xp_cmdshell in SQL Server) or read system catalogs (pg_shadow, information_schema).

Enforce Role Separation in PostgreSQL / SQL Server:

  1. Revoke Schema Modification Rights: Application service accounts should never have CREATE, DROP, or ALTER permissions.

  2. Restrict System Catalog Access: Prevent application roles from querying information_schema.tables to stop attackers from mapping your schema.

  3. Separate Read/Write Roles: Use a read-only replica user for analytics dashboards and restrict DELETE permissions on sensitive tables.

-- PostgreSQL Least-Privilege Application Role Setup
CREATE ROLE app_service_user WITH LOGIN PASSWORD 'StrongGeneratedPassword!';

-- Grant access ONLY to specific application schema and tables
GRANT USAGE ON SCHEMA sales TO app_service_user;
GRANT SELECT, INSERT, UPDATE ON sales.orders, sales.customers TO app_service_user;

-- Explicitly block destructive operations
REVOKE DELETE, TRUNCATE ON ALL TABLES IN SCHEMA sales FROM app_service_user;

4. Layer 3: Blocking Bulk Data Exfiltration with Row-Level Security (RLS)

Even with parameterized queries, what happens if an attacker compromises a valid API token and attempts to scrape your entire database via legitimate API endpoints?

Row-Level Security (RLS) enforces access control directly inside the database engine, ensuring a session can only access rows belonging to the authenticated tenant or user—even if an attacker runs SELECT * FROM customers.

-- Enable Row-Level Security on multi-tenant table
ALTER TABLE sales.customers ENABLE ROW LEVEL SECURITY;

-- Create policy restricting access to the current session's tenant_id
CREATE POLICY tenant_isolation_policy ON sales.customers
USING (tenant_id = current_setting('app.current_tenant_id')::UUID);

When your application opens a connection, it sets the session variable:

SET LOCAL app.current_tenant_id = 'a8b2c4d0-1122-3344-5566-778899aabbcc';

Now, even a compromised query cannot dump data across tenants.

5. Layer 4: Query Timeouts & Anomaly Detection

Automated exfiltration scripts rely on long-running SELECT queries or rapid pagination bursts. Add hard guardrails at the database level:

  • Enforce Statement Timeouts: Kill runaway queries automatically before they can dump large tables.

ALTER ROLE app_service_user SET statement_timeout = '5s';

  • Enable Audit Logging (pgAudit / SQL Server Audit): Log all queries returning more than 10,000 rows or touching PII columns (ssn, email, password_hash) and stream those logs to your SIEM or CloudWatch for real-time alerting.

6. Production Security Checklist

  • 🛡️ Zero String Interpolation: Enforce static code analysis (Bandit, Semgrep) in CI/CD to block raw f-strings in SQL calls.

  • 🔑 Rotate & Vault Credentials: Store DB credentials in AWS Secrets Manager or HashiCorp Vault with automatic 30-day rotation.

  • 🔒 Disable Dangerous Extensions: Ensure xp_cmdshell (SQL Server) and untrusted procedural languages (plpythonu in PostgreSQL) are disabled.

  • 📊 Monitor information_schema Queries: Trigger an immediate P1 security alert if an application user queries system metadata tables.

Summary

Defending production databases requires more than just a Web Application Firewall. By combining parameterized queries at the code layer with least-privilege roles, Row-Level Security, and strict statement timeouts inside the database engine, you neutralize both automated sqlmap probes and insider/API-level data exfiltration attempts.

💬 How do you lock down database access in your production environments? Are you using Row-Level Security or database proxies to inspect queries? Share your setup in the comments below!

🔔 Found this guide useful? Share it with your backend and data engineering teams, and subscribe to DataTipss for practical deep dives into Database Engineering, DevSecOps, and Cloud Architecture!

Terraform for Data Engineers: How to Automate Your Database Setup


 

Stop Manual Setup: Deploy a PostgreSQL Database with Terraform

If you are still manually creating databases in the AWS or Azure console, you are creating a "Snowflake Server"—a unique setup that no one can replicate if it breaks.

In 2026, professional data teams use Terraform. It allows you to write your infrastructure as code, version control it on GitHub, and deploy it perfectly every single time.

1. What is Terraform?

Terraform is a tool that lets you define your infrastructure (Databases, S3 Buckets, Kubernetes clusters) using a simple language called HCL (HashiCorp Configuration Language).

2. The Setup: provider.tf

First, we tell Terraform which cloud we are using. For this guide, we’ll use AWS, but the logic works for any cloud.

provider "aws" {
region = "us-east-1"
}

3. The Code: main.tf

Instead of clicking "Create Database," we write this block. This defines a small, cost-effective PostgreSQL instance.

resource "aws_db_instance" "datatipss_db" {
allocated_storage = 20
engine = "postgres"
engine_version = "15.4"
instance_class = "db.t3.micro" # Free tier eligible!
db_name = "analytics_db"
username = "admin_user"
password = var.db_password # Use a variable for security!
skip_final_snapshot = true
publicly_accessible = true
}

4. The Magic Commands

Once your code is written, you only need three commands to rule your infrastructure:

  1. terraform init: Downloads the AWS plugins.

  2. terraform plan: Shows you exactly what will happen (The "Preview" mode).

  3. terraform apply: Build the database!


How to Fix PostgreSQL Error: "FATAL: sorry, too many clients already"



 If you are seeing the error FATAL: sorry, too many clients already or FATAL: too many connections for role "username", your PostgreSQL instance has hit its limit of concurrent connections.

This usually happens when:

  • Your application isn't closing database connections properly.

  • You have a sudden spike in traffic.

  • A connection pooler (like PgBouncer) isn't configured.

Step 1: Check Current Connection Usage

Before changing any settings, you need to see who is using the connections. Run this query to get a breakdown of active vs. idle sessions:

SELECT count(*), state 

FROM pg_stat_activity 

GROUP BY state;

If you see a high number of "idle" connections, your application is likely "leaking" connections (opening them but never closing them).

Step 2: Emergency Fix (Kill Idle Connections)

If your production site is down because of this error, you can manually terminate idle sessions to free up slots immediately:

-- This kills all idle connections older than 5 minutes

SELECT pg_terminate_backend(pid)

FROM pg_stat_activity

WHERE state = 'idle' 

AND state_change < current_timestamp - interval '5 minutes';

Step 3: Increase max_connections (The Configuration Fix)

The default limit in PostgreSQL is often 100. If your hardware has enough RAM, you can increase this.

  1. Find your config file: SHOW config_file;

  2. Open postgresql.conf and find the max_connections setting.

  3. Change it to a higher value (e.g., 200 or 500).

  4. Restart PostgreSQL for changes to take effect.

Warning: Every connection consumes memory (roughly 5-10MB). If you set this too high, you might run the entire server out of RAM (OOM).

Step 4: The Professional Solution (Connection Pooling)

Increasing max_connections is a temporary fix. For a production-grade setup, you should use PgBouncer.

Instead of your application connecting directly to Postgres, it connects to PgBouncer. PgBouncer keeps a small pool of real connections open to the database and rotates them among hundreds of incoming requests.

Sample pgbouncer.ini configuration:

[databases]

mydatabase = host=127.0.0.1 port=5432 dbname=mydatabase


[pgbouncer]

listen_port = 6432

auth_type = md5

pool_mode = transaction

max_client_conn = 1000

default_pool_size = 20

Summary Checklist

  • Audit your code: Ensure every db.connect() has a corresponding db.close().

  • Monitor: Set up alerts for when connections exceed 80% of max_connections.

  • Scale: Use a connection pooler like PgBouncer or pg_pool if you have more than 100 active users.




SQL query to find duplicate records

Introduction

These days data is growing massively and since the data is growing the amount of bad data is also growing. Today we'll talk about one form of bad data which we can call duplicate data. We use few database management systems to store and process the data ie sql server, postgresql, oracle etc. We store lot of data in these systems but sometimes we get lot duplicate data as well in our systems which can impact the true data and reporting on which lot of businesses and important decisions are dependent.

  So for us working on data, it's very important to identify the duplicates and remove them from the database which help businesses towards better reporting. 

Let's get into the practical to understand the duplicates. First we need to create a table with few columns.

In this tutorial I am using postgresql. 

CREATE TABLE duplicate_data_test(
id int,
name text
)

now let's insert some data with duplicates.

insert into duplicate_data_test values(1,'One');
insert into duplicate_data_test values(1,'One');
insert into duplicate_data_test values(2,'two');
insert into duplicate_data_test values(3,'three');
insert into duplicate_data_test values(4,'four');
insert into duplicate_data_test values(5,'three');

Query the data to see results:

select * from duplicate_data_test;













Let's find the duplicates for entire row.

select id,name,count(*) as count from duplicate_data_test
group by id,name having count(*) > 1;

or

Using CTE as well to get the duplicates.

with cte(id,name)
as
(select id,name,row_number() over (partition by id,name order by id) as rn
from duplicate_data_test)
select * from cte;

Above query will give you the count. You can remove the count in select list if you want and then you will get duplicate record without count number. 















Sometimes we want to find duplicates based on one column. Sometime we don't have entire row is duplicate rather just one column have some duplicate values. 

So we can definitely use partition by clause like below.

select * from (
select id,name,rank() over (partition by name order by id) as rnk
from duplicate_data_test
) as dt where dt.rnk > 1













Conclusion

That was it about duplicates. Always test above code in lower environment before implementing in Production.


How to run PostgreSQL on Docker



Postgres on Docker 

Postgres is most advanced object relational database management system(ORDBMS). Postgres implements majority of SQL:2011 standard. It's ACID compliant and It avoids locking issues using multiversion concurrency control. So today we are going to run Postgres on Docker.

To start with Postgres we first need to pull the image from DockerHub. DockerHub is image repository for all images. Let's run the below command and pull the image:

docker pull postgres

Using default tag: latest

latest: Pulling from library/postgres

a9eb63951c1c: Pull complete 

b192c7f382df: Pull complete 

e7ce3f587986: Pull complete 

4098744a1414: Pull complete 

4c98d6f3399d: Pull complete 

65e57fefc38a: Pull complete 

d61d9528cfd5: Pull complete 

de6b20f44659: Pull complete 

25db13ff0bef: Pull complete 

7f74f4b0e936: Pull complete 

144c847b11fb: Pull complete 

cf0afd1be009: Pull complete 

fe0c14991327: Pull complete 


Now let's check that we have downloaded the image.

docker images

REPOSITORY        TAG       IMAGE ID       CREATED       SIZE

postgres          latest    83ce63c594ee   5 days ago    355MB


Let's run the image and start a container.

docker run --name test -e POSTGRES_PASSWORD=Test@123 -d postgres


Just run the docker ps command to check if container is running

docker ps

CONTAINER ID   IMAGE      COMMAND                  CREATED         STATUS   

83ec4a222   postgres   "docker-entrypoint.s…"   2 minutes ago   Up 


Let's enter in bash shell of container by running below command

docker exec -it 83ec4a222 bash

root@83ec4a222:/# 


Connect to Postgres now:

psql -h localhost -p 5432 -U postgres -w

psql (14.0 (Debian 14.0-1.pgdg110+1))

Type "help" for help.


You are connected to Postgres now. Lets' create some tables and execute some queries.

postgres=# \l

                                 List of databases

   Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges   

-----------+----------+----------+------------+------------+-----------------------

 postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 | 

 template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +

           |          |          |            |            | postgres=CTc/postgres

 template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +

           |          |          |            |            | postgres=CTc/postgres

(3 rows)


postgres=# 



Let's check the current database name by running below command.

postgres=# select current_database();

 current_database 

------------------

 postgres

(1 row)


So current database is Postgres. We'll check now how many databases are there on the system.

postgres=# select datname from pg_catalog.pg_database;

  datname  

-----------

 postgres

 template1

 template0

(3 rows)


There are total 3 databases on system.

You can check all tables on a database by querying information schema.

postgres=# select table_name from information_schema.tables limit 10;

      table_name       

-----------------------

 pg_statistic

 pg_type

 pg_foreign_table

 pg_authid

 pg_shadow

 pg_statistic_ext_data

 pg_roles

 pg_settings

 pg_file_settings

 pg_hba_file_rules

(10 rows)



We can do a lot more than this on Postgres this was just a small part about Postgres. We can get all information about all tables and databases just by using information schema. Docker can be very useful in this case when we don't want to install it on system and want to run Postgres inside container and can leverage the power of Docker.

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

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