Lesson 03: Microservices

The Saga Pattern

Because Two-Phase Commit locks databases and degrades performance, modern architectures like Microservices use The Saga Pattern.

In a Saga, there is no global transaction. There are no global locks. Instead, a long-running business process is broken down into a series of local, independent transactions. If one of the steps fails, the system runs Compensating Transactions to undo the work of the previous steps.

Eventual Consistency

Imagine booking a vacation. You need a Flight, a Hotel, and a Rental Car. In a Saga, the orchestrator tells the Flight Service to book the flight. The Flight Service books it locally, commits to its own database immediately (releasing its locks), and replies "Success". Then the orchestrator moves to the Hotel, and so on.

What happens if the Car Service fails (e.g. no cars available)? The orchestrator can't "rollback" a database transaction, because the Flight and Hotel were already committed! Instead, the orchestrator must send brand new requests: "Cancel Flight" and "Cancel Hotel".

Saga Orchestrator Simulator

Watch the Orchestrator book the trip sequentially. Click "Force Car to Fail" to see how the system handles a failure using Compensating Transactions.

Saga Orchestrator
Waiting to start...
โœˆ๏ธ Flight DB
Empty
๐Ÿจ Hotel DB
Empty
๐Ÿš— Car DB
Will Succeed
(Click to toggle)
System is idle.

The Trade-off

The Saga pattern is highly scalable because no locks are held across the network. However, it introduces Eventual Consistency.

For a brief window of time, the system is inconsistent. If the user checked their account after the Flight was booked but before the Car failed, they would see a partially booked vacation. The application code must be written to handle this intermediate state gracefully.

Check yourself

1. How does the Saga Pattern handle a failure in the middle of a distributed workflow?

Because Sagas don't use global locks, previous steps are already committed. The only way to "rollback" is to issue brand new requests that perform the inverse action (e.g. Canceling a booked flight).