Distributed Transactions in Microservices: 2PC, Saga Pattern, and the Transactional Outbox
Your payment service just charged a customer and also your inventory service went down as well. Neither of them knows about the other. The customer’s money is gone and no product is coming, and every log in every service looks completely fine.
Whenever you ran into this the first time Its probably becasue yuo ahve split a monolith into services. The transaction guarantees you relied on stopped at the database boundary, and nobody warned you about what comes after.
This article covers the four patterns engineers use to handle this. We’ll build all of them with the same Order, Payment, and Inventory scenario throughout so you can see exactly where each one holds, and where it cracks.
The scenario
Three services. One customer order.
OrderService creates orders. PaymentService charges customers. InventoryService reserves stock. When a customer buys something, all three need to succeed. If any one of them fails, the other two need to undo their work.
In a single database this is two lines of SQL inside a transaction. In three separate services with three separate databases, it is one of the hardest problems in distributed systems.
Here is the failure case that costs companies real money:
- Payment succeeds. Customer is charged.
- Inventory check fails. Product is out of stock.
- Customer’s money is gone. No product is coming.
The payment service doesn’t know inventory failed. The inventory service doesn’t know payment succeeded. They are completely separate systems running on separate machines. Nobody told them to talk to each other.
This is the problem. Every pattern in this article is a different answer to it.
Pattern 1: Two-Phase Commit
The classic solution. Before committing anything, ask everyone if they’re ready. Only commit when all of them say yes.
Phase one is the prepare phase. A coordinator asks every participant to lock their resources, validate the operation, and report back,ready or not ready. If everyone says ready, phase two begins: commit. If anyone says not ready, everyone rolls back.
<button data-code="public interface Participant {
boolean prepare(String transactionId, Map context);
void commit(String transactionId);
void rollback(String transactionId);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public interface Participant {
boolean prepare(String transactionId, Map<String, Object> context);
void commit(String transactionId);
void rollback(String transactionId);
}
public interface Participant {
boolean prepare(String transactionId, Map<String, Object> context);
void commit(String transactionId);
void rollback(String transactionId);
}
The coordinator runs both phases:
<button data-code="public boolean execute(Map context) {
String txId = UUID.randomUUID().toString();
List prepared = new ArrayList();
// Phase 1: ask everyone to prepare
for (Participant participant : participants) {
if (participant.prepare(txId, context)) {
prepared.add(participant);
} else {
// someone refused, roll back everyone who already prepared
for (Participant p : prepared) {
p.rollback(txId);
}
return false;
}
}
// Phase 2: everyone said yes, now commit
for (Participant participant : participants) {
participant.commit(txId);
}
return true;
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public boolean execute(Map<String, Object> context) {
String txId = UUID.randomUUID().toString();
List<Participant> prepared = new ArrayList<>();
// Phase 1: ask everyone to prepare
for (Participant participant : participants) {
if (participant.prepare(txId, context)) {
prepared.add(participant);
} else {
// someone refused, roll back everyone who already prepared
for (Participant p : prepared) {
p.rollback(txId);
}
return false;
}
}
// Phase 2: everyone said yes, now commit
for (Participant participant : participants) {
participant.commit(txId);
}
return true;
}
public boolean execute(Map<String, Object> context) {
String txId = UUID.randomUUID().toString();
List<Participant> prepared = new ArrayList<>();
// Phase 1: ask everyone to prepare
for (Participant participant : participants) {
if (participant.prepare(txId, context)) {
prepared.add(participant);
} else {
// someone refused, roll back everyone who already prepared
for (Participant p : prepared) {
p.rollback(txId);
}
return false;
}
}
// Phase 2: everyone said yes, now commit
for (Participant participant : participants) {
participant.commit(txId);
}
return true;
}
Each service implements the Participant interface. The payment service holds funds during prepare and finalises during commit. The inventory service reserves stock during prepare and confirms during commit. If anything fails at the prepare stage, everyone rolls back cleanly.
The payment failure case works exactly as you’d hope:
[PaymentParticipant] Refused: customer-2 has $50, needs $200
[Coordinator] Payment refused. Rolling back OrderParticipant
[OrderParticipant] Rolled back: discarded pending order
Result: ROLLED BACK
[PaymentParticipant] Refused: customer-2 has $50, needs $200
[Coordinator] Payment refused. Rolling back OrderParticipant
[OrderParticipant] Rolled back: discarded pending order
Result: ROLLED BACK
Clean. No order created. No money taken. This is 2PC working as designed.
Where 2PC Goes Wrong at 3am
Here’s what the textbook doesn’t emphasise enough: 2PC works perfectly until one specific thing goes wrong, and when it does, your database is permanently inconsistent with no automatic way out.
The coordinator commits participant one. Then it crashes.
<button data-code="public boolean executeWithSimulatedCrash(Map context) {
// Phase 1: all prepare successfully
for (Participant p : participants) {
p.prepare(txId, context);
}
// Phase 2: commit first participant
participants.get(0).commit(txId);
// COORDINATOR CRASHES HERE
throw new RuntimeException(
"CRASH: " + participants.get(0).getName() + " committed. " +
"Others are stuck in PREPARED state forever."
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
public boolean executeWithSimulatedCrash(Map<String, Object> context) {
// Phase 1: all prepare successfully
for (Participant p : participants) {
p.prepare(txId, context);
}
// Phase 2: commit first participant
participants.get(0).commit(txId);
// COORDINATOR CRASHES HERE
throw new RuntimeException(
"CRASH: " + participants.get(0).getName() + " committed. " +
"Others are stuck in PREPARED state forever."
);
}
public boolean executeWithSimulatedCrash(Map<String, Object> context) {
// Phase 1: all prepare successfully
for (Participant p : participants) {
p.prepare(txId, context);
}
// Phase 2: commit first participant
participants.get(0).commit(txId);
// COORDINATOR CRASHES HERE
throw new RuntimeException(
"CRASH: " + participants.get(0).getName() + " committed. " +
"Others are stuck in PREPARED state forever."
);
}
Participant one has committed. The data is written. Participant two is still in the prepared state, holding locks, waiting for a commit signal that will never come.
The database is now inconsistent. There is no automatic recovery. A human has to figure out what happened, decide what the final state should be, and manually fix it.
The second problem is that 2PC is a blocking protocol. Every participant holds locks from the moment they prepare until they receive commit or rollback. If the coordinator is slow, all participants wait. If the coordinator dies, all participants block indefinitely. At any meaningful scale this destroys throughput.
These two problems together are why 2PC is not used in modern microservices. The consistency guarantee it offers is not worth the operational cost, and a single coordinator failure can leave your system in a state that requires manual intervention to fix.
The Saga Pattern
The Saga pattern exists specifically because of those two problems.
Instead of one atomic transaction spanning all services, you break the work into a sequence of local transactions,each independently committable. If a later step fails, you don’t rollback. You compensate. You create new forward transactions that correct the effect of the ones that already succeeded.
The key distinction: compensation is not the same as rollback. A rollback pretends the operation never happened. Compensation acknowledges it happened and corrects it. A refund is not an undone charge; it is a new charge in the opposite direction. That sounds subtle but the implications matter enormously for how you design each step.
There are two ways to coordinate a Saga: choreography, where services react to each other’s events with no central coordinator, and orchestration, where a central service manages the entire flow explicitly.
Pattern 2: Saga Choreography
In choreography there is no coordinator. Services publish events when they complete their step. Other services subscribe to those events and react. Nobody is in charge. The saga emerges from the interaction.
public enum EventType {
ORDER_CREATED,
PAYMENT_PROCESSED,
INVENTORY_RESERVED,
ORDER_CONFIRMED,
// Compensation events - the undo path
PAYMENT_FAILED,
INVENTORY_FAILED,
PAYMENT_REFUNDED,
ORDER_CANCELLED
}
public enum EventType {
ORDER_CREATED,
PAYMENT_PROCESSED,
INVENTORY_RESERVED,
ORDER_CONFIRMED,
// Compensation events - the undo path
PAYMENT_FAILED,
INVENTORY_FAILED,
PAYMENT_REFUNDED,
ORDER_CANCELLED
}
The happy path flows like this: OrderService publishes ORDER_CREATED. PaymentService hears it, charges the customer, publishes PAYMENT_PROCESSED. InventoryService hears that, reserves stock, publishes INVENTORY_RESERVED. OrderService hears that, confirms the order.
No service calls another directly. They just react. Here is the full OrderService:
public class OrderService {
public OrderService(EventBus eventBus) {
eventBus.subscribe(EventType.INVENTORY_RESERVED, this::onInventoryReserved);
eventBus.subscribe(EventType.PAYMENT_FAILED, this::onPaymentFailed);
eventBus.subscribe(EventType.INVENTORY_FAILED, this::onInventoryFailed);
eventBus.subscribe(EventType.PAYMENT_REFUNDED, this::onPaymentRefunded);
}
public Order createOrder(String customerId, String productId, int quantity, double amount) {
Order order = new Order(UUID.randomUUID().toString(), customerId, productId, quantity, amount);
orders.put(order.getId(), order);
eventBus.publish(new Event(EventType.ORDER_CREATED, order.getId(), Map.of(
"customerId", customerId,
"productId",productId,
"quantity", quantity,
"amount", amount
)));
return order;
}
private void onInventoryReserved(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.CONFIRMED);
}
private void onPaymentFailed(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.PAYMENT_FAILED);
eventBus.publish(new Event(EventType.ORDER_CANCELLED, event.getOrderId(),
Map.of("reason", "Payment declined")));
}
private void onInventoryFailed(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.INVENTORY_FAILED);
// wait for PAYMENT_REFUNDED before cancelling
}
private void onPaymentRefunded(Event event) {
Order order = orders.get(event.getOrderId());
if (order.getStatus() == OrderStatus.INVENTORY_FAILED) {
order.setStatus(OrderStatus.CANCELLED);
eventBus.publish(new Event(EventType.ORDER_CANCELLED, event.getOrderId(),
Map.of("reason", "Inventory unavailable, payment refunded")));
}
}
}
public class OrderService {
public OrderService(EventBus eventBus) {
eventBus.subscribe(EventType.INVENTORY_RESERVED, this::onInventoryReserved);
eventBus.subscribe(EventType.PAYMENT_FAILED, this::onPaymentFailed);
eventBus.subscribe(EventType.INVENTORY_FAILED, this::onInventoryFailed);
eventBus.subscribe(EventType.PAYMENT_REFUNDED, this::onPaymentRefunded);
}
public Order createOrder(String customerId, String productId, int quantity, double amount) {
Order order = new Order(UUID.randomUUID().toString(), customerId, productId, quantity, amount);
orders.put(order.getId(), order);
eventBus.publish(new Event(EventType.ORDER_CREATED, order.getId(), Map.of(
"customerId", customerId,
"productId",productId,
"quantity", quantity,
"amount", amount
)));
return order;
}
private void onInventoryReserved(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.CONFIRMED);
}
private void onPaymentFailed(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.PAYMENT_FAILED);
eventBus.publish(new Event(EventType.ORDER_CANCELLED, event.getOrderId(),
Map.of("reason", "Payment declined")));
}
private void onInventoryFailed(Event event) {
orders.get(event.getOrderId()).setStatus(OrderStatus.INVENTORY_FAILED);
// wait for PAYMENT_REFUNDED before cancelling
}
private void onPaymentRefunded(Event event) {
Order order = orders.get(event.getOrderId());
if (order.getStatus() == OrderStatus.INVENTORY_FAILED) {
order.setStatus(OrderStatus.CANCELLED);
eventBus.publish(new Event(EventType.ORDER_CANCELLED, event.getOrderId(),
Map.of("reason", "Inventory unavailable, payment refunded")));
}
}
}
The compensation flow
This is the part most articles skip,because it’s the hard part.
Inventory failure is the interesting case. Payment already succeeded when inventory reports back. Money has left the customer’s account. You can’t just cancel the order and walk away.
Here is what actually happens step by step when product-B is out of stock:
[EventBus] ORDER_CREATED → orderId=abc123
[PaymentService] Charged $99.00 from customer-1
[EventBus] PAYMENT_PROCESSED → orderId=abc123
[InventoryService] FAILED: 0 units of product-B
[EventBus] INVENTORY_FAILED → orderId=abc123
[PaymentService] COMPENSATING: refunded $99.00 to customer-1
[EventBus] PAYMENT_REFUNDED → orderId=abc123
[OrderService] Order abc123 → CANCELLED (refund confirmed)
[EventBus] ORDER_CREATED → orderId=abc123
[PaymentService] Charged $99.00 from customer-1
[EventBus] PAYMENT_PROCESSED → orderId=abc123
[InventoryService] FAILED: 0 units of product-B
[EventBus] INVENTORY_FAILED → orderId=abc123
[PaymentService] COMPENSATING: refunded $99.00 to customer-1
[EventBus] PAYMENT_REFUNDED → orderId=abc123
[OrderService] Order abc123 → CANCELLED (refund confirmed)
PaymentService subscribes to INVENTORY_FAILED and issues the refund:
private void onInventoryFailed(Event event) {
String orderId = event.getOrderId();
Double amount = processedPayments.remove(orderId);
String customer = paymentCustomer.remove(orderId);
if (amount != null && customer != null) {
balances.merge(customer, amount, Double::sum);
eventBus.publish(new Event(EventType.PAYMENT_REFUNDED, orderId,
Map.of("amount", amount, "customerId", customer)));
}
}
private void onInventoryFailed(Event event) {
String orderId = event.getOrderId();
Double amount = processedPayments.remove(orderId);
String customer = paymentCustomer.remove(orderId);
if (amount != null && customer != null) {
balances.merge(customer, amount, Double::sum);
eventBus.publish(new Event(EventType.PAYMENT_REFUNDED, orderId,
Map.of("amount", amount, "customerId", customer)));
}
}
The customer gets their money back. The order is cancelled. No human intervention. No 3am incident.
The strength of choreography is the loose coupling. PaymentService doesn’t know OrderService exists. InventoryService doesn’t know PaymentService exists. Each service only knows the events it cares about. You can add a new service to the flow without touching any existing code.
The weakness is that the full saga flow lives nowhere. It is distributed across event handlers in three separate services. When something goes wrong in production and you need to trace exactly what happened to order abc123, you are reading logs from three systems and reconstructing the timeline in your head. That debugging experience is genuinely painful.
Pattern 3: Saga Orchestrator
The orchestrator flips the model. Instead of services reacting to each other, a central orchestrator tells each service what to do and tracks the state machine explicitly.
public enum SagaState {
STARTED,
PAYMENT_PENDING,
PAYMENT_COMPLETED,
INVENTORY_PENDING,
INVENTORY_RESERVED,
COMPLETED,
// Compensation states - these are the undo path
COMPENSATING_PAYMENT,
PAYMENT_COMPENSATED,
FAILED
}
public enum SagaState {
STARTED,
PAYMENT_PENDING,
PAYMENT_COMPLETED,
INVENTORY_PENDING,
INVENTORY_RESERVED,
COMPLETED,
// Compensation states - these are the undo path
COMPENSATING_PAYMENT,
PAYMENT_COMPENSATED,
FAILED
}
The orchestrator runs the entire flow and handles compensation in explicit order:
public Order execute(String customerId, String productId, int quantity, double amount) {
Order order = orderService.createOrder(customerId, productId, quantity, amount);
transitionTo(SagaState.PAYMENT_PENDING);
if (!paymentService.processPayment(order.getId(), customerId, amount)) {
transitionTo(SagaState.FAILED);
orderService.cancelOrder(order.getId(), "Payment failed");
return order;
}
transitionTo(SagaState.PAYMENT_COMPLETED);
transitionTo(SagaState.INVENTORY_PENDING);
if (!inventoryService.reserveInventory(order.getId(), productId, quantity)) {
// Payment succeeded but inventory failed. Compensate.
transitionTo(SagaState.COMPENSATING_PAYMENT);
paymentService.refundPayment(order.getId());
transitionTo(SagaState.PAYMENT_COMPENSATED);
transitionTo(SagaState.FAILED);
orderService.cancelOrder(order.getId(), "Inventory unavailable");
return order;
}
transitionTo(SagaState.INVENTORY_RESERVED);
orderService.confirmOrder(order.getId());
transitionTo(SagaState.COMPLETED);
return order;
}
public Order execute(String customerId, String productId, int quantity, double amount) {
Order order = orderService.createOrder(customerId, productId, quantity, amount);
transitionTo(SagaState.PAYMENT_PENDING);
if (!paymentService.processPayment(order.getId(), customerId, amount)) {
transitionTo(SagaState.FAILED);
orderService.cancelOrder(order.getId(), "Payment failed");
return order;
}
transitionTo(SagaState.PAYMENT_COMPLETED);
transitionTo(SagaState.INVENTORY_PENDING);
if (!inventoryService.reserveInventory(order.getId(), productId, quantity)) {
// Payment succeeded but inventory failed. Compensate.
transitionTo(SagaState.COMPENSATING_PAYMENT);
paymentService.refundPayment(order.getId());
transitionTo(SagaState.PAYMENT_COMPENSATED);
transitionTo(SagaState.FAILED);
orderService.cancelOrder(order.getId(), "Inventory unavailable");
return order;
}
transitionTo(SagaState.INVENTORY_RESERVED);
orderService.confirmOrder(order.getId());
transitionTo(SagaState.COMPLETED);
return order;
}
When inventory fails, the compensation is explicit and in order. The orchestrator knows exactly what succeeded and calls paymentService.refundPayment() directly. No events, no subscriptions, no hoping the right service heard the right message.
[Orchestrator] State: STARTED → PAYMENT_PENDING
[PaymentService] Charged $99.00 from customer-1
[Orchestrator] State: PAYMENT_PENDING → PAYMENT_COMPLETED
[Orchestrator] State: PAYMENT_COMPLETED → INVENTORY_PENDING
[InventoryService] REFUSED: 0 units of product-B available
[Orchestrator] Inventory failed. Starting COMPENSATION...
[Orchestrator] State: INVENTORY_PENDING → COMPENSATING_PAYMENT
[PaymentService] COMPENSATING: refunded $99.00 to customer-1
[Orchestrator] State: COMPENSATING_PAYMENT → PAYMENT_COMPENSATED
[Orchestrator] State: PAYMENT_COMPENSATED → FAILED
[OrderService] Order → CANCELLED (Inventory unavailable)
[Orchestrator] Saga FAILED. Compensation complete.
[Orchestrator] State: STARTED → PAYMENT_PENDING
[PaymentService] Charged $99.00 from customer-1
[Orchestrator] State: PAYMENT_PENDING → PAYMENT_COMPLETED
[Orchestrator] State: PAYMENT_COMPLETED → INVENTORY_PENDING
[InventoryService] REFUSED: 0 units of product-B available
[Orchestrator] Inventory failed. Starting COMPENSATION...
[Orchestrator] State: INVENTORY_PENDING → COMPENSATING_PAYMENT
[PaymentService] COMPENSATING: refunded $99.00 to customer-1
[Orchestrator] State: COMPENSATING_PAYMENT → PAYMENT_COMPENSATED
[Orchestrator] State: PAYMENT_COMPENSATED → FAILED
[OrderService] Order → CANCELLED (Inventory unavailable)
[Orchestrator] Saga FAILED. Compensation complete.
Every transition is logged. The saga state is queryable at any time. If the orchestrator restarts mid-saga, it can resume from the last known state rather than starting over.
The trade-off: the orchestrator is now the single point of failure and the single point of knowledge. It must be highly available, and it needs persistence so it can recover if it crashes mid-saga. You traded distributed complexity for centralised complexity.
Choreography distributes complexity. Orchestration centralises it. Neither is universally better. The right choice depends on how complex your flow is and how much you value observability over loose coupling.
Now Here’s What Nobody Tells You
Here’s the thing both patterns above have in common,and what breaks them in production even when your tests pass.
Both choreography and orchestration require two things to happen at the same moment:
- Write the business data to your database
- Publish the event to start the next step
These are two separate operations on two separate systems. What happens when the first succeeds and the second fails?
// THE BROKEN WAY - and most people write exactly this
public Order createOrder(String customerId, String productId, int quantity, double amount) {
Order order = new Order(...);
orders.put(order.getId(), order); // DB write succeeds
eventBus.publish(new Event(...)); // network hiccup, fails
// Order is in DB. Event never sent. Saga never starts. Silent data loss.
}
// THE BROKEN WAY - and most people write exactly this
public Order createOrder(String customerId, String productId, int quantity, double amount) {
Order order = new Order(...);
orders.put(order.getId(), order); // DB write succeeds
eventBus.publish(new Event(...)); // network hiccup, fails
// Order is in DB. Event never sent. Saga never starts. Silent data loss.
}
The order exists in the database. The customer sees it in their order history. But payment was never charged. Inventory was never reserved. The saga never started. There is no error anywhere. No alert fires. No log entry stands out. Just a broken order sitting quietly in the database until a customer complains.
This is called the dual-write problem. You cannot atomically write to a database and publish to a message broker in the same operation without a distributed transaction,which is the exact thing you were trying to avoid. Most Saga tutorials stop before this point. That is a mistake.
Pattern 4: The Transactional Outbox
The outbox pattern solves the dual-write problem by removing it entirely. Instead of writing to the database and then publishing an event, you write the event into the database alongside your business data, in the same transaction. A separate background process handles publishing.
public synchronized Order createOrder(String customerId, String productId,
int quantity, double amount) {
// ── BEGIN DB TRANSACTION ───────────────────────────────────────────
Order order = new Order(UUID.randomUUID()
.toString(), customerId, productId, quantity, amount);
// Write 1: Business data → orders table
orders.put(order.getId(), order);
// Write 2: Event → outbox table (SAME TRANSACTION)
OutboxEvent outboxEvent = new OutboxEvent(
UUID.randomUUID().toString(),
order.getId(),
EventType.ORDER_CREATED.name(),
buildPayload(order),
Instant.now()
);
outboxRepository.save(outboxEvent);
// ── COMMIT TRANSACTION ────────────────────────────────────────────
// We do NOT publish here. The OutboxPublisher handles that.
return order;
}
public synchronized Order createOrder(String customerId, String productId,
int quantity, double amount) {
// ── BEGIN DB TRANSACTION ───────────────────────────────────────────
Order order = new Order(UUID.randomUUID()
.toString(), customerId, productId, quantity, amount);
// Write 1: Business data → orders table
orders.put(order.getId(), order);
// Write 2: Event → outbox table (SAME TRANSACTION)
OutboxEvent outboxEvent = new OutboxEvent(
UUID.randomUUID().toString(),
order.getId(),
EventType.ORDER_CREATED.name(),
buildPayload(order),
Instant.now()
);
outboxRepository.save(outboxEvent);
// ── COMMIT TRANSACTION ────────────────────────────────────────────
// We do NOT publish here. The OutboxPublisher handles that.
return order;
}
Both writes are in the same transaction. Either both succeed or neither does. There is no window where the order exists but the event does not. The dual-write problem is gone because there is only one write target: the database.
The OutboxPublisher runs as a separate background thread, polling for unpublished events:
<button data-code="private void publishPending() {
List unpublished = outboxRepository.findUnpublished();
for (OutboxEvent outboxEvent : unpublished) {
try {
EventType type = EventType.valueOf(outboxEvent.getEventType());
eventBus.publish(new Event(type, outboxEvent.getAggregateId(), …));
outboxRepository.markPublished(outboxEvent.getId());
} catch (Exception e) {
// Publishing failed. Event stays unpublished.
// Next poll retries it. At-least-once delivery.
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
private void publishPending() {
List<OutboxEvent> unpublished = outboxRepository.findUnpublished();
for (OutboxEvent outboxEvent : unpublished) {
try {
EventType type = EventType.valueOf(outboxEvent.getEventType());
eventBus.publish(new Event(type, outboxEvent.getAggregateId(), ...));
outboxRepository.markPublished(outboxEvent.getId());
} catch (Exception e) {
// Publishing failed. Event stays unpublished.
// Next poll retries it. At-least-once delivery.
}
}
}
private void publishPending() {
List<OutboxEvent> unpublished = outboxRepository.findUnpublished();
for (OutboxEvent outboxEvent : unpublished) {
try {
EventType type = EventType.valueOf(outboxEvent.getEventType());
eventBus.publish(new Event(type, outboxEvent.getAggregateId(), ...));
outboxRepository.markPublished(outboxEvent.getId());
} catch (Exception e) {
// Publishing failed. Event stays unpublished.
// Next poll retries it. At-least-once delivery.
}
}
}
If publishing fails, the event stays in the outbox with published = false. The next poll picks it up and tries again. This gives you at-least-once delivery: the event will eventually reach its destination, possibly more than once.
At-least-once delivery means your event consumers must be idempotent. If ORDER_CREATED arrives twice, processing it a second time must produce the same result as the first. In practice this means checking whether you have already processed an event before acting on it, typically with a deduplication table keyed on the event ID.
In production the outbox publisher is usually one of:
- A polling job within the same service checking for unpublished rows every few seconds
- A CDC connector like Debezium reading the database write-ahead log directly and publishing to Kafka with no polling delay
The CDC approach is cleaner. Debezium reads PostgreSQL’s WAL and publishes every outbox insert to Kafka automatically. No polling interval, no code to maintain, no delay.
What Each Pattern Actually Gives You
2PC gives strong consistency. Every participant commits or rolls back together. The price is availability: blocking protocol, coordinator is a single point of failure, and a crashed coordinator leaves the system inconsistent with no automatic recovery.
Saga Choreography gives loose coupling and availability. No single point of failure. Services evolve independently. The price is observability: the saga flow is spread across services, state is implicit in event sequences, and debugging requires correlating logs across systems.
Saga Orchestrator gives explicit state and clear compensation order. The full flow is readable in one place. The price is coupling: services depend on the orchestrator, which must be fault-tolerant and persistent.
Outbox is not an alternative to Sagas. It is the reliability layer underneath them. Use it with either approach or your saga has a silent failure mode in production.
Choreography is genuinely the better choice when your flow is simple, your services are few, and you don’t need a human to read the whole saga in one place. The debugging pain only becomes real at scale or when the compensation logic gets complex. For a two-step saga with one compensation path, choreography is cleaner, simpler, and has fewer moving parts than standing up an orchestrator.
The most common production setup is an orchestrator-based Saga with an outbox for event publishing. The orchestrator state is persisted to a database so it survives restarts. Events go to the outbox in the same transaction as saga state updates. A CDC connector delivers them to Kafka. That combination gives you explicit state, reliable delivery, and automatic recovery, without the consistency problems of 2PC.
Running the Code
# all 20 tests across all four patterns
mvn test
# the full demo - all patterns running sequentially with printed output
mvn compile exec:java
# all 20 tests across all four patterns
mvn test
# the full demo - all patterns running sequentially with printed output
mvn compile exec:java
The demo output makes the differences visible. 2PC shows the coordinator crash mid-commit and prints explicitly that the database is inconsistent. Choreography shows events flowing between services with no central control. Orchestrator shows the state machine transitioning through every step with compensation firing in explicit reverse order. Outbox shows the two-step process: atomic write to the database, then background publish.
The full code for all four patterns is on GitHub: [link]
GitHub – shan305/distributed-transactions: Distributed transaction patterns in Java : 2PC…
Distributed transaction patterns in Java : 2PC, choreography saga, orchestrator saga, and outbox pattern. …
Published under Systems Engineering. More articles on building real things in Java.


