Course contentsShow
← Cloud and Infrastructure
Lesson 2527 of 2,98954. Serverless ArchitecturesFree lesson

Saga Pattern in Serverless

Implementing distributed transaction patterns with compensating actions for eventual consistency.

Saga Pattern in Serverless

You'll learn how to implement distributed transactions across serverless functions using compensating actions for eventual consistency.

When building serverless workflows that span multiple services (databases, APIs, payment systems), you can't rely on traditional database transactions. The Saga Pattern breaks a distributed transaction into a series of local transactions, each with a compensating action that can undo its work if something fails downstream.

How It Works

Imagine booking a vacation: reserve flight → reserve hotel → charge payment. If payment fails, you need to cancel the hotel and flight reservations automatically.

In serverless, each step is a separate Lambda or function invocation. The saga orchestrator (like Step Functions) tracks progress. If step 3 fails, it triggers compensating actions in reverse order: refund → cancel hotel → cancel flight.

There are two approaches:

Choreography: Each function publishes events that trigger the next step or compensating action. No central coordinator, but harder to track overall state.

Orchestration: A state machine (Step Functions) explicitly defines the forward path and compensation path. Clearer visibility, easier debugging—this is the serverless default.

Implementation Pattern

Your state machine defines both success transitions and error handlers. When a task fails, the error handler invokes the compensating function for each completed step. The saga maintains a log of completed steps so it knows which compensations to run.

Unlike synchronous transactions that lock resources, sagas embrace eventual consistency—the system may be temporarily inconsistent but will settle into a correct state.

Key Takeaway: The Saga Pattern enables reliable distributed transactions in serverless by chaining local transactions with compensating actions, coordinated through workflow orchestrators for eventual consistency.