Implementing PostgreSQL Logical Replication for Realtime Workflows
What You’ll Need
To follow along with this tutorial, you will need the following infrastructure and services:
- A Linux server (Ubuntu 22.04 LTS recommended) deployed on Hetzner VPS or Contabo VPS. You can also use DigitalOcean if you prefer their cloud ecosystem.
- PostgreSQL version 14 or higher installed on your primary server.
- An automation platform like n8n Cloud (or a self-hosted instance) to consume change events and trigger workflows.
- A registered domain name via Namecheap if you are exposing public webhook endpoints over HTTPS.
Table of Contents
- Understanding PostgreSQL Logical Replication vs Polling
- Configuring PostgreSQL for Logical Replication
- Building a Dedicated Change Data Capture Worker in Python
- Connecting Replication Workflows to Realtime Consumers
- Getting Started
Understanding PostgreSQL Logical Replication vs Polling
Traditional database-driven automation relies heavily on periodic polling. A script queries a table every minute, looks for records where processed = false, updates them, and triggers downstream actions. While polling works for low-throughput applications, it creates significant bottlenecks at scale. Polling introduces inherent latency, generates unnecessary disk I/O, burns CPU cycles on idle queries, and creates race conditions when multiple worker nodes run simultaneously.
If you are running complex database architectures, such as tenant-isolated environments, polling becomes even more inefficient. If you are building multi-tenant SaaS databases, check out my guide on Configuring PostgreSQL Row Level Security for Multitenancy to keep your data isolated before streaming changes across services.
Instead of relying on periodic polling (such as Executing Scheduled Python Tasks Using APScheduler), PostgreSQL logical replication allows us to implement event-driven architectures directly from the write-ahead log (WAL).
Logical replication streams row-level data changes (INSERT, UPDATE, DELETE) in real time to external consumers. PostgreSQL streams binary WAL records to a logical decoding plugin, which translates engine-level storage changes into structured data changes. This architectural pattern, known as Change Data Capture (CDC), gives you sub-millisecond execution triggers without placing extra query load on your primary relational tables.
+------------------+ +-------------------+ +----------------------+ +-------------------+
| PostgreSQL DB | | WAL & Logical | | Python CDC Worker | | Workflow Engine |
| (INSERT/UPDATE) | ----> | Replication Slot | ----> | (Streaming Receiver) | ----> | (n8n Webhook) |
+------------------+ +-------------------+ +----------------------+ +-------------------+
By connecting a streaming Python consumer directly to PostgreSQL replication slots, we can push row modifications instantly into downstream platforms like n8n Cloud.
Configuring PostgreSQL for Logical Replication
To enable logical replication, you must update the core configuration parameters of your PostgreSQL server. By default, PostgreSQL sets wal_level to replica, which only supports physical replication to standby nodes. We need to set this parameter to logical.
Step 1: Updating postgresql.conf
Open your postgresql.conf file (typically located at /etc/postgresql/15/main/postgresql.conf on Ubuntu systems) and modify or append the following settings:
# /etc/postgresql/15/main/postgresql.conf
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10
track_commit_timestamp = on
The max_replication_slots parameter defines how many streaming consumers can connect simultaneously, while max_wal_senders dictates the maximum number of concurrent WAL streaming connections allowed by the database engine.
Restart PostgreSQL to apply the parameter changes:
sudo systemctl restart postgresql
Step 2: Creating the Database Schema and Replication Objects
Log into your PostgreSQL instance using psql as a superuser:
sudo -u postgres psql
Execute the following DDL statements to set up a dedicated application database, a sample order tracking table, a replication user role, and a logical publication:
CREATE DATABASE workflow_db;
\c workflow_db;
CREATE TABLE public.orders (
id SERIAL PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
total_amount NUMERIC(10, 2) NOT NULL,
order_status VARCHAR(50) NOT NULL DEFAULT 'pending',
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE public.orders REPLICA IDENTITY FULL;
CREATE ROLE cdc_worker WITH REPLICATION LOGIN PASSWORD 'DbSecurePass2025!';
GRANT CONNECT ON DATABASE workflow_db TO cdc_worker;
GRANT USAGE ON SCHEMA public TO cdc_worker;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO cdc_worker;
CREATE PUBLICATION orders_publication FOR TABLE public.orders;
Setting REPLICA IDENTITY FULL ensures that PostgreSQL includes both the old and new values of every column in the logical stream when an UPDATE or DELETE operation occurs. Without this setting, update logs only include changed columns or primary key values.
💡 Fast-Track Your Project: Don’t want to configure this yourself? I build custom n8n pipelines and bots. Message me with code SYS3-HUGO.
Building a Dedicated Change Data Capture Worker in Python
Now that PostgreSQL is publishing row-level changes, we need a lightweight, production-grade daemon to stream these WAL events, convert them into JSON payloads, and forward them to external API endpoints.
We will use psycopg2 and its LogicalReplicationConnection interface, utilizing the standard PostgreSQL test_decoding logical output plugin.
Step 1: Installing Python Dependencies
Run the following command on your server (hosted on Hetzner VPS or Contabo VPS) to install the required Python libraries:
pip install psycopg2-binary requests
Step 2: Writing the CDC Consumer Daemon
Create a file named cdc_worker.py. This script connects to the PostgreSQL replication slot, reads real-time change events, parses raw text decoded from the test_decoding engine, and dispatches HTTP POST requests to an external workflow webhook.
import sys
import time
import json
import re
import requests
import psycopg2
import psycopg2.extras
DB_CONFIG = {
"dbname": "workflow_db",
"user": "cdc_worker",
"password": "DbSecurePass2025!",
"host": "127.0.0.1",
"port": 5432
}
SLOT_NAME = "cdc_orders_slot"
PUBLICATION_NAME = "orders_publication"
WEBHOOK_URL = "https://n8n.example.com/webhook/pg-cdc-event"
def parse_test_decoding_output(raw_payload):
pattern = r"table public\.(\w+): (INSERT|UPDATE|DELETE): (.*)"
match = re.match(pattern, raw_payload)
if not match:
return None
table_name = match.group(1)
action = match.group(2)
raw_data = match.group(3)
fields = {}
tokens = re.findall(r'(\w+)\[([^\]]+)\]:\'([^\']*)\'|(\w+)\[([^\]]+)\]:null', raw_data)
for token in tokens:
if token[0]:
col_name = token[0]
val = token[2]
fields[col_name] = val
elif token[3]:
col_name = token[3]
fields[col_name] = None
return {
"table": table_name,
"action": action,
"data": fields,
"timestamp": time.time()
}
def process_wal_message(msg):
payload = msg.payload
parsed_event = parse_test_decoding_output(payload)
if parsed_event:
print(f"Captured CDC Event: {parsed_event['action']} on table {parsed_event['table']}")
try:
response = requests.post(
WEBHOOK_URL,
json=parsed_event,
headers={"Content-Type": "application/json"},
timeout=5
)
print(f"Forwarded to webhook. Status Code: {response.status_code}")
except Exception as err:
print(f"Failed to post CDC event to webhook: {err}", file=sys.stderr)
msg.cursor.consume_stream(msg)
def run_cdc_listener():
conn = psycopg2.connect(
dbname=DB_CONFIG["dbname"],
user=DB_CONFIG["user"],
password=DB_CONFIG["password"],
host=DB_CONFIG["host"],
port=DB_CONFIG["port"],
connection_factory=psycopg2.extras.LogicalReplicationConnection
)
cursor = conn.cursor()
try:
cursor.create_replication_slot(SLOT_NAME, output_plugin="test_decoding")
print(f"Created logical replication slot: {SLOT_NAME}")
except psycopg2.ProgrammingError:
print(f"Replication slot {SLOT_NAME} already exists.")
print(f"Starting CDC stream on slot '{SLOT_NAME}'...")
options = {
"include-xids": "0",
"include-timestamp": "1"
}
cursor.start_replication(
slot_name=SLOT_NAME,
options=options,
decode=True
)
def consume_callback(msg):
process_wal_message(msg)
while True:
try:
cursor.consume_stream(consume_callback)
except KeyboardInterrupt:
print("Stopping CDC stream worker...")
cursor.close()
conn.close()
sys.exit(0)
except Exception as e:
print(f"Stream error encountered: {e}", file=sys.stderr)
time.sleep(2)
if __name__ == "__main__":
run_cdc_listener()
This Python script maintains a persistent connection to PostgreSQL using WAL streaming. When an INSERT, UPDATE, or DELETE statement hits the database, PostgreSQL forwards the change directly to the Python daemon. The worker formats the payload and issues an HTTP POST request to your processing workflow.
Connecting Replication Workflows to Realtime Consumers
Once change events flow out of PostgreSQL, you can process them inside your infrastructure. A common setup uses an automation platform like n8n Cloud to handle business logic, generate notification emails, or send instant mobile alerts.
For critical events, such as immediate system alerts, look into Deploying Self Hosted Gotify Notification Server to deliver high-priority push notifications straight to your devices without third-party delay.
Step 1: Setting up a Systemd Service for standard reliability
To ensure your CDC script runs continuously and recovers automatically from server reboots or network disconnects, create a systemd unit file on your host machine.
Create the service file:
sudo nano /etc/systemd/system/pg-cdc-worker.service
Add the following configuration:
[Unit]
Description=PostgreSQL CDC Worker Service
After=network.target postgresql.service
[Service]
Type=simple
User=root
WorkingDirectory=/opt/cdc_worker
ExecStart=/usr/bin/python3 /opt/cdc_worker/cdc_worker.py
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reload
sudo systemctl enable pg-cdc-worker
sudo systemctl start pg-cdc-worker
Verify that your worker is operational and listening to replication slots:
sudo systemctl status pg-cdc-worker
Step 2: Testing the Complete Realtime Pipeline
Now, trigger an insert on your database to test the stream:
\c workflow_db;
INSERT INTO public.orders (customer_name, email, total_amount, order_status)
VALUES ('Jane Doe', 'jane.doe@example.com', 149.99, 'completed');
Check the systemd logs of your CDC worker:
sudo journalctl -u pg-cdc-worker.service -n 20 --no-pager
You will see output confirming that PostgreSQL captured the WAL event, decoded it in memory, and delivered the change to your designated endpoint in milliseconds:
Captured CDC Event: INSERT on table orders
Forwarded to webhook. Status Code: 200
By removing polling loops and integrating native logical replication streaming directly into downstream workflow runners like n8n Cloud, you unlock immediate database event processing while keeping your server resources light and efficient.
Getting Started
Building resilient event-driven architectures requires reliable hosting and flexible tools:
- Provision cloud infrastructure on Hetzner VPS, Contabo VPS, or DigitalOcean.
- Secure domain names for public HTTPS webhooks using Namecheap.
- Build visual event processing pipelines using n8n Cloud.
Outsource Your Automation
Don’t have time? I build production n8n workflows, WhatsApp bots, and fully automated YouTube Shorts pipelines. Hire me on Fiverr, mention SYS3-HUGO for priority. Or DM at chasebot.online.
Want to automate this yourself?
Start with n8n Cloud (free tier available) or self-host on a Hetzner VPS for full control.
Want this engine running on your own VPS?
This blog publishes itself — daily, unattended, on free API tiers. The full engine, Hugo theme, and setup guide are available as System 3.
Get System 3