Change Data Capture (CDC) with Debezium & Kafka: eliminating dual-write bugs
Why application dual-writes corrupt distributed systems, and how Debezium streams PostgreSQL Write-Ahead Logs (WAL) to Kafka for real-time cache and search index syncing.
In modern data architectures, a single piece of business data rarely lives in only one place.
When a customer updates their profile or places an order:
- The PostgreSQL Database stores the source-of-truth relational record.
- The Redis Cache stores the serialized session or fast lookup entity.
- The Elasticsearch Cluster indexes the text for search and filtering.
- The Data Warehouse (Snowflake / BigQuery) ingests the event for analytics.
How do you keep all these heterogeneous data stores synchronized in real time without introducing distributed race conditions?
1. The Dual-Write Anti-Pattern
The most common mistake engineering teams make is implementing dual writes directly inside application code:
// DUAL-WRITE HAZARD:
async function updateOrderStatus(orderId: string, status: string) {
// Step 1: Write to primary database
await db.query("UPDATE orders SET status = $1 WHERE id = $2", [status, orderId]);
// Step 2: Publish message to message broker
await kafkaProducer.send({
topic: "orders.events",
messages: [{ key: orderId, value: JSON.stringify({ orderId, status }) }],
});
}
DUAL WRITE HAZARDS:
1. Partial Failure: DB update succeeds, but network crash kills Kafka producer.
➔ Cache and search indexes are now permanently stale!
2. Race Conditions (Out-of-Order Execution):
Thread A (Order status = "Pending") writes DB at t=0
Thread B (Order status = "Shipped") writes DB at t=1, then publishes to Kafka at t=2
Thread A experiences network jitter, publishes to Kafka at t=3
➔ Kafka ends with "Pending", corrupting downstream caches!
2. The Solution: Change Data Capture (CDC)
Change Data Capture (CDC) solves this by shifting event generation out of application code and into the database engine itself.
Instead of writing to multiple destinations, the application writes only once to PostgreSQL within a standard ACID transaction.
┌─────────────────┐
│ Application │
└────────┬────────┘
│ 1. Standard SQL Write (ACID)
▼
┌─────────────────┐
│ PostgreSQL (DB) │ ────▶ [Write-Ahead Log (WAL)]
└─────────────────┘ │
│ 2. Logical Replication Stream
▼
┌───────────────┐
│Debezium Engine│
└───────┬───────┘
│ 3. Ordered Kafka Events
▼
┌───────────────┐
│ Apache Kafka │
└───────┬───────┘
┌─────────────────────┼─────────────────────┐
│ │ │
▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐
│Redis Cache│ │Elastic srch│ │ Data Lake │
└───────────┘ └───────────┘ └───────────┘
3. How Debezium and PostgreSQL WAL Work
The PostgreSQL Write-Ahead Log (WAL)
Every relational database maintains an append-only log (the WAL in Postgres, the Redo Log in Oracle, the Binlog in MySQL). Before any table data or B-tree index is modified on disk, the exact binary delta is committed sequentially to the WAL.
Debezium Logical Decoding
Debezium connects to PostgreSQL via a Logical Replication Slot (using pgoutput or decoderbufs). It reads WAL byte segments as they are committed and converts them into rich, structured JSON or Apache Avro change events:
{
"before": {
"order_id": "1001",
"status": "pending",
"total": 89.50
},
"after": {
"order_id": "1001",
"status": "shipped",
"total": 89.50
},
"source": {
"version": "2.5.0",
"connector": "postgres",
"name": "production_db",
"ts_ms": 1727500000000,
"db": "commerce",
"table": "orders",
"txId": 58392,
"lsn": 10485760
},
"op": "u"
}
4. Key Architectural Benefits of Debezium CDC
- Zero Impact on Application Code: Backend developers write clean, standard SQL. They never have to write error-prone transactional outbox or sync logic.
- Guaranteed Per-Key Ordering: By partitioning Kafka topics on the table primary key (
order_id), events for a single entity are processed in strict chronological order. - Fault-Tolerant Replayability: If a downstream consumer (like Elasticsearch) crashes or requires a complete re-index, it can reset its Kafka offset to time zero and replay the entire history of database mutations.
- Historical Schema Tracking: Debezium integrates with Schema Registry (Avro/Protobuf), seamlessly tracking table column additions and type modifications without breaking downstream microservices.
5. Summary Cheatsheet
| Characteristic | Dual Writes | Transactional Outbox | Debezium CDC |
|---|---|---|---|
| Consistency | Low (Split-Brain Risk) | High | Guaranteed (WAL source) |
| App Code Complexity | High | Medium (Custom Outbox Table) | Zero (Native DB Engine) |
| Latency | Instantaneous | 500ms - 2000ms (Poller lag) | Sub-10ms (Streamed WAL) |
| CDC / Audit History | Missing | Manual | Full Before & After State |
Test Your Understanding
Quick architectural scenario challenge based on this breakdown.
A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.
Q1.How should a downstream dependency failure be handled to protect upstream service availability?
Comments –
Sign in to share your thoughts
Nothing yet. Be the first.