Skip to content

Postgres logical decoding to a downstream analytics warehouse with wal2json

Stream every row change from a PostgreSQL 16 database into your analytics warehouse within about ninety seconds, using logical decoding with the wal2json plugin and a small Python consumer. You will set up the replication slot, the consumer and the idempotent merge, then monitor the lag.

If your analytics warehouse trails your PostgreSQL 16 application database by a day, this article shows you how to stream every row change to the warehouse within about ninety seconds. It is written for the engineer who owns the database and is tired of nightly pg_dump loads and hand-made CSV exports. The method is logical decoding. PostgreSQL’s write-ahead log, the file where it records every change before applying it, is read through a replication slot. The wal2json plugin turns each change into a JSON event, and a small Python consumer ships those events to your warehouse loader. The slot remembers the last position the consumer confirmed, so the consumer can crash and resume without skipping or repeating an event. You will install that pipeline against PostgreSQL 16 with wal2json, a Python consumer built on psycopg, and an idempotent merge on the warehouse side, meaning a load that can be applied twice without creating duplicates.

What’s happening

PostgreSQL logical decoding is the database’s first-class CDC mechanism. You declare a replication slot (SELECT pg_create_logical_replication_slot('analytics_slot','wal2json')) and a downstream consumer connects with replication=database and starts reading. The output plugin (wal2json here, but pgoutput is the built-in alternative used by logical replication subscriptions) takes the raw WAL records and emits one JSON object per transaction, with one entry per row change. The consumer reads these in transaction order, ships them to the warehouse, and acknowledges the LSN it’s processed up to. Postgres holds onto the WAL behind the slot until it’s acknowledged — which means an inactive slot is dangerous: WAL accumulates and your data directory fills up. Slot monitoring isn’t optional; it’s the first alert you set up.

A few things have to line up:

  • wal_level = logical and a restart of Postgres. Without it, no logical slot can be created.
  • max_replication_slots and max_wal_senders both raised above the default — one slot consumes one walsender process.
  • A replication role (CREATE ROLE analytics_repl WITH REPLICATION LOGIN PASSWORD 'x') in pg_hba.conf with replication listed.
  • Idempotent merges downstream. Logical decoding gives you at-least-once on a clean restart and exactly-once only if you make the consumer transactional with the warehouse. In practice you design the warehouse table for upsert-by-primary-key and treat duplicates as a no-op.

How to verify

After the installer, four checks tell you the pipeline is alive:

# 1. wal_level + slot exist
sudo -u postgres psql -c "SHOW wal_level"
sudo -u postgres psql -c "SELECT slot_name, plugin, active, restart_lsn, confirmed_flush_lsn FROM pg_replication_slots"

# 2. The consumer is connected (walsender visible)
sudo -u postgres psql -c "SELECT application_name, client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn FROM pg_stat_replication"

# 3. Slot lag in bytes (alert if > 50 MB and growing)
sudo -u postgres psql -c "SELECT slot_name, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS lag FROM pg_replication_slots"

# 4. Consumer service is running
systemctl status wal2json-consumer | head -20

Then write a row and watch it appear in the warehouse:

INSERT INTO orders(amount, status) VALUES (199.00, 'paid');

If the row doesn’t reach the warehouse within ninety seconds, the consumer logs are the first place to look (journalctl -u wal2json-consumer -f). If pg_replication_slots.active shows f, the consumer is disconnected and WAL is accumulating — restart the consumer and confirm the slot becomes active again.

The fix

Save the script as /root/setup-wal2json-warehouse.sh and run it on the Postgres primary (or a dedicated CDC node co-located with it). It installs wal2json, enables logical replication, creates the slot and the replication user, drops a Python consumer (/opt/wal2json-consumer/) that ships JSON events to a pluggable warehouse loader. It wires the consumer as a systemd unit with restart-on-failure, and registers a node_exporter-friendly textfile collector that surfaces slot lag as a metric you can scrape.

#!/usr/bin/env bash
set -euo pipefail

### Postgres 16 logical decoding -> warehouse loader via wal2json
### Run as root on the primary (or a node that can reach it on 5432)
### Assumes Postgres 16 already installed (e.g. from PGDG) and superuser psql works
### Warehouse target is pluggable — the loader has a stub for HTTP POST to your warehouse ingestion endpoint

