Skip to content
TrendyolPublic

About

go-pq-cdc is lightweight and efficient Change Data Capture (CDC) system designed for PostgreSQL

Topics

Resources

Contributing

Stars

219 stars

Watchers

4 watching

Forks

Repository files navigation

go-pq-cdc Go Reference Go Report Card OpenSSF Scorecard

go-pq-cdc is designed to provide efficient and lightweight Change Data Capture (CDC) for PostgreSQL databases. The architecture leverages PostgreSQL's built-in logical replication capabilities to capture changes in the database and stream these changes to downstream systems, such as Kafka, Elasticsearch etc. The entire system is written in Golang, ensuring low resource consumption and high performance.

Debezium vs go-pq-cdc benchmark

Snapshot Feature

Capture existing data before starting CDC! The new snapshot feature enables initial data synchronization, ensuring downstream systems receive both historical and real-time data.

✨ Key Highlights:

  • Zero Data Loss: Consistent point-in-time snapshot using PostgreSQL's pg_export_snapshot()
  • Chunk-Based Processing: Memory-efficient processing of large tables
  • Smart Partitioning: Auto-selects optimal strategy (Integer Range, CTID Block, or Offset)
  • Multi-Instance Support: Parallel processing across multiple instances
  • Crash Recovery: Automatic resume from failures
  • No Duplicates: Seamless transition from snapshot to CDC
  • Snapshot Only Mode: One-time data export without CDC (no replication slot required)
  • Protocol Flexibility: pgoutput proto_version 1 and 2 support
  • Safe Streaming TX Handling: Streamed rollback transactions are discarded correctly

📚 Read Full Documentation for detailed architecture, configuration, and best practices. 📚 Protocol Version & Streaming Transactions for proto_version behavior and migration guidance.

Destination Routing

Route each change to the right Kafka topic or Elasticsearch index. Official sink connectors apply a static table mapping, then let your handler override the destination per row (for example by column value).

✨ Key Highlights:

  • Handler-driven: Set Topic on Kafka messages or IndexName on Elasticsearch actions in Go.
  • Safe fallback: Empty override uses tableTopicMapping / tableIndexMapping.
  • Official sinks: Supported in go-pq-cdc-kafka and go-pq-cdc-elasticsearch.

📚 Read Full Documentation for resolution order, examples, and limits.

Contents

Why?

CDC systems are crucial for real-time data synchronization, analytics, and event-driven architectures. Our main goal is to build a cdc base library for faster and stateful systems.

Official

3rd party

Usage

go get github.com/Trendyol/go-pq-cdc
package main

import (
	"context"
	cdc "github.com/Trendyol/go-pq-cdc"
	"github.com/Trendyol/go-pq-cdc/config"
	"github.com/Trendyol/go-pq-cdc/pq/message/format"
	"github.com/Trendyol/go-pq-cdc/pq/publication"
	"github.com/Trendyol/go-pq-cdc/pq/replication"
	"github.com/Trendyol/go-pq-cdc/pq/slot"
	"log/slog"
	"os"
)

func main() {
	ctx := context.Background()
	cfg := config.Config{
		Host:      "127.0.0.1",
		Username:  "cdc_user",
		Password:  "cdc_pass",
		Database:  "cdc_db",
		DebugMode: false,
		Publication: publication.Config{
			CreateIfNotExists: true,
			Name: "cdc_publication",
			Operations: publication.Operations{
				publication.OperationInsert,
				publication.OperationDelete,
				publication.OperationTruncate,
				publication.OperationUpdate,
			},
			Tables: publication.Tables{publication.Table{
				Name:            "users",
				ReplicaIdentity: publication.ReplicaIdentityFull,
			}},
		},
		Slot: slot.Config{
			Name:                        "cdc_slot",
			CreateIfNotExists:           true,
			SlotActivityCheckerInterval: 3000,
			ProtoVersion:                2,
		},
		Metric: config.MetricConfig{
			Port: 8081,
		},
		Logger: config.LoggerConfig{
			LogLevel: slog.LevelInfo,
		},
	}

	connector, err := cdc.NewConnector(ctx, cfg, Handler)
	if err != nil {
		slog.Error("new connector", "error", err)
		os.Exit(1)
	}

	defer connector.Close()
	connector.Start(ctx)
}

func Handler(ctx *replication.ListenerContext) {
	switch msg := ctx.Message.(type) {
	case *format.Insert:
		slog.Info("insert message received", "new", msg.Decoded)
	case *format.Delete:
		slog.Info("delete message received", "old", msg.OldDecoded)
	case *format.Update:
		slog.Info("update message received", "new", msg.NewDecoded, "old", msg.OldDecoded)
	case *format.Truncate:
		slog.Info("truncate message received", "relations", msg.RelationOIDs, "cascade", msg.Cascade, "restartIdentity", msg.RestartIdentity)
	case *format.LogicalDecodingMessage:
		slog.Info("logical message received", "prefix", msg.Prefix, "content", string(msg.Content), "lsn", msg.LSN)
	}

	if err := ctx.Ack(); err != nil {
		slog.Error("ack", "error", err)
	}
}

Examples

PostgreSQL User Permissions

go-pq-cdc connects to PostgreSQL with a regular role. For most deployments you do not need a superuser. A dedicated role with the right grants is enough. The exact privileges depend on which features you enable.

Minimum role for streaming CDC against a fixed table list:

CREATE ROLE cdc_user WITH LOGIN REPLICATION PASSWORD 'change_me';

GRANT USAGE ON SCHEMA public TO cdc_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO cdc_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT SELECT ON TABLES TO cdc_user;

Add these grants when the corresponding feature is enabled:

