Skip to content

wal2json CDC pipelines from PostgreSQL

Run change data capture from PostgreSQL using the wal2json logical decoding plugin — output format, replication slots, consumer choices, and operational care.

wal2json is a logical-decoding output plugin for PostgreSQL that emits row changes as JSON. Combined with a replication slot and a downstream consumer (Kafka Connect, a Python script, Debezium, a custom Go service), it turns a Postgres database into a live event stream — every insert, update, and delete arrives as a JSON message with the before/after row and metadata. This article covers the setup, the consumer choices, and the operational care a CDC pipeline needs. For an alternative path on selected tables, see logical replication.

How to verify

Confirm wal2json is installed and the replication slot is healthy:

sudo apt list --installed 2>/dev/null | grep wal2json
psql -c "SHOW wal_level;"             # must be 'logical'
psql -c "SELECT * FROM pg_replication_slots WHERE plugin='wal2json';"
psql -c "SELECT slot_name,
                pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn))
                AS slot_lag
         FROM pg_replication_slots
         WHERE plugin='wal2json';"

slot_lag is the metric — if it grows unbounded, your consumer is behind or the slot is orphaned.

What’s happening

PostgreSQL’s WAL records every change. Logical decoding plugins turn that physical record into a logical message: “row X in table Y was updated from A to B.” wal2json is one such plugin (alongside pgoutput, the native plugin used by logical replication, and protobuf/avro variants). It produces JSON output that’s easy to consume from any language.

The flow: your consumer opens a replication connection (the special replication protocol, not regular SQL), creates or reuses a logical replication slot bound to wal2json, then receives a stream of JSON messages with xid (transaction id), lsn (log sequence number), and a list of changes. The consumer reports back flushed_lsn — the LSN it has durably stored. Postgres advances confirmed_flush_lsn and can recycle WAL up to restart_lsn.

Slots are durable. A consumer that dies and restarts picks up where it left off — exactly-once delivery is on the consumer’s responsibility (idempotent writes, dedup by xid/lsn), but no message is lost. The cost: an orphan slot pins WAL retention. Set max_slot_wal_keep_size so a runaway slot can’t fill the disk.

The procedure

  1. Install wal2json and prepare the server:

    sudo apt install postgresql-16-wal2json
    ALTER SYSTEM SET wal_level = 'logical';
    ALTER SYSTEM SET max_replication_slots = 20;
    ALTER SYSTEM SET max_wal_senders = 20;
    ALTER SYSTEM SET max_slot_wal_keep_size = '32GB';

    Restart Postgres.

  2. Create the replication role and slot:

    CREATE ROLE cdc_user WITH REPLICATION LOGIN PASSWORD 'use-pgpass';
    SELECT pg_create_logical_replication_slot('cdc_main', 'wal2json');

    pg_hba.conf needs an entry for the replication connection:

    host  replication  cdc_user  10.0.0.0/8  scram-sha-256
  3. Tail with pg_recvlogical for a quick test:

    pg_recvlogical -d app -U cdc_user --slot cdc_main --start \
      -o format-version=2 \
      -o include-types=true \
      -o include-pk=true \
      -f -

    format-version=2 produces a per-transaction JSON object. include-pk=true adds the primary key for each row — necessary for downstream UPSERT logic.

  4. Build a real consumer. Most production deployments use Debezium (for Kafka Connect) or a custom service. A minimal Python consumer using psycopg:

    import psycopg
    with psycopg.connect("dbname=app user=cdc_user replication=database",
                          autocommit=True) as conn:
        cur = conn.cursor()
        cur.start_replication(
            slot_name='cdc_main',
            decode=False,
            options={'format-version': '2',
                     'include-pk': 'true',
                     'include-types': 'true'})
        for msg in cur:
            process(msg.payload)         # your sink: Kafka, S3, warehouse
            msg.cursor.send_feedback(flush_lsn=msg.data_start)

    The send_feedback(flush_lsn=...) call is critical — without it, the slot never advances.

  5. Filter at the source. wal2json supports include/exclude filters:

    pg_recvlogical ... \
      -o add-tables='public.orders,public.customers' \
      -o filter-tables='public.audit_log'

    Filtering at the plugin level is much cheaper than dropping records downstream.

  6. Monitor slot lag and consumer health.

    SELECT slot_name,
           pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) AS lag_bytes,
           active
    FROM pg_replication_slots;

    Alert when lag_bytes grows past your threshold (1 GB is a reasonable starting point for a normal-volume database) or when active = false for more than a few minutes.

Common pitfalls

  • An idle or crashed consumer holds the slot — WAL retention grows. max_slot_wal_keep_size is the safety net; alert before it fires.
  • Logical decoding can’t follow DDL — schema changes break consumers. Coordinate schema deploys with consumer code, or use a schema registry.
  • Large transactions buffer in decoder memory until commit; very large COPY operations can blow up the decoder. Use streaming = 'on' (PG 14+) or break loads into smaller transactions.
  • wal2json format-version=1 produces a single message per transaction with all changes — easier to parse, but huge transactions become huge messages. format-version=2 streams per-change messages.
  • Schema drift between source and consumer is silent — the JSON simply changes shape. Validate schema on the consumer side.

In the engagements we run, wal2json + a custom Go or Python consumer is the lightweight CDC option when we don’t need the operational footprint of Kafka Connect or Debezium. We monitor slot lag and consumer health as first-class signals, cap WAL retention with max_slot_wal_keep_size, and pair the pipeline with idempotent sinks. For the operating model behind a Postgres-driven event stream, see managed operations.