if [[ "$(id -u)" -ne 0 ]]; then echo "Run as root."; exit 1; fi

# === EDIT ===
PG_HOST="10.10.0.20"
PG_PORT="5432"
PG_DB="appdb"
REPL_USER="analytics_repl"
REPL_PASSWORD="CHANGE_ME_REPL"
SLOT_NAME="analytics_slot"
WAREHOUSE_INGEST_URL="https://warehouse.internal.example.com/ingest"
WAREHOUSE_TOKEN="CHANGE_ME_WAREHOUSE_TOKEN"
PUBLICATION_NAME="analytics_pub"
TABLES_TO_REPLICATE="public.orders, public.customers"
# ============

echo "==> Detecting OS"
if [[ -f /etc/almalinux-release || -f /etc/rocky-release || -f /etc/redhat-release ]]; then
  PKG="dnf"
  dnf -y install epel-release || true
  dnf -y install wal2json_16 python3 python3-pip python3-virtualenv \
    postgresql16 jq curl
elif [[ -f /etc/lsb-release || -f /etc/debian_version ]]; then
  PKG="apt"
  apt-get update
  DEBIAN_FRONTEND=noninteractive apt-get -y install postgresql-16-wal2json \
    python3 python3-pip python3-venv postgresql-client jq curl
else
  echo "Unsupported OS"; exit 1
fi

echo "==> Enabling wal_level=logical (requires Postgres restart)"
sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -c "ALTER SYSTEM SET wal_level = 'logical'"
sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -c "ALTER SYSTEM SET max_replication_slots = 16"
sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -c "ALTER SYSTEM SET max_wal_senders = 16"
sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -c "SELECT pg_reload_conf()"

if [[ "${PKG}" == "dnf" ]]; then
  systemctl restart postgresql-16
else
  systemctl restart postgresql
fi

echo "==> Waiting for Postgres back up"
for i in {1..30}; do
  if sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -tAc "SELECT 1" >/dev/null 2>&1; then break; fi
  sleep 2
done

echo "==> Replication role + slot + publication"
sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} <<SQL
DO \$\$ BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${REPL_USER}') THEN
    CREATE ROLE ${REPL_USER} WITH REPLICATION LOGIN PASSWORD '${REPL_PASSWORD}';
  END IF;
END \$\$;
GRANT CONNECT ON DATABASE ${PG_DB} TO ${REPL_USER};
SQL

sudo -u postgres psql -h ${PG_HOST} -p ${PG_PORT} -d ${PG_DB} <<SQL
GRANT USAGE ON SCHEMA public TO ${REPL_USER};
GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${REPL_USER};
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO ${REPL_USER};

-- Slot creation is idempotent: skip if already there
SELECT pg_create_logical_replication_slot('${SLOT_NAME}', 'wal2json')
WHERE NOT EXISTS (SELECT 1 FROM pg_replication_slots WHERE slot_name = '${SLOT_NAME}');
SQL

echo "==> pg_hba: add a replication entry"
PG_HBA=$(sudo -u postgres psql -tAc "SHOW hba_file")
if ! grep -q "${REPL_USER}.*replication" "${PG_HBA}"; then
  echo "hostssl  ${PG_DB}   ${REPL_USER}   0.0.0.0/0   scram-sha-256" >> "${PG_HBA}"
  echo "hostssl  replication ${REPL_USER}  0.0.0.0/0   scram-sha-256" >> "${PG_HBA}"
  sudo -u postgres psql -c "SELECT pg_reload_conf()"
fi

echo "==> Creating consumer user and venv"
id -u wal2json >/dev/null 2>&1 || useradd -r -s /usr/sbin/nologin -d /opt/wal2json-consumer wal2json
mkdir -p /opt/wal2json-consumer /var/log/wal2json /var/lib/wal2json
chown -R wal2json:wal2json /opt/wal2json-consumer /var/log/wal2json /var/lib/wal2json

sudo -u wal2json python3 -m venv /opt/wal2json-consumer/venv
sudo -u wal2json /opt/wal2json-consumer/venv/bin/pip install --upgrade pip
sudo -u wal2json /opt/wal2json-consumer/venv/bin/pip install \
  "psycopg[binary,pool]==3.2.1" \
  "requests==2.32.3" \
  "tenacity==9.0.0"

