MVP Factory
EN
ai startup development

Outbox pattern: atomic writes & Kafka guarantees

KW
Krystian Wiewiór · · 4 min read

Meta description: Master the transactional outbox pattern — atomic DB writes, CDC via Debezium, at-least-once Kafka delivery, and the idempotency contract that makes consumers replay-safe.


TL;DR

The dual-write problem kills distributed consistency. The transactional outbox pattern solves it by co-locating domain writes and event records in a single DB transaction, then using CDC (Change Data Capture) to reliably publish to Kafka. Exactly-once delivery is a myth worth abandoning — at-least-once with a robust idempotency key is the production-proven contract.


The dual-write problem nobody talks about enough

Most teams building event-driven microservices write to the database and publish to Kafka as two separate operations. This looks harmless until your process crashes between step one and step two. Now your domain state is committed, your downstream consumers never got the event, and your system is silently inconsistent.

In my experience building production systems, this failure mode is subtle and catastrophic precisely because it’s invisible at the application layer. No exception is thrown. No metric spikes. The bug lives in the gap between infrastructure boundaries.

The outbox pattern: one transaction to rule them all

The fix is elegant. Instead of publishing directly to Kafka, you write an outbox_events record within the same database transaction as your domain entity change. Atomicity is now guaranteed by the database — the event either exists alongside the domain state, or neither does.

BEGIN;

UPDATE orders SET status = 'CONFIRMED' WHERE id = :orderId;

INSERT INTO outbox_events (id, aggregate_type, aggregate_id, event_type, payload, created_at)
VALUES (:uuid, 'Order', :orderId, 'OrderConfirmed', :jsonPayload, NOW());

COMMIT;

Your service never talks to Kafka during the write path. The outbox table is the source of truth for unpublished events.

CDC via Debezium: the reliable relay

A dedicated relay process polls or streams from outbox_events and publishes to Kafka. The production-grade approach is CDC — Change Data Capture via Debezium, which tails the database’s transaction log (WAL in Postgres, binlog in MySQL) rather than polling rows.

Relay StrategyLatency (p99)At-Risk WindowOperational Complexity
Polling (1s interval)~1,000ms1s of missed events on crashLow
Polling (100ms interval)~100ms100ms windowLow–Medium
CDC via Debezium~50msNear-zero (log-based)Medium–High
In-process publisher~5msFull dual-write riskLow (but dangerous)

CDC wins on reliability because it reads committed transactions directly from the log. No polling gap, no missed window, no thundering herd on the outbox table under load.

Exactly-once is a lie. Here’s what to build instead.

Kafka guarantees at-least-once delivery in standard configurations. Even with idempotent producers (enable.idempotence=true) and transactional APIs, exactly-once semantics require your consumer to participate in Kafka transactions — a constraint that breaks down the moment your consumer writes to a non-Kafka sink (a database, a REST API, a cache).

Stop designing for exactly-once. Design for idempotent consumers.

fun handleOrderConfirmed(event: OrderConfirmedEvent) {
    val alreadyProcessed = processedEventRepo.existsById(event.eventId)
    if (alreadyProcessed) return  // safe replay

    transactionTemplate.execute {
        fulfillmentService.initiateFulfillment(event.orderId)
        processedEventRepo.save(ProcessedEvent(id = event.eventId, processedAt = Instant.now()))
    }
}

The idempotency key design is non-negotiable: use the outbox event’s UUID as the deduplication key on the consumer side. Store it in a processed_events table within the same transaction as your consumer’s side-effect. This is the idempotency contract — consume-and-record atomically, replay safely.

The complete architecture

Domain Service
     │
     ▼
[ DB Transaction ]─────────────────────────────┐
   ├── domain_table (UPDATE)                    │
   └── outbox_events (INSERT)                   │
                                                 │
Debezium (CDC)                                   │
     │  reads WAL/binlog                         │
     ▼                                           │
[ Kafka Topic: order.events ]                    │
     │                                           │
     ▼                                           │
Consumer Service                                 │
   ├── check processed_events (dedup)            │
   ├── apply business logic                      │
   └── write processed_events (same tx) ◄────────┘

The failure modes this eliminates: Debezium crash → resumes from last WAL offset, no events lost. Kafka consumer crash mid-processing → replays event, idempotency key blocks re-execution. Database failover → outbox records survive with the domain state.


Actionable takeaways

Audit your service for any code path that writes to a DB and then calls an event bus. Migrate those to the outbox pattern first, before optimizing anything else — dual writes are the root cause, not a symptom.

For production workloads, deploy Debezium over a polling relay. The operational overhead pays off at scale. Use Kafka Connect with the Debezium connector and monitor source.lag as your primary SLI for event delivery latency.

Define your idempotency contract at the consumer level, not the broker level. Build a processed_events table per consumer service, deduplicate on the outbox UUID, and write deduplication records in the same transaction as your side effects. That’s the only replay safety that actually holds under real failure conditions.


Tags: microservices backend architecture cleanarchitecture api


Share: Twitter LinkedIn