Distributed Transactions and Data Consistency

Understand why cross-service transactions cannot simply roll back together, and learn about Sagas, eventual consistency, compensation, and recovery through orders, inventory, and payments.

🎯 Introduction

The previous article covered reliable event publication and avoiding duplicate processing. But an order involves more than one event: creating the order, reserving stock, and confirming payment belong to different services. What happens if stock is reserved but payment fails? What if payment succeeds but orders temporarily cannot update its state?

This article uses those two situations to explain eventual consistency, Sagas, compensating actions, and failure recovery. We focus on business design without revisiting MySQL transactions or RabbitMQ acknowledgments, or building another Express project.


🧱 Why One MySQL Transaction Cannot Cover the Entire Order Flow

Within one database, a local transaction can commit or roll back several writes together. Here, however, orders, inventory, and payments each own their data and manage their own database.

Suppose this happens:

courseComponents.mermaid.loading

The inventory reservation has already committed and does not automatically roll back when payment fails. Orders cannot undo it by modifying the inventory table directly, because that would violate the data ownership established earlier.

This is not an incorrect SQL statement. Once multiple services have committed local transactions, additional business coordination is needed. The first concern in distributed transactions is making these independent operations eventually produce a valid business outcome.


🔄 Eventual Consistency: Temporary Differences Need a Recovery Path

Consider successful payment. Payments confirms success first, and orders may receive the event later. At a particular moment, their records can differ:

TimePayment recordOrder recordAcceptable?
Before paymentAwaiting paymentAwaiting paymentYes
Immediately after payment succeedsSuccessfulAwaiting paymentTemporarily
After orders handles the payment eventSuccessfulPaidExpected outcome reached

This illustrates eventual consistency: services do not need to update at the same instant, but reliable events, retries, or recovery jobs must bring the business to an allowed final state. The databases do not need identical contents; their records must stop contradicting the outcome of the same business operation. A successful payment should eventually be reflected in a paid order. A definitively failed payment should lead to cancellation and release of reserved stock. An unknown outcome requires further verification, rather than pretending the flow has finished.

Eventual consistency does not mean leaving data alone and expecting it to converge. Persistent event-processing failures must be detected and handled through retries, compensation, or manual intervention. Otherwise, orders can remain incorrect indefinitely.

To track progress, orders can use these states:

Order stateMeaning
PENDING_RESERVATIONOrder created; waiting for the reservation outcome
PENDING_PAYMENTStock reserved; waiting for payment
PAYMENT_UNKNOWNNo definitive payment outcome; cannot treat it as failure yet
PAIDPayment success confirmed
CANCELLINGCannot proceed; releasing reserved stock
CANCELLEDCancellation finished and relevant reservations handled

These states are one teaching design, not a mandatory Saga state set. The essential distinction is that in progress, unknown, and failed are different outcomes.


🛠 Organizing Local Transactions with a Saga

A Saga coordinates a cross-service business flow as a sequence of independently committed local transactions. It defines compensating actions for situations where the flow cannot continue, allowing recovery to a valid business state.

First consider an order where every step succeeds. Each responsible service commits its own local transaction; orders does not start one MySQL transaction spanning three databases:

courseComponents.mermaid.loading

When all four steps succeed, the order completes. The difficult question is: what if an earlier step commits and a later step fails? If stock is reserved but payment definitively fails, orders arranges for inventory to release the original reservation. That subsequent business operation is compensation.

Not every step succeeds in practice. Instead of drawing every exception at once, decide what to do from the operation outcome:

SituationAction
Stock is definitively insufficientCancel the order; no successful reservation needs releasing
Stock reserved, payment definitively failedRelease that reservation, then finish cancellation
Payment succeeded, order update failedPreserve the payment fact and recover the order update; do not cancel
Inventory or payment request timed out; outcome unknownPause and query the original outcome; do not assume failure

For example, when stock is reserved and payment definitively fails, compensation has just two steps:

courseComponents.mermaid.loading

