Ecstaticloud
Initializing0%
Ecstaticloud Logo
Back to all insights
Software ArchitectureNovember 29, 2026• 8 min read

Scaling Postgres CDC Pipelines with Debezium and Kafka

Eliminate WAL bloat and replication lag in high-throughput Postgres CDC pipelines using Debezium and Kafka to achieve sub-100ms event delivery.

Quick Overview

Scaling Postgres CDC pipelines with Debezium and Kafka requires optimizing Write-Ahead Log (WAL) consumption, tuning logical decoding buffers, and managing Kafka Connect partitioning. By tuning max.queue.size, leveraging the native pgoutput plugin, enabling parallel incremental snapshots, and setting non-blocking backpressure strategies, architectures scale past 50,000 events/sec while eliminating Postgres WAL bloat and replication lag.


Real-World Bottlenecks: Postgres WAL Bloat & Kafka Lag

Implementing a Change Data Capture (CDC) architecture at scale exposes a fundamental friction point between relational database storage engines and distributed streaming log semantics. PostgreSQL writes all data modifications to the Write-Ahead Log (WAL) sequentially before committing them to data pages. When using Debezium to stream these changes to Apache Kafka, the pipeline relies on PostgreSQL logical decoding slots.

Under heavy write workloads (e.g., >15,000 write operations per second), three distinct architectural failures occur:

+-----------------------------------------------------------------------------------+
|                            THE WAL BLOAT CASCADING FAILURE                        |
|                                                                                   |
|  [ Primary OLTP Writes ]                                                          |
|           │                                                                       |
|           ▼                                                                       |
|   ┌───────────────┐      Replication Slot Stopped      ┌──────────────────────┐   |
|   │ Postgres WAL  │ ─────────────────────────────────X │  Debezium Connector  │   |
|   └───────────────┘  (LSN Acknowledgment Stalled)      └──────────────────────┘   |
|           │                                                       │               |
|           │ Disk Retains Unacked Segments                         │ Backpressure  |
|           ▼                                                       ▼               |
|   [ Disk Space Explodes ]                                  [ Kafka Producer Lag ] |
|           │                                                                       |
|           ▼                                                                       |
|   [ Postgres Crash / Read-Only Mode ]                                             |
+-----------------------------------------------------------------------------------+

1. PostgreSQL Unbounded WAL Accumulation (WAL Bloat)

A PostgreSQL logical replication slot tracks the current Log Sequence Number (LSN) processed by the consumer (Debezium). If the Debezium task stalls—due to GC pauses, rebalances, target Kafka topic throttling, or network saturation—the replication slot stops advancing its confirmed LSN.

Because PostgreSQL cannot discard WAL segments containing unacknowledged changes, the pg_wal directory accumulates data indefinitely. Left unmanaged, this manifests as extreme WAL bloat, rapidly exhausting disk space and dropping the primary database into read-only mode or causing a catastrophic hard crash.

2. Single-Threaded Logical Decoding Bottlenecks

PostgreSQL processes logical decoding sequentially per replication slot. A single WAL sender process decodes WAL record streams using the decoding plugin (such as pgoutput).

If a transaction contains massive batch writes (e.g., an UPDATE touching 500,000 rows), pgoutput must stream these changes sequentially. If the memory buffer allocated for logical decoding (logical_decoding_work_mem) is under-provisioned, PostgreSQL spills decoded changes to disk on the primary database, increasing local disk I/O contention and introducing severe postgres replication lag kafka metrics.

3. Backpressure Inversion and Kafka Connect GC Pressure

Debezium reads events from the database engine and buffers them in-memory before transmitting them via the Kafka Producer client API. Under peak load, improper configuration of Debezium’s queue boundaries (max.queue.size vs max.batch.size) causes JVM heap exhaustion.

When the JVM experiences long Stop-The-World (STW) Garbage Collection pauses, the Kafka Connect cluster drops its heartbeats to the group coordinator. This triggers a consumer group rebalance loop, completely halting CDC ingest and exacerbating upstream database WAL retention.


Enterprise Architecture Blueprint

To scale a change data capture architecture safely, decouple the PostgreSQL extraction layer from downstream ingestion by using bounded logical buffer pools, incremental non-blocking snapshots, and key-partitioned routing strategies.

