Saga Pattern for Distributed Transactions
What you'll learn: How to maintain data consistency across multiple serverless functions without traditional distributed transactions.
In serverless architectures, you can't use traditional database transactions that span multiple services. The Saga pattern breaks a long-running business transaction into a sequence of local transactions, each handled by a different service or function. If one step fails, the saga executes compensating transactions to undo the work of previous steps.
Core Concept
Think of booking a vacation: you reserve a flight, then a hotel, then a car. If the car rental fails, you need to cancel the hotel and flight. That's a saga with compensating actions.
Each step in a saga:
- Performs its local transaction
- Publishes an event or triggers the next step
- Maintains a record of what it did (for potential rollback)
If any step fails, the saga executes compensating transactions in reverse order to "undo" completed steps.
Two Coordination Styles
Choreography: Services listen for events and react independently. The flight service publishes "FlightBooked," the hotel service listens and books a room.
Orchestration: A central coordinator (like Step Functions from your previous lesson) directs each step explicitly and manages compensations.
Compensating Actions
These aren't true rollbacks—they're business operations that semantically undo previous work. For a payment, the compensation might be a refund. For an inventory reservation, it's releasing the hold.
Key Takeaway: The Saga pattern enables distributed data consistency in serverless systems by chaining local transactions with compensating actions for rollback, ensuring eventual consistency without requiring distributed locks or two-phase commits.