Course contentsShow
← Databases & SQL
Lesson 1724 of 1,95316. Distributed Data ArchitecturesFree lesson

Saga Pattern for Distributed Transactions

Implement a sequence of local transactions with compensating logic to maintain atomicity across services.

In this lesson, you will learn how to maintain data consistency across distributed services without relying on traditional, resource-heavy global transactions.

When your data is partitioned across multiple shards or independent microservices, you cannot use a single BEGIN TRANSACTION block to wrap operations. If an operation fails on the third service, you cannot perform a standard ROLLBACK on the first two because they have already committed their local changes.

The Saga Pattern solves this by breaking a distributed transaction into a sequence of local transactions. Each local transaction updates the database and publishes an event or message to trigger the next step. Crucially, for every forward operation, you must define a compensating transaction—a logic block designed to undo the changes if a subsequent step fails.

Conceptual Workflow: The Order Example

Imagine an order processing system where Service A reserves inventory and Service B processes the payment.

  1. Service A (Inventory): Decrement stock. If successful, trigger Service B.
  2. Service B (Payment): Attempt to charge the customer.
    • If payment succeeds, finish.
    • If payment fails, trigger the Compensating Transaction in Service A.
  3. Compensating Logic (Service A): Increment the stock back to the original count.
-- Service A: Local Transaction
BEGIN;
UPDATE inventory SET stock = stock - 1 WHERE item_id = 123;
-- Commit here is mandatory to release the row lock
COMMIT; 

-- If Payment fails later, we trigger this in Service A:
BEGIN;
UPDATE inventory SET stock = stock + 1 WHERE item_id = 123;
COMMIT;

Because each step commits locally, the system remains responsive and avoids long-lived locks that would otherwise create hotspots in your sharded infrastructure. However, note that during the interim, other users might see "dirty reads"—the system is eventually consistent, not immediately consistent. Your application logic must be designed to handle the fact that a partial state might exist for a few milliseconds while the Saga completes.

Key Takeaway: The Saga pattern replaces atomic global transactions with a sequence of local, durable commits paired with compensating logic to ensure data integrity through eventual consistency.