Feature Extra grants needed
publication.createIfNotExists: true GRANT CREATE ON DATABASE <db> TO cdc_user; so the publication can be created.
slot.createIfNotExists: true REPLICATION role attribute (already in the example above).
Heartbeat with auto-created table GRANT CREATE ON SCHEMA <schema> TO cdc_user; for the initial CREATE TABLE, plus GRANT INSERT, UPDATE ON <heartbeat_table> for the auto-managed singleton row.
Snapshot mode (initial / only) SELECT on the source tables (already covered above).
Adding tables to an existing publication The role must own the publication, e.g. ALTER PUBLICATION cdc_publication OWNER TO cdc_user;.
visibilityGuard (with or without replicas) No extra grant: pg_current_snapshot(), pg_last_wal_replay_lsn(), pg_control_recovery() and pg_control_system() are callable by every role. pg_hba.conf on each listed standby must accept a normal connection from the CDC host.

Common failure modes when grants are missing:

  • must be superuser or replication role to start walsender — role missing REPLICATION.
  • permission denied for schema <schema> — missing USAGE on the schema.
  • permission denied to create publication — missing CREATE on the database.
  • permission denied for table <heartbeat_table> — heartbeat enabled but the role cannot INSERT/UPDATE the singleton row.

pg_hba.conf must also allow replication connections from the CDC host, for example:

host replication cdc_user 10.0.0.0/8 scram-sha-256

Availability

The go-pq-cdc operates in passive/active modes for PostgreSQL change data capture (CDC). Here's how it ensures availability:

  • Active Mode: When the PostgreSQL replication slot (slot.name) is active, go-pq-cdc continuously monitors changes and streams them to downstream systems as configured.
  • Passive Mode: If the PostgreSQL replication slot becomes inactive (detected via slot.slotActivityCheckerInterval), go-pq-cdc automatically captures the slot again and resumes data capturing. Other deployments also monitor slot activity, and when detected as inactive, they initiate data capturing.

This setup ensures continuous data synchronization and minimal downtime in capturing database changes.

TOAST Handling

PostgreSQL does not send TOASTed column values during an update unless the TOASTed column itself is modified. For example, if only a small field changes, large columns such as TEXT, JSONB, or BYTEA are sent as TOAST placeholders instead of real values.

Unchanged TOASTed columns are restored from the old tuple only when it actually carries their values (see the paragraph below the snippet):

// Unchanged TOAST columns ('u') are filled from the old tuple only when it carries real values
// for them: 'O' (REPLICA IDENTITY FULL) or a key column. A 'K' tuple's non-key columns are 'n'
// placeholders, which must not be copied. Anything still 'u' is listed in UnchangedToastColumns.
for i, col := range msg.NewTupleData.Columns {
    if col.DataType != tuple.DataTypeToast || i >= len(rel.Columns) {
        continue
    }
    if msg.OldTupleData != nil && i < len(msg.OldTupleData.Columns) &&
        (msg.OldTupleType == format.UpdateTupleTypeOld || rel.Columns[i].Flags&1 == 1) {
        msg.NewTupleData.Columns[i] = msg.OldTupleData.Columns[i]
    }
    if msg.NewTupleData.Columns[i].DataType == tuple.DataTypeToast {
        msg.UnchangedToastColumns = append(msg.UnchangedToastColumns, rel.Columns[i].Name)
    }
}

Unchanged TOAST columns are restored from the old tuple only when it carries real values for them: a full old tuple (O, REPLICA IDENTITY FULL) or a key column. With REPLICA IDENTITY DEFAULT, a K old tuple holds n placeholders for non-key columns, which are never copied. Any unchanged TOAST column that cannot be restored is omitted from NewDecoded and listed by name in Update.UnchangedToastColumns, so a consumer can tell "not sent" apart from "set to NULL".

Heartbeat-based WAL Protection

Logical replication slots in PostgreSQL retain WAL segments until all consumers have confirmed they no longer need them. In low-traffic databases, this can cause WAL bloat when other databases on the same Postgres instance generate a lot of traffic while the CDC database itself remains mostly idle. In this situation the replication slot's restart_lsn and confirmed_flush_lsn may lag far behind pg_current_wal_lsn(), preventing WAL segments from being recycled.

Even without heartbeat, an idle slot advances: when nothing is in flight (no open transaction, nothing buffered, and every message delivered to the listener acked), go-pq-cdc confirms the WAL end position carried by the walsender's keepalive messages, the way PostgreSQL's own subscriber does. The integration suite covers this on PostgreSQL 15, 16 and 17. It only works if the listener acks every message it is given, including Relation, Truncate and logical decoding messages, not just inserts, updates and deletes: a listener that skips any of them, or acks only the last message of a batch, keeps the stream busy and the slot never advances this way. Heartbeat is still recommended for end-to-end liveness. It also works for listeners that skip Relation messages or ack only the last message of a batch, and on server versions where this has not been verified.

go-pq-cdc provides a table-based heartbeat mechanism for this scenario. When heartbeat.table.name is configured, the connector:

  • Creates the heartbeat table automatically (if missing).
  • Ensures a single row exists.
  • Periodically runs an internal UPDATE to generate small committed WAL records.
  • Auto-acknowledges heartbeat events internally. An Ack tells go-pq-cdc that its message and everything delivered before it is durable; a heartbeat advances the slot only when the most recently delivered message is covered that way (Relation messages need no ack of their own). A later Ack therefore releases earlier messages whether or not they were acked individually.
  • Does not forward heartbeat events to your listener.

Each heartbeat:

  • Produces a real transaction and COMMIT in the CDC database.
  • Is decoded and acknowledged by go-pq-cdc via the replication stream.
  • Advances the slot's confirmed_flush_lsn and, over time, restart_lsn under that condition, allowing PostgreSQL to safely recycle old WAL.