Why not treat timeouts as failures? Inventory may have completed the reservation before its response was lost. Payment may have charged successfully even though its response never arrived. Verify the original outcome before choosing to continue, compensate, or wait to avoid mishandling a valid operation.

If releasing stock also fails, keep the order in CANCELLING and mark it CANCELLED only after release completes.

These states and flows are teaching examples. An endpoint does not automatically support outcome queries. Real projects need queryable reservation and payment-attempt records with corresponding idempotency identifiers to recover safely after timeouts.

Why every step must persist its progress

A Saga can outlast one HTTP request, and its coordinator may restart midway. Its current step cannot live only in a JavaScript variable.

For example, orders can persist the processing state, reservation ID, payment attempt ID, and next action. After restarting, the coordinator reads those records and resumes unfinished steps.

The coordinator can be a workflow component within orders; it need not be another service. Inventory and payment operations still run in their respective services.


⚠️ Compensation Is Not SQL Rollback and Can Also Fail

Suppose inventory initially has 10 available units and reserves 2 for this order:

Stageavailable quantityreserved quantity
Before reservation100
After reserving 2 units82
After definitive payment failure and successful release100

Reserving stock already committed a local transaction. Releasing the reservation is a separate business operation, not a cross-database ROLLBACK. At minimum, release must meet these requirements:

  • Use the original reservation ID, rather than blindly increasing stock by product ID.
  • Repeated release requests for one reservation must release it only once, or stock will be created incorrectly.
  • If release fails, retain a pending state such as CANCELLING; do not claim cancellation is complete.
  • Once payment success is confirmed, an order update failure is not a reason to release stock.

Saga compensation does not guarantee restoring every record as though time had reversed. It performs valid business recovery actions in light of operations that have already occurred.

Why payment timeouts are especially dangerous

After orders calls simulated payments, a network timeout may prevent the response from arriving. Payments may nevertheless have recorded success.

courseComponents.mermaid.loading

Each payment attempt needs a stable idempotency key to prevent retries from causing duplicate charges. We will not repeat the database implementation here. The key point is that a timeout means no answer was received, not that the operation failed.


⚖️ Orchestration and Choreography

Sagas commonly use two approaches:

ComparisonOrchestrationChoreography
Who chooses the next stepA coordinator schedules actions from current stateServices react to business events
Order exampleOrders coordinates inventory, payment, and cancellationInventory, payments, and orders connect the flow through events
BenefitCentral flow makes failure paths easier to understandEvent-based collaboration reduces central flow control
Main challengeCoordination state must persist and support recoveryEvent dependencies and overall progress are harder to track

This course uses orchestration to make the steps and failure branches easier to follow. Neither approach automatically resolves unknown payment outcomes, idempotent compensation, reliable publication, or recovery progress.


❓ Knowledge Check

Q1: Can a Saga make several databases commit together like one MySQL transaction?

No. It coordinates local transactions that commit separately, using subsequent actions or compensation to reach an acceptable outcome. It does not provide atomic commitment and immediate isolation for the entire flow.

Q2: Should an order be canceled if payment succeeds but its status update fails?

Do not cancel it directly. Payment success is a confirmed fact. Persist and recover the step that marks the order paid, with alerts or manual reconciliation when necessary.

Q3: Should a payment timeout trigger stock release?

Not on the timeout alone. Verify payment success first. Keep an unresolved state while the outcome is unknown, so a charged order is not incorrectly canceled.


🧪 Exercise

An order has reserved 2 units, then its simulated payment request times out. Design recovery:

  1. Name the order state and explain why it cannot immediately become CANCELLED.
  2. List the next actions when payment queries return success, definitive failure, or an unknown outcome.
  3. If stock release also times out after payment fails, explain how to prevent duplicate release.
  4. If payment succeeds but the order update fails, explain recovery without incorrect cancellation.

Acceptance criteria: Distinguish definitive failure from unknown outcomes; prevent duplicate charges and stock releases; provide a continuation or manual-intervention path for every temporary failure.


🎉 Congratulations on completing this article! You can now design explicit cross-service states and recovery paths for orders, inventory, and payments.