Course contentsShow
← Databases & SQL
Lesson 1924 of 1,95318. Application Integration PatternsFree lesson

Distributed Transaction Coordination

Explain the complexities of the Two-Phase Commit protocol and why modern systems prefer Sagas for consistency.

In this lesson, you will learn why distributed systems often abandon strict atomic transactions in favor of more resilient, asynchronous patterns.

The Two-Phase Commit (2PC) Bottleneck

When you need to update data across multiple independent databases, you might be tempted to use Two-Phase Commit (2PC). In 2PC, a central coordinator asks every participant to "prepare" (lock their records and promise to commit). If all respond with a "yes," the coordinator sends a "commit" command.

The complexity arises because 2PC is a blocking protocol. If a participant fails after promising to commit but before receiving the final command, that participant must keep those database rows locked indefinitely to maintain consistency. In a distributed environment, this leads to:

  • High Latency: Every participant must be online and responsive simultaneously.
  • Tight Coupling: The system is only as available as its slowest or most unstable node.
  • Deadlock Risks: Holding locks across networks significantly increases the probability of cross-service deadlocks.

Why Sagas Replace 2PC

Modern distributed systems prioritize availability over immediate consistency, moving toward the Saga Pattern. Instead of one giant, atomic transaction, a Saga breaks the operation into a sequence of local transactions.

If one step in the sequence fails, the system executes compensating transactions to undo the changes made by previous steps. For example, if an "Order Service" completes but the "Inventory Service" fails, the Saga triggers a local command to revert the order status.

-- Conceptual Saga Flow:
-- 1. Local Transaction: Deduct funds
-- 2. Local Transaction: Reserve items
-- 3. If Step 2 fails, execute Compensating Transaction:
UPDATE accounts SET balance = balance + 100 WHERE account_id = 'user_1';

Because Sagas do not hold global locks, they are significantly more performant and resilient to network partitions. However, they trade off "Atomicity" for "Eventual Consistency," meaning that for a brief window, your system state might look incomplete to an end user. Accepting this trade-off is the hallmark of scaling database systems beyond a single monolithic instance.

Key Takeaway: While Two-Phase Commit offers strict consistency, its blocking nature makes it unsuitable for distributed microservices; Sagas provide a more resilient, non-blocking alternative by managing failures through explicit compensation logic.