While your listener keeps acking, this makes WAL retention predictable even when application traffic on the CDC database is very low, while other databases on the same instance are generating heavy write load.

Heartbeat only cleans WAL when its writes flow through the replication slot.

The heartbeat table must satisfy both conditions below — otherwise the auto-UPDATEs commit successfully but the slot never decodes them, confirmed_flush_lsn stays frozen, and WAL keeps growing as if heartbeat were disabled:

  1. The heartbeat table is listed in publication.tables. If it is not part of the publication the change is filtered out before reaching the slot. The connector validates this at startup for selective publications and returns an error if the heartbeat table is missing.
  2. The heartbeat table has a REPLICA IDENTITY that allows the auto-UPDATE to be decoded — DEFAULT (the auto-created table already has a primary key, so this works out of the box) or FULL. REPLICA IDENTITY NOTHING will silently break WAL advancement because the UPDATE cannot be decoded by pgoutput.

Use a dedicated heartbeat table — never reuse a business table.

heartbeat:
  table:
    name: "my_heartbeat"
    schema: "public"
  interval: 100ms

Make sure the heartbeat table is included in the publication, for example:

Publication: publication.Config{
    Name:              "cdc_publication",
    CreateIfNotExists: true,
    Tables: publication.Tables{
        publication.Table{Name: "users"},
        publication.Table{Name: "my_heartbeat"}, // must be present
    },
},

Migration (breaking change)

Before:

heartbeat:
  enabled: true
  query: "INSERT INTO heartbeat_table(txt) VALUES ('hb')"
  interval: 5s

After:

heartbeat:
  table:
    name: "heartbeat_table"
    schema: "public"
  interval: 100ms

You can run Simple With Heartbeat example.

Upgrade: heartbeat table must be in publication

If you use heartbeat with a selective publication (publication.tables is non-empty and the publication is not FOR ALL TABLES), the connector now fails at startup when the heartbeat table is missing from publication.tables.

Previously, this misconfiguration could still start successfully, but heartbeat writes would not reach the replication slot and WAL retention would not improve.

Before upgrading, add the heartbeat table to your publication config (or switch to a FOR ALL TABLES publication):

publication:
  name: cdc_publication
  createIfNotExists: true
  tables:
    - name: users
      schema: public
    - name: my_heartbeat
      schema: public

Replica Identity Requirement

For this TOAST reconstruction to work, PostgreSQL must send the old tuple. This requires setting the table's replica identity to FULL:

ALTER TABLE your_table REPLICA IDENTITY FULL;

  • With REPLICA IDENTITY DEFAULT, PostgreSQL only sends primary keys for updates/deletes.
  • In that mode, old tuple values (including TOASTed fields) are not provided.
  • Therefore, FULL is required to correctly handle TOASTed columns in CDC.

For large tables, REPLICA IDENTITY USING INDEX can be a better trade-off for network traffic and matching performance:

  • FULL sends old values of all columns (O tuple data).
  • USING INDEX sends only old values of the columns from the selected unique index (K tuple data).
  • This reduces payload size, but unlike FULL, old non-index columns are not available.

You can run Replica Identity Using Index for a minimal USING INDEX setup.

REPLICA IDENTITY NOTHING is best paired with insert-only publications because PostgreSQL does not provide old-row data for updates and deletes in that mode.

You can run Replica Identity Nothing for an insert-only NOTHING example.

Configuration

Variable Type Required Default Description Options
host string yes - PostgreSQL host Should be a valid hostname or IP address. Example: localhost.
username string yes - PostgreSQL username Should have sufficient privileges to perform required database operations.
password string yes - PostgreSQL password Keep secure and avoid hardcoding in the source code.
database string yes - PostgreSQL database The database must exist and be accessible by the specified user.
debugMode bool no false For debugging purposes Enables pprof for trace.
metric.port int no 8080 Set API port Choose a port that is not in use by other applications.
logger.logLevel string no info Set logging level [DEBUG, WARN, INFO, ERROR]
logger.logger Logger no slog Set logger Can be customized with other logging frameworks if slog is not used.
publication.createIfNotExists bool no - Create publication if not exists. Otherwise, return publication is not exists error.
publication.name string yes - Set PostgreSQL publication name Should be unique within the database.
publication.operations []string yes - Set PostgreSQL publication operations. List of operations to track; all or a subset can be specified. INSERT: Track insert operations.
UPDATE: Track update operations.
DELETE: Track delete operations.
publication.tables []Table yes - Set tables which are tracked by data change capture Define multiple tables as needed.
publication.tables[i].name string yes - Set the data change captured table name Must be a valid table name in the specified database.
publication.tables[i].replicaIdentity string yes - Set the data change captured table replica identity [DEFAULT, FULL, NOTHING, USING INDEX] DEFAULT: Captures primary key old values.
FULL: Captures all old row columns.
NOTHING: Captures no old row data (typically insert-only scenarios; update/delete matching can fail).
USING INDEX: Captures old values from a chosen unique index.

