Distributed Transactions and Data Consistency
🎯 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:
| Time | Payment record | Order record | Acceptable? |
|---|---|---|---|
| Before payment | Awaiting payment | Awaiting payment | Yes |
| Immediately after payment succeeds | Successful | Awaiting payment | Temporarily |
| After orders handles the payment event | Successful | Paid | Expected 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.
To track progress, orders can use these states:
| Order state | Meaning |
|---|---|
PENDING_RESERVATION | Order created; waiting for the reservation outcome |
PENDING_PAYMENT | Stock reserved; waiting for payment |
PAYMENT_UNKNOWN | No definitive payment outcome; cannot treat it as failure yet |
PAID | Payment success confirmed |
CANCELLING | Cannot proceed; releasing reserved stock |
CANCELLED | Cancellation 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:
| Situation | Action |
|---|---|
| Stock is definitively insufficient | Cancel the order; no successful reservation needs releasing |
| Stock reserved, payment definitively failed | Release that reservation, then finish cancellation |
| Payment succeeded, order update failed | Preserve the payment fact and recover the order update; do not cancel |
| Inventory or payment request timed out; outcome unknown | Pause 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.
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:
| Stage | available quantity | reserved quantity |
|---|---|---|
| Before reservation | 10 | 0 |
| After reserving 2 units | 8 | 2 |
| After definitive payment failure and successful release | 10 | 0 |
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:
| Comparison | Orchestration | Choreography |
|---|---|---|
| Who chooses the next step | A coordinator schedules actions from current state | Services react to business events |
| Order example | Orders coordinates inventory, payment, and cancellation | Inventory, payments, and orders connect the flow through events |
| Benefit | Central flow makes failure paths easier to understand | Event-based collaboration reduces central flow control |
| Main challenge | Coordination state must persist and support recovery | Event 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:
- Name the order state and explain why it cannot immediately become
CANCELLED. - List the next actions when payment queries return success, definitive failure, or an unknown outcome.
- If stock release also times out after payment fails, explain how to prevent duplicate release.
- 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.
Business Events
Publish business events reliably with MySQL transactions and the transactional outbox pattern, and prevent repeated order updates with idempotent consumers.
Fault Tolerance and Reliability
Use order-to-inventory calls to learn timeouts, bounded retries, circuit breakers, isolation, and graceful degradation, preventing downstream failures from spreading.
