Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

go-pq-cdc

> 数据库
Open source

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

195 stars0 likes0 views
WebsiteGitHub

About

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

go-pq-cdc

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.

Contents

  • go-pq-cdc
    • Snapshot Feature
      • Contents
      • Why?
      • Usage
      • Examples
      • PostgreSQL User Permissions
      • Availability
      • TOAST Handling
      • Heartbeat-based WAL Protection
        • Replica Identity Requirement
      • Configuration
      • Protocol Version & Streaming Transactions
      • API
      • Visibility Guard
      • Commit LSN and reading from a standby
      • Failover slots (PostgreSQL 17+)
      • Exposed Metrics
      • Grafana Dashboard
      • Compatibility
      • Breaking Changes

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

  • Postgresql to Elasticsearch Connector
  • Postgresql to Kafka Connector

3rd party

  • Postgresql to RabbitMQ Connector

Usage

bash
go get github.com/Trendyol/go-pq-cdc
…

Examples

  • Simple
  • Simple File Config
  • Simple With Heartbeat
  • Streaming Transactions
  • Snapshot Mode (Initial Data Capture)
  • Snapshot Only Mode (One-Time Export)
  • Snapshot with Query Condition
  • Replica Identity Using Index
  • Replica Identity Nothing
  • PostgreSQL to Elasticsearch
  • PostgreSQL to Kafka
  • PostgreSQL to PostgreSQL
  • Partitioned Tables

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:

sql
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 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 TO cdc_user; for the initial CREATE TABLE, plus GRANT INSERT, UPDATE ON 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;.

Common failure modes when grants are missing:

  • must be superuser or replication role to start walsender — role missing REPLICATION.
  • permission denied for schema — missing USAGE on the schema.
  • permission denied to create publication — missing CREATE on the database.
  • permission denied for 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.

To guarantee that UPDATE messages include full, correct data, go-pq-cdc automatically merges old and new tuples, restoring any missing TOASTed fields:

go
if m.OldTupleData != nil {
    for i, col := range m.NewTupleData.Columns {
        // Toasted columns are not sent unless the column itself changed
        if col.DataType == tuple.DataTypeToast {
            m.NewTupleData.Columns[i] = m.OldTupleData.Columns[i]
        }
    }
}

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.

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.
  • 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, allowing PostgreSQL to safely recycle old WAL.

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.

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

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

go
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:

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

After:

yaml
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):

yaml
publication:
  name: cdc_publication
  createIfNotExists: true
  tables:
    - name:

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gocdcgogolangpostgresql

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库