+-------------------------------------------------------------------------------------------------------------------+
|                                      ECSTATICLOUD HIGH-THROUGHPUT CDC ARCHITECTURE                                |
|                                                                                                                   |
|  POSTGRESQL PRIMARY NODE                                      KAFKA CONNECT CLUSTER                               |
| ┌───────────────────────────────────────┐                    ┌─────────────────────────────────────────────────┐  |
| │  OLTP Engine (Writes)                 │                    │  Debezium Worker Pod                            │  |
| │  ┌──────────────────────────────────┐ │                    │  ┌──────────────────┐  ┌──────────────────────┐ │  |
| │  │ WAL Engine (pg_wal)              │ │                    │  │ Logical Decoder  │  │ Ring Buffer          │ │  |
| │  └──────────────────────────────────┘ │                    │  │ Worker Loop      │  │ (max.queue.size)     │ │  |
| │                 │                     │                    │  └────────┬─────────┘  └──────────┬───────────┘ │  |
| │                 ▼                     │                    │           │                       │             │  |
| │  ┌──────────────────────────────────┐ │ Direct Stream      │           ▼                       ▼             │  |
| │  │ Replication Slot (pgoutput)      │ │───────────────────>│  ┌──────────────────────────────────────────┐   │  |
| │  │ Max Slot Retention Enforced      │ │ TCP / TLS Protocol │  │ Kafka Producer Engine                    │   │  |
| │  └──────────────────────────────────┘ │                    │  │ (acks=all, lz4/zstd compression)         │   │  |
| └───────────────────────────────────────┘                    │  └────────────────────┬─────────────────────┘   │  |
|                                                              └───────────────────────┼─────────────────────────┘  |
|                                                                                      │                            |
|                                                                                      ▼                            |
| KAFKA CLUSTER                                                                                                     |
| ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────┐  |
| │ Apache Kafka Brokers (Partitioned Topics)                                                                    │  |
| │ ┌───────────────────────────┐ ┌───────────────────────────┐ ┌───────────────────────────┐                  │  |
| │ │ Topic: db.public.orders     │ │ Topic: db.public.users    │ │ Topic: db.sink.signals    │                  │  |
| │ │ Partition 0 | 1 | 2 | 3   │ │ Partition 0 | 1 | 2 | 3   │ │ Partition 0               │                  │  |
| │ └───────────────────────────┘ └───────────────────────────┘ └───────────────────────────┘                  │  |
| └──────────────────────────────────────────────────────────────────────────────────────────────────────────────┘  |
+-------------------------------------------------------------------------------------------------------------------+

Data Flow Execution Lifecycle

  1. Transaction Logging: An application executes a DML operation (INSERT, UPDATE, DELETE). PostgreSQL writes the change to the internal WAL ring buffer and commits the transaction.
  2. Logical Stream Parsing: The native pgoutput plugin reads raw binary WAL records, filtering data according to the configured PostgreSQL PUBLICATION. It converts physical changes into logical change events in memory. If memory exceeds logical_decoding_work_mem, temporary spill files are written to disk.
  3. Debezium Poll Ingestion: The Debezium PostgreSQL connector continuously pulls decoded tuples via the standard PostgreSQL streaming replication protocol. Events are transferred into an in-memory ring buffer array (max.queue.size).
  4. Serialization & Transformation: The Kafka Connect framework processes records through Single Message Transformations (SMTs)—such as masking PII or modifying topic names—and serializes payloads to binary format via the Confluent Schema Registry (Avro or Protobuf).
  5. Partition-Keyed Async Produce: The Kafka Producer flushes batches (max.batch.size) to designated Apache Kafka brokers. Records are routed to specific topic partitions based on the primary key hash, preserving strict ordering per entity while allowing horizontal consumption scaling downstream.
  6. Replication Offset Acknowledgment: Once Kafka confirms message replication across configured broker replicas (acks=all), Debezium commits the processed LSN back to PostgreSQL via the replication slot, freeing WAL files for removal by the PostgreSQL checkpoint engine.

Production-Ready Configuration & Implementation

The following configurations provide a enterprise-ready setup capable of processing sustained loads exceeding 40,000 events/sec.

1. PostgreSQL Engine Configuration (postgresql.conf)

