In distributed architectures, one of the quickest ways to corrupt system state is an unhandled dual write. You save an entity to your primary database (like PostgreSQL), and immediately attempt to publish an event to Apache Kafka within the same HTTP request lifecycle.

If the database commit succeeds but the Kafka broker returns a timeout or your process crashes, your event is lost forever. If you reverse the sequence and produce to Kafka first, a database transaction rollback leaves phantom events circulating across downstream consumers. Distributed transactions (Two-Phase Commit / 2PC) introduce unacceptable latency and coordinator bottlenecks.

Here is how to solve dual writes reliably using the Transactional Outbox pattern paired with Debezium Change Data Capture (CDC).

1. The Outbox Table Schema

Instead of publishing directly to Kafka from your application code, write the domain mutation and an outbox event inside a single, local ACID transaction.

Create a dedicated outbox table designed for high insert throughput:

CREATE TABLE outbox_events ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), aggregate_type VARCHAR(255) NOT NULL, aggregate_id VARCHAR(255) NOT NULL, event_type VARCHAR(255) NOT NULL, payload JSONB NOT NULL, tracing_context JSONB DEFAULT '{}'::jsonb, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -- Index for cleanup jobs or polling fallbacks CREATE INDEX idx_outbox_created_at ON outbox_events (created_at); 

When handling an operation like CreateOrder, execute both operations inside the same transaction block:

BEGIN; INSERT INTO orders (id, customer_id, total_cents, status) VALUES ('a5b1c2d3-0000-0000-0000-000000000001', 'cust_99', 14999, 'CREATED'); INSERT INTO outbox_events (aggregate_type, aggregate_id, event_type, payload) VALUES ( 'Order', 'a5b1c2d3-0000-0000-0000-000000000001', 'OrderCreated', '{"order_id": "a5b1c2d3-0000-0000-0000-000000000001", "total_cents": 14999}'::jsonb ); COMMIT; 

Both writes either commit together or roll back together. Data consistency is guaranteed at the storage engine level.

2. Streaming via Debezium CDC (Log-Tailing)

Polling outbox tables introduces query overhead and table lock contention under high load. A production-grade alternative is log-based CDC via Debezium. Debezium reads PostgreSQL's write-ahead log (WAL) through logical decoding plugins (pgoutput), streaming rows to Kafka asynchronously without table locks.

Here is a production Debezium Outbox Event Router connector configuration:

{ "name": "order-outbox-connector", "config": { "connector.class": "io.debezium.connector.postgresql.PostgresConnector", "tasks.max": "1", "plugin.name": "pgoutput", "database.hostname": "postgres-cluster", "database.port": "5432", "database.user": "debezium_cdc", "database.password": "${file:/secrets/db.properties:cdc_pass}", "database.dbname": "orders_db", "database.server.name": "order_engine", "table.include.list": "public.outbox_events", "tombstones.on.delete": "false", "transforms": "outbox", "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter", "transforms.outbox.route.by.field": "aggregate_type", "transforms.outbox.route.topic.replacement": "events.${routedByValue}", "transforms.outbox.table.field.event.id": "id", "transforms.outbox.table.field.event.key": "aggregate_id", "transforms.outbox.table.field.event.payload": "payload" } } 

With this configuration:

  • Events route automatically to dynamic topics like events.Order.
  • The record key in Kafka is set to aggregate_id, ensuring strict partition-level ordering per entity.
  • Debezium converts the CDC row into a clean domain event without wrapping it in excessive CDC metadata.

3. Choosing Coordination: Choreography vs. Orchestration

Once events land in Kafka, multi-service workflows (Sagas) must execute. Teams often default to pure event choreography without considering operational maintenance.

Use this rule of thumb:

  • Event Choreography (Services react directly to upstream events): Best for workflows with $\le 3$ service hops and minimal rollback logic (e.g., notification dispatches, read-model projections in CQRS).
  • Saga Orchestrator (Central state-machine coordinator): Essential when workflows exceed 3 hops or require strict compensation actions (e.g., booking flights, hotel reservations, and credit authorizations where any failure requires deterministic rollbacks in reverse order).
CHOREOGRAPHY: OrderCreated -> PaymentProcessed -> StockReserved ORCHESTRATION: OrderSagaCoordinator -> Send(ProcessPayment) -> Recv(PaymentCaptured) -> Send(ReserveStock) 

Choreography offers higher raw throughput, while orchestration offers clear distributed observability and determinism.

Take Your Event-Driven Systems Further

Building bulletproof distributed systems requires more than just knowing the pattern names—it demands exact partition sizing, backpressure mechanics, dead-letter routing, and CQRS synchronization.

If you want full configuration templates, production Docker Compose test environments, schema evolution rules, and end-to-end architectures, check out The Event-Driven Architecture & Kafka Engine Playbook for $19.

Inside, you'll find:

  • Production outbox and CDC pipelines (PostgreSQL, Debezium, Kafka Connect).
  • Deterministic partition key strategies and idempotent consumer patterns.
  • End-to-end CQRS blueprints with Elasticsearch/Redis read projections.
  • Saga choreography vs. orchestration decision frameworks with zero boilerplate.