Transactions across services
Think of planning a trip: you book a flight, a hotel and a car, each with a different company. There’s no button that books all three or none. If the car isn’t available, you cancel the hotel and the flight yourself. That’s a saga: several separate steps, plus a plan for undoing the earlier ones.
For an order:
- Order service: create the order as
PENDING. - Payment service: charge the card. Undo: refund.
- Inventory service: reserve the items. Undo: release them.
- Order service: mark the order
CONFIRMED.
If step 3 fails, the saga runs the undo steps for what already happened, in reverse: refund the payment, then mark the order CANCELLED.
Two important ideas:
- Undo is a new action, not a time machine. The refund is a real transaction the customer sees on their statement. An email that was sent can’t be unsent; you send another one.
- “In progress” is a real state. Between the steps, the order is
PENDING. The app shows it, and other code must handle it.
Distributed transactions (2PC/XA) couple the availability of all participants, hold locks across network calls and aren’t supported by most brokers and cloud databases, so microservices use sagas: a sequence of local ACID transactions, each emitting a message that triggers the next, with compensating transactions for steps that can be semantically undone. Sagas give up isolation: other transactions see intermediate states, so design with semantic locks (status fields like PENDING that other operations respect), commutative updates, re-reading values, and ordering steps so that pivot steps (the point of no return, such as a capture) come after compensatable ones and before retriable ones. Coordination styles: choreography (each service reacts to events; simple for two or three steps, but the flow is implicit and cyclic dependencies creep in) and orchestration (a coordinator sends commands and tracks state; explicit, testable, easier to change and to observe). Both rely on the transactional outbox for atomic state-change-plus-message and on idempotent handlers, since delivery is at least once.
// Payment service
@KafkaListener(topics = ["orders"])
fun onOrderPlaced(event: OrderPlaced) {
payments.charge(event.orderId, event.total) // local transaction + outbox: PaymentSucceeded or PaymentFailed
}
// Inventory service
@KafkaListener(topics = ["payments"])
fun onPaymentSucceeded(event: PaymentSucceeded) {
inventory.reserve(event.orderId, event.items) // StockReserved or StockUnavailable
}
// Payment service again: the compensation
@KafkaListener(topics = ["inventory"])
fun onStockUnavailable(event: StockUnavailable) {
payments.refund(event.orderId) // PaymentRefunded
}
// Order service: follows all of them to update the order's status
@KafkaListener(topics = ["payments", "inventory"])
fun onSagaEvent(event: OrderSagaEvent) {
orders.apply(event) // PENDING → CONFIRMED or CANCELLED
}// Payment service
@KafkaListener(topics = "orders")
void onOrderPlaced(OrderPlaced event) {
payments.charge(event.orderId(), event.total()); // local transaction + outbox: PaymentSucceeded or PaymentFailed
}
// Inventory service
@KafkaListener(topics = "payments")
void onPaymentSucceeded(PaymentSucceeded event) {
inventory.reserve(event.orderId(), event.items()); // StockReserved or StockUnavailable
}
// Payment service again: the compensation
@KafkaListener(topics = "inventory")
void onStockUnavailable(StockUnavailable event) {
payments.refund(event.orderId()); // PaymentRefunded
}
// Order service: follows all of them to update the order's status
@KafkaListener(topics = {"payments", "inventory"})
void onSagaEvent(OrderSagaEvent event) {
orders.apply(event); // PENDING → CONFIRMED or CANCELLED
}- Nobody is “in charge”: each service listens for the event that concerns it, does its local work, and publishes the result.
refundis the compensation forcharge. It runs when inventory reports that the items aren’t available.- The order service listens to everything and moves the order from
PENDINGtoCONFIRMEDorCANCELLED, which is what the customer sees.
This works well for short flows. With more steps, the flow is spread across many listeners, and it gets hard to answer “what happens if…?”. That’s where orchestration (next part) helps.
Predict the output
In the choreography above, the inventory service publishes StockUnavailable, but the payment service is down for 10 minutes. What does the customer's order look like during those 10 minutes, and what happens after?
The event waits in Kafka until the payment service consumes it. Meanwhile the system is in an intermediate state: charged but not confirmed. That's normal in a saga, and why PENDING must be a visible, handled state (the app shows 'processing'). Nothing is lost, because the event is durable and the consumer commits its offset only after the refund is done.
Tap the line with the bug.
@KafkaListener(topics = ["inventory"])
fun onStockUnavailable(event: StockUnavailable) {
val payment = payments.findByOrderId(event.orderId)
paymentProvider.refund(payment.chargeId, payment.amount)
payment.markRefunded()
payments.save(payment)
}@KafkaListener(topics = "inventory")
void onStockUnavailable(StockUnavailable event) {
Payment payment = payments.findByOrderId(event.orderId());
paymentProvider.refund(payment.chargeId(), payment.amount());
payment.markRefunded();
payments.save(payment);
}Hint: Kafka delivers at least once. What if the same event arrives twice?
If the service crashes after the refund but before the offset is committed, or the event is simply delivered twice, the handler calls the provider again and refunds the customer twice. Compensations must be idempotent, like every other step.
Check the state first, and give the provider an idempotency key so even a retried call can’t refund twice:
if (payment.isRefunded) return // already compensated
paymentProvider.refund(payment.chargeId, payment.amount, idempotencyKey = "refund-${payment.id}")if (payment.isRefunded()) return; // already compensated
paymentProvider.refund(payment.chargeId(), payment.amount(), "refund-" + payment.id());Designing the steps
- Order matters: compensatable steps first (reserve stock, authorize the card), the pivot (capture the payment, ship) next, and only steps that can’t fail for business reasons (send email, add loyalty points; retried until they succeed) after it.
- Prefer reservations to irreversible actions: authorize then capture, reserve then commit stock. A reservation with an expiry is a compensation that happens by itself.
- Isolation anomalies: a second saga can read stock reserved by a saga that will later be compensated. Use semantic locks (
RESERVED,PENDING), re-check at the pivot, and design counters to tolerate commutative updates. - Compensations can fail too: they must be retried until they succeed (with alerts), or escalate to a manual queue with full context.
- Saga = local transactions + messages + compensations; no 2PC. Delivery is at least once: every step and compensation is idempotent; state change + message via the outbox.
- No isolation: intermediate states are visible; semantic locks (
PENDING,RESERVED), re-checks at the pivot. - Step order: compensatable → pivot → retriable. Prefer reservations (authorize/capture, reserve/commit) with expiry.
- Choreography for short flows; orchestration when flows grow, need timeouts, or must be observable and changeable.
Check this part
What is a compensating action?
Why must PENDING be a real, visible order state?
Why are sagas used instead of two-phase commit between services?
Where should the pivot step (the point of no return) go?