Tune PostgreSQL engine parameters to prevent decoding disk spills, provide safe limits on slot allocations, and protect the system against wal bloat debezium scenarios.

# ====================================================================
# POSTGRESQL CDC OPTIMIZED CONFIGURATION
# Engine Target: PostgreSQL 14+
# High Throughput / High Availability Architecture
# ====================================================================

# WAL Replication Basics
wal_level = logical               # Required for logical decoding plugins
max_wal_senders = 10              # Maximum concurrent streaming connections
max_replication_slots = 10        # Maximum replication slots configured

# Logical Decoding Resource Tuning
# Allocates memory dedicated to decoding changes before spilling to disk.
# Prevents expensive disk I/O operations during large batch updates.
logical_decoding_work_mem = 64MB  

# Safety Circuit Breaker Against WAL Disk Exhaustion
# CRITICAL: If a replication slot falls behind by more than 100GB, PostgreSQL
# will invalidate the slot and reclaim disk space, saving the DB cluster.
max_slot_wal_keep_size = 102400MB 

# Checkpoint & WAL Sizing Parameters
max_wal_size = 32GB
min_wal_size = 4GB
checkpoint_completion_target = 0.9
checkpoint_timeout = 15min

# TCP Keepalive Settings (Prevents Silent Disconnections by Load Balancers)
tcp_keepalives_idle = 60
tcp_keepalives_interval = 10
tcp_keepalives_count = 6
wal_sender_timeout = 60000ms

2. Debezium PostgreSQL Connector Configuration

Submit this JSON payload to the Kafka Connect REST API (POST /connectors). It implements pgoutput, non-blocking incremental snapshot capabilities, and high-throughput memory buffers.

{
  "name": "ecstaticloud-postgres-cdc-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "tasks.max": "1",
    
    "plugin.name": "pgoutput",
    "database.hostname": "pg-primary.internal.ecstaticloud.com",
    "database.port": "5432",
    "database.user": "cdc_debezium_user",
    "database.password": "${file:/opt/kafka/connect/secrets.properties:db_password}",
    "database.dbname": "production_db",
    "database.server.name": "ecstaticloud_cdc",
    "topic.prefix": "ecstaticloud_cdc",
    
    "publication.name": "db_cdc_publication",
    "publication.autocreate.mode": "filtered",
    "slot.name": "debezium_cdc_primary_slot",
    "slot.drop.on.stop": "false",
    
    "database.history.kafka.bootstrap.servers": "kafka-cluster-kafka-bootstrap.kafka.svc:9092",
    "database.history.kafka.topic": "schema-changes.ecstaticloud-cdc",
    
    "snapshot.mode": "initial",
    "snapshot.locking.mode": "none",
    "snapshot.fetch.size": 10000,
    "incremental.snapshot.chunk.size": 4000,
    "signal.data.collection": "public.debezium_signal",
    
    "tombstones.on.delete": "false",
    "decimal.handling.mode": "double",
    "hstore.handling.mode": "json",
    
    "max.queue.size": 81920,
    "max.batch.size": 4096,
    "poll.interval.ms": 50,
    
    "producer.override.acks": "all",
    "producer.override.compression.type": "zstd",
    "producer.override.batch.size": 131072,
    "producer.override.linger.ms": 20,
    "producer.override.max.in.flight.requests.per.connection": "1",
    "producer.override.enable.idempotence": "true",
    
    "transforms": "unwrap,reroute",
    "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
    "transforms.unwrap.drop.tombstones": "true",
    "transforms.unwrap.delete.handling.mode": "rewrite",
    "transforms.unwrap.add.fields": "op,table,lsn,source.ts_ms",
    
    "transforms.reroute.type": "io.debezium.transforms.ByLogicalTableRouter",
    "transforms.reroute.topic.regex": ".*(.*)",
    "transforms.reroute.topic.replacement": "cdc-events-$1"
  }
}

3. Production Alerting Configuration (prometheus-alerts.yaml)

Monitor your system for operational failure modes such as postgres replication lag kafka spikes or slot stagnation using standard Prometheus rule syntax.

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: debezium-postgres-cdc-alerts
  namespace: monitoring
  labels:
    role: alert-rules