echo "==> Consumer source"
cat > /opt/wal2json-consumer/consumer.py <<'PY'
#!/usr/bin/env python3
"""
wal2json -> warehouse consumer.

Streams change events from a wal2json replication slot, batches them by
transaction, and POSTs them to the warehouse ingest endpoint. On HTTP 2xx we
acknowledge the LSN; otherwise we let the slot retain WAL and retry.

Designed for at-least-once with idempotent merges downstream (warehouse table
MUST upsert by primary key). We never ack until the warehouse confirms.
"""
import os, sys, json, time, signal, logging
from datetime import datetime
import psycopg
from psycopg import sql
import requests
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type

PG_HOST   = os.environ["PG_HOST"]
PG_PORT   = int(os.environ.get("PG_PORT", "5432"))
PG_DB     = os.environ["PG_DB"]
PG_USER   = os.environ["REPL_USER"]
PG_PASS   = os.environ["REPL_PASSWORD"]
SLOT      = os.environ["SLOT_NAME"]
INGEST    = os.environ["WAREHOUSE_INGEST_URL"]
TOKEN     = os.environ["WAREHOUSE_TOKEN"]
BATCH_MAX = int(os.environ.get("BATCH_MAX", "500"))
BATCH_AGE = float(os.environ.get("BATCH_AGE_SEC", "5.0"))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],
)
log = logging.getLogger("wal2json-consumer")

_stop = False
def _on_signal(signum, frame):
    global _stop
    log.info("signal %s — stopping after current batch", signum)
    _stop = True
signal.signal(signal.SIGTERM, _on_signal)
signal.signal(signal.SIGINT, _on_signal)


@retry(stop=stop_after_attempt(8),
       wait=wait_exponential(multiplier=1, min=1, max=30),
       retry=retry_if_exception_type((requests.RequestException,)))
def ship(batch):
    r = requests.post(
        INGEST,
        headers={
            "Authorization": f"Bearer {TOKEN}",
            "Content-Type": "application/json",
            "X-Source": "postgres-wal2json",
        },
        data=json.dumps({"events": batch}),
        timeout=15,
    )
    r.raise_for_status()
    return r


def main():
    dsn = f"host={PG_HOST} port={PG_PORT} dbname={PG_DB} user={PG_USER} password={PG_PASS} sslmode=require"
    log.info("connecting to %s as %s, slot=%s", PG_HOST, PG_USER, SLOT)
    with psycopg.Connection.connect(
        dsn,
        autocommit=True,
        prepare_threshold=None,
        row_factory=psycopg.rows.tuple_row,
    ) as conn:
        cur = conn.cursor()
        # Start logical replication using the COPY-based wal2json protocol
        cur.execute(
            sql.SQL("START_REPLICATION SLOT {slot} LOGICAL 0/0 "
                    "(\"format-version\" '2', \"include-types\" 'true', "
                    "\"include-lsn\" 'true', \"include-timestamp\" 'true')")
            .format(slot=sql.Identifier(SLOT))
        )
        batch = []
        batch_started = time.time()
        last_lsn = None
        while not _stop:
            msg = cur.read_message()
            if msg is None:
                if batch and (time.time() - batch_started) > BATCH_AGE:
                    _flush(batch, last_lsn, cur)
                    batch.clear()
                    batch_started = time.time()
                continue
            payload = msg.payload
            try:
                obj = json.loads(payload)
            except ValueError:
                log.warning("non-JSON payload, skipping")
                cur.send_feedback(flush_lsn=msg.data_start)
                continue
            obj["_lsn"] = str(msg.data_start)
            obj["_received_at"] = datetime.utcnow().isoformat() + "Z"
            batch.append(obj)
            last_lsn = msg.data_start
            if len(batch) >= BATCH_MAX or (time.time() - batch_started) > BATCH_AGE:
                _flush(batch, last_lsn, cur)
                batch.clear()
                batch_started = time.time()


def _flush(batch, lsn, cur):
    if not batch:
        return
    log.info("shipping %d events, up to LSN %s", len(batch), lsn)
    ship(batch)
    cur.send_feedback(write_lsn=lsn, flush_lsn=lsn, apply_lsn=lsn, reply=True)


if __name__ == "__main__":
    main()
