Course contentsShow
← System Design
Lesson 597 of 1,91916. Distributed TransactionsFree lesson

Saga State Management and Persistence

How saga coordinators persist execution state to ensure recovery and exactly-once semantics across failures.

Saga State Management and Persistence

What you'll learn: How saga coordinators track execution progress and survive failures to ensure exactly-once guarantees.

The Reliability Challenge

A saga consists of multiple local transactions that may take hours or days to complete across distributed services. If the orchestrator crashes mid-saga, you need to know exactly where you were: which steps completed, which failed, which compensations fired. Without durable state management, a restart could retry completed steps (causing duplicate charges) or skip failed compensations (leaving inconsistent data).

Persisting Saga State

Saga coordinators must write state to durable storage before and after each step. Think of it like a detailed GPS log: before you turn left, you record "about to turn left at Oak Street." After turning, you record "completed turn, now heading north."

The persisted state includes:

  • Current step index in the saga sequence
  • Execution status of each transaction (pending, completed, failed, compensated)
  • Correlation IDs linking requests to saga instances
  • Input/output data from each step for idempotency checks
  • Compensation stack tracking which rollbacks to execute if failure occurs

Recovery After Failure

When an orchestrator restarts, it:

  1. Loads incomplete sagas from persistent storage
  2. Checks the last recorded state for each saga
  3. Resumes from the exact step that was in-flight
  4. Uses idempotency tokens to safely retry operations without duplicates

This enables exactly-once semantics: each local transaction executes once, even across coordinator crashes.

Storage Options

Coordinators typically use databases (PostgreSQL, MongoDB) or event stores with strong durability guarantees. Each state transition is written atomically before invoking the next service.

Key Takeaway:
Saga coordinators persist execution state at every step to enable crash recovery and guarantee exactly-once processing, turning a fragile multi-step workflow into a reliable distributed transaction.