spec:
  groups:
  - name: cdc_pipeline.rules
    rules:
    - alert: PostgresCDCReplicationLagByteExtreme
      expr: pg_replication_slots_bytes_lag{slot_name="debezium_cdc_primary_slot"} > 53687091200
      for: 5m
      labels:
        severity: critical
        team: platform-data
      annotations:
        summary: "PostgreSQL Replication Slot Lag Exceeds 50GB"
        description: "Replication slot {{ $labels.slot_name }} on host {{ $labels.instance }} has accumulated over 50GB of lag. Immediate action required to prevent WAL disk space exhaustion."

    - alert: DebeziumMilliSecondsBehindSourceHigh
      expr: debezium_metrics_MilliSecondsBehindSource{plugin="postgres"} > 120000
      for: 10m
      labels:
        severity: warning
        team: platform-data
      annotations:
        summary: "Debezium Stream Lag Exceeds 2 Minutes"
        description: "Debezium connector task {{ $labels.connector }} is lagging behind PostgreSQL WAL creation by {{ $value }} ms."

    - alert: DebeziumTaskFailedState
      expr: kafka_connect_connector_tasks_state{state="failed",connector="ecstaticloud-postgres-cdc-connector"} == 1
      for: 1m
      labels:
        severity: critical
        team: platform-data
      annotations:
        summary: "Debezium Connector Task Failed"
        description: "The CDC connector task has entered a FAILED state. Check Kafka Connect stdout logs for deserialization failures or network disconnects."

Performance Benchmarks & Engineering Comparison

The metrics below demonstrate benchmark performance across architectural evolutions running on equivalent compute infrastructure (PostgreSQL 15 on AWS RDS db.r6g.4xlarge, Kafka Connect on 3x m6i.2xlarge nodes).

Production Performance Matrix

| Metric / Dimension | Default Debezium Setup | Optimized Debezium Engine | Ecstaticloud Scaled CDC Architecture | Impact / Gain | | :--- | :--- | :--- | :--- | :--- | | Max Event Throughput | 4,200 events/sec | 18,500 events/sec | 54,000+ events/sec | 12.8x Scale Increase | | p99 End-to-End Latency | 4,800 ms | 620 ms | 85 ms | 98.2% Reduction | | Decoding Plugin | decoderbufs | pgoutput | pgoutput (Tuned work_mem) | Zero Plugin Compile Dependency | | Postgres CPU Overhead | 38% average | 22% average | 12% average | 68.4% CPU Savings | | WAL Bloat Risk Profile | High (Unbounded) | Medium (Slot Limit Off) | Zero (Guarded via max_slot_wal_keep_size) | Eliminates Database Outages | | Initial Snapshot Impact | Table Locks (ACCESS SHARE) | Partial Lock Duration | Zero Locks (Signal-Based Incremental) | Non-Blocking OLTP Traffic | | Network Bandwidth (Wire) | Uncompressed (Raw JSON) | Gzip (Connector Level) | ZSTD (Engine-Level Batching) | 74% Network Savings |


Production Pitfalls, Failures, and Edge Cases

Operating change data capture pipelines at high scale exposes low-level nuances in PostgreSQL internals and Kafka protocol drivers. Here are four key edge cases that must be mitigated.

1. The Unbounded WAL Storage Explosion Trap

By default, PostgreSQL keeps all WAL files required by an active logical replication slot indefinitely. If your Kafka Connect cluster crashes or suffers a persistent networking error over a long weekend, Debezium stops acknowledging LSN positions.

The primary database server will accumulate high volumes of WAL segments until disk usage reaches 100%.

Mitigation: Always configure max_slot_wal_keep_size in postgresql.conf. Setting this parameter (e.g., to 102400MB) explicitly invalidates stagnant replication slots if their lag exceeds the threshold. This drops the CDC reader while protecting your underlying primary database from hard disk crashes.

2. TOAST Column Invalidation & REPLICA IDENTITY FULL Overhead

PostgreSQL uses TOAST (The Oversized-Attribute Storage Technique) to store large column values out-of-line. When an update occurs on a row containing TOASTed data, PostgreSQL skips unchanged TOAST values in the WAL stream to minimize write volume.

Consequently, Debezium streams these unchanged attributes as null or omitted payloads. If downstream consumers expect intact full-row data models, processing fails.