PY
chown wal2json:wal2json /opt/wal2json-consumer/consumer.py
chmod 750 /opt/wal2json-consumer/consumer.py

echo "==> Environment file"
cat > /etc/wal2json-consumer.env <<EOF
PG_HOST=${PG_HOST}
PG_PORT=${PG_PORT}
PG_DB=${PG_DB}
REPL_USER=${REPL_USER}
REPL_PASSWORD=${REPL_PASSWORD}
SLOT_NAME=${SLOT_NAME}
WAREHOUSE_INGEST_URL=${WAREHOUSE_INGEST_URL}
WAREHOUSE_TOKEN=${WAREHOUSE_TOKEN}
BATCH_MAX=500
BATCH_AGE_SEC=5
EOF
chmod 600 /etc/wal2json-consumer.env
chown root:wal2json /etc/wal2json-consumer.env

echo "==> systemd unit"
cat > /etc/systemd/system/wal2json-consumer.service <<'UNIT'
[Unit]
Description=wal2json -> warehouse consumer
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=wal2json
Group=wal2json
EnvironmentFile=/etc/wal2json-consumer.env
ExecStart=/opt/wal2json-consumer/venv/bin/python /opt/wal2json-consumer/consumer.py
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable --now wal2json-consumer

echo "==> Slot-lag metric exporter (node_exporter textfile)"
mkdir -p /var/lib/node_exporter/textfile
cat > /usr/local/bin/export-slot-lag.sh <<'METRIC'
#!/bin/bash
set -e
OUT=/var/lib/node_exporter/textfile/postgres_slot_lag.prom
TMP=$(mktemp)
echo "# HELP postgres_slot_lag_bytes Logical replication slot lag in bytes" >> "$TMP"
echo "# TYPE postgres_slot_lag_bytes gauge" >> "$TMP"
sudo -u postgres psql -tAF, -c "
SELECT slot_name, pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)
FROM pg_replication_slots WHERE slot_type='logical'" \
| while IFS=, read -r name bytes; do
    echo "postgres_slot_lag_bytes{slot=\"${name}\"} ${bytes}" >> "$TMP"
  done
mv "$TMP" "$OUT"
METRIC
chmod 755 /usr/local/bin/export-slot-lag.sh

cat > /etc/systemd/system/postgres-slot-lag.service <<'SLU'
[Unit]
Description=Export Postgres logical slot lag to textfile
[Service]
Type=oneshot
ExecStart=/usr/local/bin/export-slot-lag.sh
SLU

cat > /etc/systemd/system/postgres-slot-lag.timer <<'SLT'
[Unit]
Description=Run every 30s
[Timer]
OnBootSec=30
OnUnitActiveSec=30
[Install]
WantedBy=timers.target
SLT
systemctl daemon-reload
systemctl enable --now postgres-slot-lag.timer

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo "Slot:"
sudo -u postgres psql -tA -c "SELECT slot_name, plugin, active, restart_lsn FROM pg_replication_slots WHERE slot_name = '${SLOT_NAME}'"
echo
echo "Consumer service:"
systemctl is-active wal2json-consumer || true
echo
echo "Logs:    journalctl -u wal2json-consumer -f"
echo "Metric:  cat /var/lib/node_exporter/textfile/postgres_slot_lag.prom"

Make it executable and run:

chmod 700 /root/setup-wal2json-warehouse.sh
/root/setup-wal2json-warehouse.sh

The two operational concerns from day one: slot-lag alerting (alert on postgres_slot_lag_bytes > 50_000_000 and growing for 5 minutes) and slot-presence alerting (alert if the slot’s active column flips to f for more than 30 seconds — that means your consumer is gone and WAL is piling up). The warehouse loader is a stub HTTP POST in this script. In production you swap it for the ClickHouse / Snowflake / BigQuery client you actually use, and the schema on the warehouse side must upsert by primary key. Duplicate events from a consumer restart are expected and must be a no-op. If the warehouse loader is the slow link, raise BATCH_MAX and BATCH_AGE_SEC so you ship fewer, larger payloads.

For Postgres CDC operated under SLAs with slot-lag alerting wired into our on-call rotation, see Cloud PaaS and monitoring + on-call — or open a scoping ticket if your current setup has no slot-lag alerts at all.