Transactional Outbox & Distributed Consistency
Bridge relational database ACID transactions with Apache Kafka event streams using the Transactional Outbox pattern and Debezium Change Data Capture.
Microservices frequently face a difficult architectural requirement: you must update an entity in a relational database (such as PostgreSQL) and simultaneously publish an event to Apache Kafka (such as OrderCreated).
If you execute these two operations sequentially in Java code, your system is vulnerable to the Dual-Write Hazard, resulting in unrecoverable state inconsistencies between your database and your event stream.
In this lesson, you will analyze why dual writes fail, explore how the Transactional Outbox Pattern guarantees atomic database updates and event publishing, and learn how Debezium Change Data Capture (CDC) streams outbox records to Kafka with sub-second latency.
01The Dual-Write Hazard
Consider this common Spring Boot code snippet:
@Transactional
public void createOrder(OrderRequest request) {
// 1. Save to relational database
Order order = orderRepository.save(new Order(request));
// 2. Publish event to Kafka
kafkaTemplate.send("orders", order.getId(), new OrderCreatedEvent(order));
}While this code looks clean, it creates two catastrophic failure scenarios in production:
Scenario A: Kafka Fails, Database Commits
- The database transaction commits successfully. The customer order is saved in PostgreSQL.
- The
kafkaTemplate.send()call fails due to a network timeout or broker outage. - The method throws an exception, but the database transaction has already committed.
- Result: The order exists in the database, but no event was ever published to Kafka. The Inventory Service never reserves stock, and the Billing Service never charges the customer.
Scenario B: Kafka Succeeds, Database Rolls Back
- You switch the order: you publish to Kafka first, then call
orderRepository.save(). - The Kafka message is sent and acknowledged by the broker.
- The database write throws a
DataIntegrityViolationExceptiondue to an unexpected unique constraint conflict and rolls back. - Result: A "ghost order" event exists in Kafka. The shipping service packages an item for an order that does not exist in the primary system of record.
Loading the rest of the lesson…