Applied independently of createIfNotExists: if set, the connector runs ALTER TABLE ... REPLICA IDENTITY when the table's current identity differs (requires DDL privilege on the table).
publication.tables[i].replicaIdentityIndex string no* - Unique index name used when replicaIdentity is USING INDEX. Required only for USING INDEX, ignored otherwise.
publication.tables[i].schema string no public Set the data change captured table schema name Must be a valid table name in the specified database.
publication.tables[i].columns []string no - Only include these columns in replication and snapshotting Must not be set when replicaIdentity is FULL; only compatible with DEFAULT.
publication.tables[i].partitioned bool no false Flag for replicating a partitioned table via the root table name instead of listing out the individual table parts. Sets publish_via_partition_root = true when creating the publication. Only avaible with PostgreSQL 13+. This is a publication-wide setting, Setting any table with this will include it for all tables in the publication.
publication.tables[i].snapshotPartitionStrategy string no auto Override partition strategy for snapshot auto: Auto-detect best strategy (sparse integer PKs fall back to ctid_block). integer_range: Sequential integer PKs. ctid_block: String/UUID/hash/sparse PKs. offset: Slow fallback.
publication.tables[i].queryCondition string no - Per-table query condition for snapshot queries (SNAPSHOT-ONLY, does NOT affect CDC). Takes precedence over global snapshot.queryCondition. Example: "deleted_at IS NULL". Appended to WHERE clause with AND.
slot.createIfNotExists bool no - Create replication slot if not exists. Otherwise, return replication slot is not exists error.
slot.name string yes - Set the logical replication slot name Should be unique and descriptive. Quoted when sent to PostgreSQL.
slot.slotActivityCheckerInterval int no 1000 Set the slot activity check interval time in milliseconds Specify as an integer value in milliseconds (e.g., 1000 for 1 second).
slot.protoVersion int no 2 pgoutput protocol version used in START_REPLICATION 1: no streaming of in-progress transactions. Works on PostgreSQL 10+. 2: PostgreSQL 14+, streaming of in-progress transactions. messages is requested on PostgreSQL 14+ unless slot.logicalMessages is off.
slot.logicalMessages string no auto Logical decoding messages (pg_logical_emit_message), PostgreSQL 14+ auto: request the option when the server supports it. on: require it; startup fails on PostgreSQL 10-13. off: never request it, so no message is ever delivered. See Logical Decoding Messages.
slot.failover bool no false Create the slot with FAILOVER true (PostgreSQL 17+) so standbys running sync_replication_slots keep a synchronized copy; an existing slot is altered with ALTER_REPLICATION_SLOT … (FAILOVER true). Rejected with a clear error on older servers. Needs synchronized_standby_slots on the primary, see Failover slots.
statusUpdateInterval duration no 10s How often the standby acknowledges the primary with a standby status update while WAL is flowing back-to-back. Must stay well below the server's wal_sender_timeout (60s by default); not checked at startup. The 10s default matches wal_receiver_status_interval, the cadence Postgres expects from standbys. Set to 0 to disable the periodic update and reply only when PostgreSQL requests it.
snapshot.enabled bool no false Enable initial snapshot feature When enabled, captures existing data before starting CDC.
snapshot.mode string no never Snapshot mode: initial, never, or snapshot_only initial: Take snapshot only if no previous snapshot exists, then start CDC.
never: Skip snapshot, start CDC immediately.
snapshot_only: Take snapshot and exit (no CDC, no replication slot required).
snapshot.chunkSize int64 no 8000 Number of rows per chunk during snapshot Adjust based on table size. Larger chunks = fewer chunks but more memory per chunk.
snapshot.claimTimeout duration no 30s Timeout to reclaim stale chunks If a worker doesn't send heartbeat for this duration, chunk is reclaimed by another worker.
snapshot.heartbeatInterval duration no 5s Interval for worker heartbeat updates Workers send heartbeat every N seconds to indicate they're processing a chunk.
snapshot.instanceId string no auto Custom instance identifier (optional) Auto-generated as hostname-pid if not specified. Useful for tracking workers.
snapshot.tables []Table no* - Tables to snapshot (required for snapshot_only mode, optional for initial mode) snapshot_only: Must be specified here (independent from publication).
initial: If specified, must be a subset of publication tables. If not specified, all publication tables are snapshotted.
snapshot.queryCondition string no - Global query condition applied to all snapshot queries (SNAPSHOT-ONLY, does NOT affect CDC). Per-table queryCondition overrides this value. Example: "status = 'active'". Appended to WHERE clause with AND.
heartbeat.table.name string no - Name of the heartbeat table. Setting this enables heartbeat behavior. Table is auto-created if missing and should be included in publication.tables if you want it replicated.
heartbeat.table.schema string no public Schema of the heartbeat table. Defaults to public when omitted.
heartbeat.interval duration no 100ms Interval between heartbeat updates when heartbeat is configured. Must be greater than 0. Any valid Go duration string (e.g. 100ms, 1s, 5s, 1m).
extensionSupport.enableTimescaleDB bool no false Enable support for TimescaleDB hypertables. Ensures proper handling of compressed chunks during replication.
visibilityGuard.enabled bool no false Hold the first event of every transaction until the transaction is visible to new snapshots on the primary (closes the logical-decoding read-after-write window; see Visibility Guard). Opens one extra regular connection to the same host as the replication connection. Heartbeat events bypass the gate.
visibilityGuard.failMode string no closed What to do when a transaction is not visible within timeout closed: restart the stream; the event is redelivered from the confirmed LSN. open: log a warning, count it, dispatch anyway. Guard errors (replica, failover, connection loss) restart the stream in both modes.
visibilityGuard.timeout duration no 10s Maximum time to wait per transaction Must be less than half of the server's wal_sender_timeout (checked at startup, skipped when it is 0). That bound matters when statusUpdateInterval is 0: keepalive replies stop while the gate blocks.
visibilityGuard.pollInterval duration no 5ms First poll interval; doubles up to 250ms with jitter
visibilityGuard.replicas []string no [] Standbys (host:port) that must have applied the transaction before its first event is dispatched (see Visibility Guard). Requires enabled: true. Credentials and database come from the main config. Direct standby hosts only, never a pooled endpoint. Shares timeout and failMode with the primary check. Must cover every region or cluster consumers read from.
visibilityGuard.discovery.dns.names []string no - DNS names whose A and AAAA records are the standbys to gate, one name per region or cluster, for example replica.<scope>.service.services.<region>.<domain> (see Replica discovery). Requires enabled: true. Mutually exclusive with replicas and with the Go hook ResolveReplicas. At least one valid DNS name; no duplicates (case-insensitive, a trailing dot is ignored). An empty or failing answer fails the refresh.
visibilityGuard.discovery.dns.port int no port PostgreSQL port combined with every address (a DNS record carries none). Defaults to the main connection's port. 1-65535.
visibilityGuard.discovery.dns.nameserver string no - Literal ip:port of a DNS server (for example a Consul agent's DNS port, usually 8600). Every query goes to it over TCP. A host name is rejected. When unset the system resolver configuration is used and a warning is logged at startup.
visibilityGuard.discovery.dns.refreshInterval duration no 10s How long a discovered member list is trusted. A transaction is only released against a list younger than this; an older one is re-read first. Must be greater than 0. 0 takes the default.

API

Endpoint Description
GET /status Returns a 200 OK status if the client is able to ping the PostgreSQL server successfully.
GET /metrics Prometheus metric endpoint.
GET /debug/pprof/* (Only for debugMode=true) pprof

Protocol Version & Streaming Transactions

go-pq-cdc now supports both pgoutput protocol versions:

  • slot.protoVersion: 1

    • Starts replication with proto_version '1'
    • Does not request streaming 'true', so in-progress transactions are not streamed
    • On PostgreSQL 14 and newer, also requests messages 'true' unless slot.logicalMessages is off. PostgreSQL 10–13 do not receive that option, so those servers still start
  • slot.protoVersion: 2 (default)

    • Requires PostgreSQL 14+
    • Starts replication with proto_version '2' and streaming 'true', plus messages 'true' unless slot.logicalMessages is off
    • Supports streamed in-progress transactions (STREAM START/STOP/COMMIT/ABORT)

Streaming behavior for proto_version: 2:

  • Streamed DML events are buffered per transaction XID.
  • Events are emitted only on STREAM COMMIT.
  • STREAM ABORT discards all buffered events for that transaction.
  • This prevents rolled-back streamed transactions from leaking to consumers.

Logical Decoding Messages

pg_logical_emit_message writes a logical decoding message into the WAL, which pgoutput forwards as an M record. go-pq-cdc decodes it into *format.LogicalDecodingMessage and delivers it to the handler like any row change:

Field Meaning
Prefix the routing key given to pg_logical_emit_message
Content the payload bytes, unmodified
LSN the WAL position of the message itself, not a commit LSN

A message emitted inside a transaction arrives with that transaction at COMMIT, in row order, with ctx.Xid and ctx.CommitLSN set as they are for row changes. A message emitted outside a transaction arrives immediately and belongs to no transaction: ctx.Xid and ctx.CommitLSN are both 0.

A message that arrives while a streamed transaction is in flight is delivered immediately but cannot be acknowledged until that transaction resolves. Confirming the message's own position would promise the server that the transaction's earlier rows — still held in memory, not yet delivered — had been handled, and the server acts on that promise by refusing to resend them. The transaction's own end-of-transaction acknowledgement covers the message instead, so a message may be delivered twice if the process stops in the meantime. It is never skipped.

Messages require PostgreSQL 14+. slot.logicalMessages defaults to auto, which requests them whenever the server supports the option; off never requests them, which is the only way to guarantee a handler never receives one; on requires them, so a PostgreSQL 10–13 server fails startup instead of omitting the option silently.

Visibility Guard

Mechanism. The logical walsender streams a transaction as soon as its commit record is flushed to WAL. The rows become visible to new snapshots only later, when the committing backend finishes (ProcArrayEndTransaction), and with synchronous_standby_names set (Patroni synchronous_mode) that step first waits for the synchronous standby's acknowledgement. A consumer that receives the event and immediately reads the primary can therefore miss the row (read-after-write); the same ordering allows a "phantom" event if the primary dies before the standby received the commit. visibilityGuard closes this window: before dispatching the first event of every transaction it polls a regular connection on the same host until the transaction's xid is no longer in progress in pg_current_snapshot() (txid_current_snapshot() before PostgreSQL 13). Later events of the same transaction pass without a wait; heartbeat events bypass the gate.

visibilityGuard:
  enabled: true
  failMode: closed   # closed | open
  timeout: 10s       # must be < wal_sender_timeout / 2 unless statusUpdateInterval is set; covers the primary and every replica below
  pollInterval: 5ms  # doubles up to 250ms, with jitter
  replicas:          # optional: standbys that must have applied the transaction before dispatch
    - standby1:5432
    - standby2:5432

Replicas. replicas extends the gate to standbys. On every connection (at startup and after each reconnect) the listed host must belong to the replication session's cluster (pg_control_system(), compared with IDENTIFY_SYSTEM): a standby of another cluster is in recovery and answers with a replay position from a history CommitLSN is not part of, which would pass the check at once. After the primary check, the first event of every transaction is then held until each listed standby answers, on a connection of its own, pg_is_in_recovery() true, pg_last_wal_replay_lsn() > CommitLSN (strict, see below) and a timeline no newer than the replication session's. An event whose transaction has no decoded BEGIN (no xid, no CommitLSN) is never dispatched: the guard fails closed on it. Credentials and database come from the main config. List direct standby hosts, never a pooled or load-balanced endpoint: the check is only meaningful for the server that answered it. Both waits share timeout, standbys are polled concurrently, and the replica connections reconnect on their own (a standby shutting down answers 57P01 before closing; that is redialed like a reset), so a standby restart does not restart the stream. Every pass is logged (replica guard wait completed, Debug; replica guard slow wait completed, Info from 100 ms) with the xid, CommitLSN, and per replica the backend address and the replay position it certified. A poll that passed on a replica certifies every lower CommitLSN for the next second without another query (logged as cached_age_ms), so a busy stream costs about one poll per replica per second instead of one per transaction; a replica that is behind is still polled on every transaction until it passes. Design record: docs/replica-guard-design.md.

Replica discovery (DNS)

A static replicas list has to be edited by hand whenever a standby is added, removed or promoted. visibilityGuard.discovery.dns reads the standbys from DNS names instead: one name per region or cluster whose A and AAAA records are the standbys your service registry reports as healthy, for example the Consul name replica.<scope>.service.services.<region>.<domain>. The guard looks every name up on each refresh and gates the addresses it gets, on port (default: the main connection's port).

visibilityGuard:
  enabled: true
  discovery:
    dns:
      refreshInterval: 10s          # default; how long a member list is trusted before the next gated transaction re-reads it
      port: 5432                    # default: the main connection's port
      nameserver: 10.0.0.1:8600     # optional literal ip:port, queried over TCP; see below
      names:
        - replica.scope.service.services.region-a.example.internal
        - replica.scope.service.services.region-b.example.internal

Lookup. Per name the guard makes three lookups with the pure-Go resolver, always for the absolute name (a trailing dot is added), so a resolver search list can never answer for it: A records (ip4), AAAA records (ip6), and an unfiltered cross-check (ip). A lookup error other than "no such name / no data" fails the name. The one exception is an AAAA lookup whose records were all IPv4-mapped (the resolver reports "no suitable address found"); the cross-check covers those. An address the cross-check returns that the family lookups do not explain fails the name, and so does a cross-check that finds nothing while a family returned records. One family being absent is fine only when the other returned records. Names are looked up concurrently inside the guard's one-second bound for a resolver call. An address repeated inside one answer counts once.

Failure handling. An empty answer is a failure, never "zero replicas": a name that lists nobody cannot be told apart from a registry that lost its entries. The price is that a region with no passing standby stops the stream under failMode: closed. A failure of any name fails the whole refresh (the set is never partial), and the same host:port under two names is an error rather than a merge. A failing refresh is retried on the next gated transaction and counts against timeout; when it expires, the transaction follows failMode, as for a standby that is behind. A configuration that fails validation, or a name that cannot be resolved at startup, fails the connector start.

Nameserver. With nameserver set, every query goes to that address over TCP. Point it at a Consul agent's DNS port to remove any forwarder from the path. Without it the system resolver configuration is used, and the guard logs one warning at startup: Consul cuts a UDP answer to udp_answer_limit (3) records when the querier does not use EDNS, which a forwarder in between may do, and it does so silently, so a standby can be missing from the set. Set nameserver, or confirm that your resolver path returns complete answers.

Go hook. Authentication, timelines and sources other than DNS are not part of the block. Set VisibilityGuardConfig.ResolveReplicas in Go instead; it is mutually exclusive with the block and with replicas. Its contract is documented on the field in config/config.go: return an error unless the cluster was reached and identified; a non-nil empty slice means "proved, zero replicas", while a nil slice is an invalid answer and is rejected.

Discovery limits. The guarantee above holds for the members the guard gates. Discovery adds these residuals:

  • Timelines are unknown. DNS carries no timeline, so every member is polled without the timeline rule. The guarantee is conditional: it holds only if your routing never sends reads to a standby that sits on an orphaned history after a crash failover (a standby that received WAL the new primary never had). A static list has the same gap; a Go hook that supplies timelines narrows it.
  • Promotion. A standby promoted while the name still lists it answers "not in recovery", the re-resolve still lists it, the error is fatal and the stream restarts, again and again until the name stops listing the node: typically about one health-check interval. There is no hard bound if the health publisher stalls or DNS is stale, and an orchestrator's restart backoff (for example CrashLoopBackOff) can stretch a few seconds of DNS lag into a minute of downtime.
  • Answer freshness. Consul serving stale reads (max_stale), forwarder caches and minimum-TTL floors bound how fresh an answer is. A standby that was added or removed is picked up only after the health-check interval plus up to refreshInterval, plus those caches.
  • Complete answers. Without nameserver, a forwarder that drops EDNS makes Consul cut the answer to 3 records silently (see above). Entries in /etc/hosts override DNS for the names they match. The standard library resolver is also trusted for message integrity: it accepts a TCP answer that still carries the truncation flag and can return the records parsed before a malformed tail, so a damaged answer can lack a standby without an error; the upgrade path is a message-level DNS client that rejects truncated or partially parsed answers.
  • Warning-state instances are returned by Consul unless only_passing is set on the DNS configuration, so a standby whose health check is only warning stays in the set (and is gated).
  • Liveness. With discovery configured, DNS (and the registry behind it) becomes a liveness dependency of the stream: once the set is older than refreshInterval and a refresh has not succeeded, dispatch is held and then follows failMode.
  • Coverage is an operator contract. List one name per region or cluster your consumers read from; safety needs every routed standby to be gated. A standby_leader of a standby cluster is not under replica.: list its own name if anything routes reads to it. The library does not verify coverage. A static replicas list must cover every region or cluster consumers read from in the same way.

Design record: docs/replica-guard-design.md.

Guarantee. Everything delivered to the handler is committed on the server (with or without the guard). With the guard on, a fresh snapshot taken on the same primary after the handler was called also sees the row. With replicas set, every listed standby has applied the transaction when the handler is called, so a read on any of them under READ COMMITTED sees the row. One exception is built into hot standby: a standby that restarts replays again from its last restartpoint and accepts connections as soon as it is consistent, so for a moment its replay position can sit below a CommitLSN it had already applied. Because a passing poll is reused for up to one second, a transaction dispatched in that second can be certified by an observation made just before such a restart; the same consumer-side retry covers both.

Limits. The guarantee does not cover:

  • Reads from a standby that is not listed in replicas, or through a pooler that may route to one. Use the strict CommitLSN rule or WaitReplayed in Commit LSN and reading from a standby. In Patroni deployments this is the more likely cause of "the row is not there yet" than the primary-side window. A standby added to the cluster later is not covered until it is added to replicas. A listed standby that is promoted keeps the connector from starting (it is no longer in recovery) until replicas is updated or the node is rebuilt as a standby, so list standbys only where their addresses are stable.
  • The consumer's own open REPEATABLE READ or SERIALIZABLE transaction: its snapshot predates the commit.
  • Later changes: the row may already be updated or deleted when the consumer reads it.
  • Row-level security and the privileges of the reading role.

Consumer-side retry and self-contained outbox payloads remain the recommended pattern; the guard removes the common case, not the need for them.

Failure handling. failMode: closed (default): a timeout or any guard error (server in recovery, timeline changed, connection lost) restarts the stream with the error class visibility guard unreachable; the held event is not acked and is redelivered from the confirmed LSN. failMode: open: after timeout the event is dispatched with a warning and go_pq_cdc_visibility_fail_open_total is incremented; guard errors still restart the stream. timeout must stay below half of the server's wal_sender_timeout (checked at startup, skipped when it is 0) because keepalive replies stop while the gate blocks when statusUpdateInterval is disabled. Waits are recorded in go_pq_cdc_visibility_wait_duration_seconds, timeouts in go_pq_cdc_visibility_timeout_total.

With replicas, a standby that is unreachable or still behind when timeout expires counts as a timeout and follows the same failMode rules. A chronically lagging standby therefore keeps the stream in a restart loop under closed, by design: raise timeout together with wal_sender_timeout, or use open with an alert on the timeout counter. A listed server that is not in recovery (a primary, a promoted standby, a pooler that routed elsewhere), one whose timeline is ahead of the replication session, or a server error on the poll is a guard error in both modes. Each standby's distance to the held transaction is exported as go_pq_cdc_visibility_replica_lag_bytes{replica}; go_pq_cdc_visibility_replica_checks_total{replica,result} counts certified transactions by result="cached" or "polled", so the cache hit ratio shows whether a busy stream is still paying one round trip per transaction.

Synchronous replication corollary. With synchronous_standby_names set, a transaction becomes visible on the primary only after the synchronous standby acknowledged it at the configured synchronous_commit level. A fail-closed guard therefore also prevents phantom events on a Patroni failover, without PostgreSQL 17 failover slots: an event is dispatched only once the standby that may be promoted has the commit. The same corollary is what closes the one race the replica check cannot see, a standby that is still receiving a new timeline and reports the old one; this is why replicas requires the primary guard. This holds unless:

  • Patroni runs synchronous_mode without synchronous_mode_strict and no standby is available: synchronous replication is switched off and commits stop waiting.
  • The committing backend is cancelled or terminated while waiting for the standby: it commits locally and becomes visible without the acknowledgement (the server logs a WARNING).
  • The session used synchronous_commit = local or off.
  • synchronous_commit = remote_write: the standby received the WAL but has not flushed it.

Commit LSN and reading from a standby

Every CDC event exposes ctx.Xid, the top-level transaction that produced it, and ctx.CommitLSN, the WAL position of the commit record of that transaction (pgoutput Begin.FinalLSN, or StreamCommit.CommitLSN for streamed transactions). Snapshot events carry 0.

visibilityGuard only describes the primary. A consumer that reads from a standby, or through a pooler that may route to one, has to wait until the standby has replayed that commit record. The rule is strict:

SELECT pg_last_wal_replay_lsn() > '<ctx.CommitLSN>'::pg_lsn;

pg_last_wal_replay_lsn() reports the end of the last replayed record, so it equals CommitLSN right before the commit record itself is applied; >= is not enough. ctx.CommitLSN.String() prints the pg_lsn text form (X/X). The check is only as good as the way it is run:

  • Run the check and the read on the same server: the same connection, one transaction, or a pool pinned to one standby. A replica endpoint that spreads connections over several standbys (HAProxy, pgbouncer with several hosts, a DNS name with several addresses, a pool in the application) can pass the check on one standby and read from another.
  • Check first, then read, as separate statements under READ COMMITTED. REPEATABLE READ keeps the snapshot of the first statement, and a single combined statement (… WHERE id = $1 AND pg_last_wal_replay_lsn() > $2) takes its snapshot before the function is evaluated.
  • NULL from pg_last_wal_replay_lsn() means the connection reached a primary (or a promoted standby), not "already applied". After a failover the new timeline can pass the old CommitLSN without containing that transaction.
  • synchronous_commit = on means flushed, not applied: a synchronous standby can still be behind on apply. Only remote_apply on the producer, with the standby you read from listed in synchronous_standby_names, removes the need for the check.

PostgreSQL 17 and 18 have no server-side wait for a replay position (pg_wal_replay_wait is not in either release), so poll. replication.WaitReplayed runs that poll for you, with the guard's defaults (10s timeout, 5ms interval doubling to 250ms), on any *pgx.Conn, *pgxpool.Conn or pgx.Tx; pass the connection you will read from:

conn, err := standbyPool.Acquire(ctx) // the connection the read will use
defer conn.Release()
if err = replication.WaitReplayed(ctx, conn, lCtx.CommitLSN, replication.WaitOptions{}); err != nil {
    return err // replication.ErrNotStandby, replication.ErrVisibilityTimeout, or a connection error
}
err = conn.QueryRow(ctx, "SELECT ... FROM orders WHERE id = $1", id).Scan(...) // separate statement

To have the library wait instead, list the standby in visibilityGuard.replicas. example/replica-read demonstrates each point against a primary with two synchronous standbys.

Failover slots (PostgreSQL 17+)

slot.failover: true creates the replication slot with FAILOVER true, or issues ALTER_REPLICATION_SLOT … (FAILOVER true) for an existing slot, so a standby running sync_replication_slots keeps a synchronized copy and the slot survives a failover without WAL loss. Servers older than 17 reject the option with a clear error. Required setup:

  • Primary: synchronized_standby_slots = 'standby_physical_slot'. The logical walsender then waits for the listed physical slots before sending a change, so no event is delivered ahead of the standby that may become the next primary. With the parameter empty there is no waiting: the synchronized slot can lag behind what consumers have already seen, and those events are redelivered after failover.
  • Standby: sync_replication_slots = on, hot_standby_feedback = on, primary_slot_name set, and dbname in primary_conninfo.
  • An inactive slot listed in synchronized_standby_slots stalls the logical walsender; remove it from the list before taking that standby down for good.
  • Patroni 4.1.0+ leaves failover = true slots alone (no copy, no pg_replication_slot_advance) but does not set synchronized_standby_slots; set it through postgresql.parameters.
  • If the slot is active for another process when go-pq-cdc starts (rolling deployment), the ALTER is skipped with a warning and retried on the next start.

Complementary to visibilityGuard: the guard closes the read-after-write window on the primary, the failover slot keeps the consumer position across a promotion.

Exposed Metrics

The client collects relevant metrics related to PostgreSQL change data capture (CDC) and makes them available at the /metrics endpoint.

Metric Name Description Labels Value Type
go_pq_cdc_update_total The total number of UPDATE operations captured on specific tables. slot_name, host Counter
go_pq_cdc_delete_total The total number of DELETE operations captured on specific tables. slot_name, host Counter
go_pq_cdc_insert_total The total number of INSERT operations captured on specific tables. slot_name, host Counter
go_pq_cdc_logical_message_total The total number of logical decoding messages delivered to the handler. slot_name, host Counter
go_pq_cdc_cdc_latency_current The current latency in capturing data changes from PostgreSQL, in nanoseconds. slot_name, host Gauge
go_pq_cdc_cdc_latency_current_milliseconds The current latency in capturing data changes from PostgreSQL, in milliseconds. slot_name, host Gauge
go_pq_cdc_process_latency_current The current latency in processing the captured data changes, in nanoseconds. slot_name, host Gauge
go_pq_cdc_process_latency_current_milliseconds The current latency in processing the captured data changes, in milliseconds. slot_name, host Gauge
go_pq_cdc_message_buffer_length Messages queued in the stream's internal channel, read at scrape time, out of a capacity of 1000. Near 1000 means the consumer cannot keep up; near 0 while slot lag grows means the upstream is the bottleneck. slot_name, host Gauge
go_pq_cdc_replication_slot_slot_confirmed_flush_lsn The last confirmed flush Log Sequence Number (LSN) in the PostgreSQL replication slot. slot_name, host Gauge
go_pq_cdc_replication_slot_slot_current_lsn The current Log Sequence Number (LSN) being processed in the PostgreSQL replication slot. slot_name, host Gauge
go_pq_cdc_replication_slot_slot_is_active Indicates whether the PostgreSQL replication slot is currently active (1 for active, 0 for inactive). slot_name, host Gauge
go_pq_cdc_replication_slot_slot_lag The replication lag measured by the difference between the current LSN and the confirmed flush LSN. slot_name, host Gauge
go_pq_cdc_replication_slot_slot_retained_wal_size The size of Write-Ahead Logging (WAL) files retained for the replication slot in bytes. slot_name, host Gauge
go_pq_cdc_snapshot_in_progress Indicates whether snapshot is currently in progress (1 for active, 0 for inactive). slot_name, host Gauge
go_pq_cdc_snapshot_total_tables Total number of tables to snapshot. slot_name, host Gauge
go_pq_cdc_snapshot_total_chunks Total number of chunks to process across all tables. slot_name, host Gauge
go_pq_cdc_snapshot_completed_chunks Number of chunks completed in snapshot. slot_name, host Gauge
go_pq_cdc_snapshot_total_rows Total number of rows read during snapshot. slot_name, host Counter
go_pq_cdc_snapshot_duration_seconds Duration of the last snapshot operation in seconds. slot_name, host Gauge
go_pq_cdc_visibility_wait_duration_seconds Time the visibility guard held a transaction until it became visible on the primary. slot_name, host Histogram
go_pq_cdc_visibility_timeout_total Number of visibility guard waits that reached visibilityGuard.timeout. slot_name, host Counter
go_pq_cdc_visibility_fail_open_total Number of transactions dispatched after a visibility guard timeout (failMode: open). slot_name, host Counter
go_pq_cdc_visibility_replica_lag_bytes WAL bytes a listed standby still has to replay before the held transaction is applied (0 once applied). slot_name, host, replica Gauge
go_pq_cdc_visibility_replica_checks_total Transactions certified per standby: cached (a poll under 1 s old already passed the commit) or polled. slot_name, host, replica, result Counter
runtime metrics Prometheus Collector N/A N/A

Grafana Dashboard

Import the grafana dashboard json file. Dashboard

Compatibility

go-pq-cdc Version slot.protoVersion Minimum PostgreSQL Server Version Notes
0.0.2 or higher 1 10 No streaming transaction protocol messages
0.0.2 or higher 2 14 Supports streamed in-progress transactions

Breaking Changes

Date taking effect Version Change How to check
Next release TBD Startup fails when heartbeat is enabled but the heartbeat table is missing from a selective publication. Ensure publication.tables includes your heartbeat table, or use a FOR ALL TABLES publication. See Upgrade: heartbeat table must be in publication.

About

go-pq-cdc is lightweight and efficient Change Data Capture (CDC) system designed for PostgreSQL

Topics

Resources

Contributing

Stars

219 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages