Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 4 min read

Event-Driven Microservices with the Outbox Pattern

--- title: "Event-Driven Microservices: The Outbox Pattern, Debezium, and the Idempotency Contract That Saves You" published: true description: "Master the transactional outbox pattern β€” atomic DB writes, CDC via Debeziu

---
title: "Event-Driven Microservices: The Outbox Pattern, Debezium, and the Idempotency Contract That Saves You"
published: true
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."
tags: architecture, api, postgresql, kotlin
canonical_url: https://blog.mvpfactory.co/event-driven-microservices-outbox-pattern-kafka-idempotency
---

## What you will build

By the end of this workshop you will understand how to eliminate the dual-write problem in event-driven microservices. You will implement the transactional outbox pattern β€” storing events atomically alongside domain writes, relaying them via Debezium CDC, and writing the idempotency contract that makes your Kafka consumers safe to replay under any failure condition.

## Prerequisites

- Familiarity with Kafka and a relational database (Postgres or MySQL)
- Basic Kotlin or JVM service experience
- A running Kafka cluster and a database you can add tables to

---

## Step 1 β€” Understand the dual-write problem

Most teams write to the database *and* publish to Kafka as two separate operations. This looks fine until the process crashes between step one and step two. Domain state is committed. The event is never published. Downstream consumers are silently out of sync.

No exception is thrown. No metric spikes. The bug lives in the gap between infrastructure boundaries. This is the failure mode that kills distributed consistency, and it is subtle enough to survive code review.

## Step 2 β€” Write to the outbox, not to Kafka

Here is the pattern I use in every project. Instead of publishing directly to Kafka, write an `outbox_events` record *within the same database transaction* as your domain entity change.


sql
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;


Atomicity is guaranteed by the database. The event either exists alongside the domain state, or neither does. Your service never talks to Kafka on the write path.

## Step 3 β€” Relay with Debezium CDC

A dedicated relay process reads from `outbox_events` and publishes to Kafka. The production-grade approach is CDC β€” Change Data Capture via **Debezium**, which tails the database transaction log (WAL in Postgres, binlog in MySQL) rather than polling rows.

| Relay Strategy | Latency (p99) | At-Risk Window | Complexity |
|---|---|---|---|
| Polling (1s interval) | ~1,000ms | 1s of missed events | Low |
| Polling (100ms interval) | ~100ms | 100ms window | Low–Medium |
| CDC via Debezium | ~50ms | Near-zero | Medium–High |
| In-process publisher | ~5ms | Full dual-write risk | Low (dangerous) |

CDC wins on reliability. No polling gap, no missed window, no thundering herd on the outbox table under load. Deploy Debezium via Kafka Connect and monitor `source.lag` as your primary SLI for event delivery latency.

## Step 4 β€” Build idempotent consumers, not exactly-once consumers

Here is the gotcha that will save you hours: exactly-once delivery is a lie worth abandoning.

Kafka guarantees at-least-once delivery in standard configurations. Even with `enable.idempotence=true` and transactional APIs, exactly-once semantics break down the moment your consumer writes to a non-Kafka sink β€” a database, a REST API, a cache. That covers almost every real consumer you will ever write.

The docs do not make this obvious, but the production-proven contract is: **at-least-once delivery + idempotent consumers**.


kotlin
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()))
}

}


Use the outbox event's UUID as your deduplication key. Store it in a `processed_events` table within the *same transaction* as your consumer's side-effect. Consume-and-record atomically. Replay safely.

---

## Gotchas

**Forgetting the idempotency write is in the same transaction.** If you check `processed_events` before the transaction and write it after, you have a race condition. The check and the write must be atomic with the business logic.

**Using polling when Debezium is available.** Polling has a gap window. Under load, that gap becomes your outage window. The operational overhead of Debezium pays for itself at scale.

**Designing for exactly-once at the broker.** Kafka transactions are real, but they only hold end-to-end when both producer and consumer are Kafka. The moment your consumer touches a database, you are back to at-least-once. Design accordingly.

**Letting the outbox table grow unbounded.** Add a cleanup job that deletes published rows older than your retention window. Otherwise you have a slow-query incident waiting to happen.

---

## Conclusion

Here is the minimal setup to get this working in production: atomic outbox writes in one DB transaction, Debezium reading the WAL, and a `processed_events` table per consumer service with deduplication on the outbox UUID.

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 optimising anything else β€” dual writes are the root cause, not a symptom.

The failure modes this eliminates are real: Debezium crash resumes from last WAL offset, consumer crash replays safely via the idempotency key, database failover preserves outbox records alongside domain state.

**Resources:**
- [Debezium documentation](https://debezium.io/documentation/)
- [Kafka Connect Debezium connector](https://debezium.io/documentation/reference/stable/connectors/)
- [Kafka producer idempotence](https://kafka.apache.org/documentation/#producerconfigs_enable.idempotence)
πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.