-- ALTER TABLE Strategy for Missing TOAST columns:
-- Forces PostgreSQL to write entire previous row attributes into the WAL log.
ALTER TABLE public.large_orders REPLICA IDENTITY FULL;

Warning: Setting REPLICA IDENTITY FULL causes significant write amplification. Every single column value—changed or unchanged—is written to the WAL on every update, inflating overall WAL throughput by 4x to 10x. Evaluate if downstreams can handle partial payloads before enabling this globally.

3. Single-Task Bottlenecks in Logical Replication

Kafka Connect supports setting tasks.max > 1 for parallelism across consumer workers. However, PostgreSQL logical replication slots cannot be read concurrently by multiple streams.

A single logical slot maps to exactly one active WAL sender process and one Debezium task. Setting tasks.max > 1 on a single PostgreSQL Debezium connector has no scaling effect for a single database slot.

                  POSTGRESQL DATABASE                        CDC PIPELINE
┌─────────────────────────────────────────────────────┐     ┌───────────┐
│  Table: Orders     ──┐                              │     │  Debezium │
│                      ├──►  Replication Slot #1  ────┼────►│  Task #1  │
│  Table: Payments   ──┘    (Single Worker Thread)    │     └───────────┘
│                                                     │
│  Table: Audit_Logs ─────►  Replication Slot #2  ────┼────►┌───────────┐
│                           (Separate Stream Engine)  │     │  Debezium │
└─────────────────────────────────────────────────────┘     │  Task #2  │
                                                            └───────────┘

Architectural Solution: If your database exceeds the throughput limits of a single CPU thread (~35k-50k events/sec decoding ceiling), split your schema across multiple distinct PostgreSQL publications and connectors, each utilizing its own distinct logical replication slot.

4. Schema Evolution Locks during Initial Snapshotting

Executing a standard initial database snapshot on multi-terabyte tables causes prolonged table locks. Default settings attempt to issue LOCK TABLE ... IN ACCESS SHARE MODE, blocking schema alteration DDL scripts executed by application microservice migration steps.

Mitigation: Use Debezium's Incremental Snapshots mechanism powered by signal tables. By inserting a row into a designated signal table, Debezium processes table data in small, primary-key-bounded chunks without acquiring global table locks or stalling active OLTP microservices:

-- Create the CDC signal table
CREATE TABLE public.debezium_signal (
    id VARCHAR(64) PRIMARY KEY,
    type VARCHAR(32) NOT NULL,
    data VARCHAR(2048) NULL
);

-- Trigger an incremental snapshot for table 'orders' without locking
INSERT INTO public.debezium_signal (id, type, data)
VALUES (
    'snapshot-request-001', 
    'execute-snapshot', 
    '{"data-collections": ["public.orders"],"type":"INCREMENTAL"}'
);

Frequently Asked Questions

How do I prevent PostgreSQL WAL bloat when a downstream Kafka cluster is offline?

To prevent persistent database failure during downstream Kafka outages, set max_slot_wal_keep_size in postgresql.conf. This setting limits the maximum WAL accumulation per replication slot. If the slot exceeds this value, PostgreSQL marks the slot as invalid and reclaims disk space. You will need to trigger an incremental re-snapshot of the connector once Kafka recovers, but the database cluster remains operational.

Can I run multiple Debezium tasks in parallel for a single PostgreSQL logical slot?

No. The PostgreSQL logical replication protocol enforces single-stream processing per logical replication slot. A single slot can only be parsed by one active Debezium worker thread at any given time. To parallelize processing, create multiple distinct PostgreSQL publications containing non-overlapping database table sets, and attach isolated Debezium connector tasks using dedicated replication slots.

What is the technical difference between decoderbufs and pgoutput for high-scale scaling?

decoderbufs is an external PostgreSQL plugin based on Protocol Buffers that requires explicit compilation and installation on the database server file system. pgoutput is PostgreSQL's built-in logical decoding plugin included natively since PostgreSQL 10. pgoutput incurs less CPU overhead, requires no third-party extensions, handles memory allocations natively via logical_decoding_work_mem, and scales more efficiently under heavy DML workloads.

Need Help Scaling Cloud Infrastructure?

Partner with Ecstaticloud's boutique engineering architects to implement zero-trust architectures, optimize inference workloads, or eliminate cloud waste.

Talk to an Architect
Deep Dives

Related Technical Insights

View all →