Home
cd ../playbooks
Developer ToolsAdvanced

Saga Orchestration for Distributed Transactions

Implement the saga pattern for multi-step workflows that span services and can't use a single ACID transaction — choreography vs. orchestration, a step/compensation model with explicit saga states, reverse-order compensation on failure, persisted saga state that survives an orchestrator restart, timeouts, and the idempotency and compensation-testing discipline that makes rollback actually work.

15 minutes
By rmyndharisSource
#saga-pattern#distributed-transactions#microservices#architecture#workflow#distributed-systems

In a distributed workflow there's no ROLLBACK — when the payment step fails after inventory was already reserved, something has to explicitly release that inventory, and the saga pattern is how you make that compensation reliable instead of leaving the system stuck in a half-completed state nobody cleans up.

Who it's for: backend engineers coordinating workflows across microservices, architects designing distributed transactions without a two-phase commit, developers implementing order-fulfillment or booking flows that touch multiple services, teams debugging half-completed distributed state and needing a principled compensation model

Example

"Coordinate reserve-inventory → charge-payment → ship across our services reliably" → An orchestrator that runs each step with its compensation defined up front, flips to COMPENSATING and undoes completed steps in reverse order when payment fails (releasing inventory, refunding), persists saga state so a crashed orchestrator resumes, enforces per-step timeouts, and keeps every step idempotent so retries are safe

CLAUDE.md Template

New here? 3-minute setup guide → | Already set up? Copy the template below.

Or install from your terminal:
npx ccplaybooks add saga-orchestration
# Saga Orchestration

Implement saga patterns for distributed transactions and cross-aggregate workflows. Use when coordinating a multi-step business process across services, handling compensating transactions, or managing long-running workflows that can't rely on a single ACID transaction.

## Core Concepts

A saga is a sequence of local transactions across services; when a step fails, previously completed steps are undone by running their **compensating** actions in reverse. There are two coordination styles:

```
Choreography                     Orchestration
Svc A → Svc B → Svc C            Orchestrator
  │       │       │                 ├── Svc 1

Get new playbooks like this one

One email a week with new Claude Code workflows. Free, like everything here.

No spam. Unsubscribe anytime.

README.md

What This Does

A guide to implementing the saga pattern — the standard way to run a multi-step business process across services when a single ACID transaction isn't possible. It lays out the two coordination styles and when each fits (choreography, where services react to each other's events, for short flows; orchestration, where a central coordinator explicitly drives every step and its undo, once a saga grows past a few steps), with an explicit state model (Started → Pending → Compensating → Completed/Failed). The core is a step-plus-compensation model: every step that has a side effect defines the compensating action that reverses it, and on failure the orchestrator runs the completed steps' compensations in reverse order rather than leaving the system in a half-done state.

It covers the mechanics that make a saga production-grade: persisting saga state after each transition so a crashed orchestrator resumes where it stopped (sagas are long-running and must survive restarts), per-step timeouts so a stuck step compensates instead of hanging forever, a worked order-fulfillment example (reserve inventory → charge payment → ship, each with its compensation), and the choreography variant with correlation IDs for tracing a flow that has no central coordinator. The do's and don'ts target the parts teams get wrong: non-idempotent steps that break on retry, compensations that don't actually undo, synchronous service coupling, and — most of all — shipping the rollback path untested, since it's the most critical and least-exercised code in the whole saga.


Quick Start

Step 1: Create a Project Folder

mkdir saga-orchestration && cd saga-orchestration

Step 2: Download the Template

Click Download above, then:

mv ~/Downloads/CLAUDE.md ./

Step 3: Design Your Saga

claude

Describe the cross-service workflow you need to coordinate. Claude will choose choreography or orchestration, define each step with its compensation, wire up reverse-order rollback, state persistence, and timeouts, and keep every step idempotent for safe retries.


Tips & Best Practices

  • Write and test every compensation as carefully as its forward action — the rollback path is the entire point of a saga and the part that's almost never exercised in normal operation, so it's where latent bugs hide until the worst moment.
  • Make each step idempotent from the start; the orchestrator retries on transient failures, and a step that double-charges or double-ships on a retry is a far worse failure than the one it was recovering from.
  • Persist saga state on every transition — treating the saga as in-memory state that a restart can lose turns a recoverable partial failure into an orphaned, half-completed workflow.

Limitations

  • Sagas provide eventual consistency and atomicity-via-compensation, not true isolation — intermediate states are visible to other readers, so a flow that genuinely needs isolation needs a different approach.
  • The patterns are framework-agnostic Python illustrations; wiring them to your actual message bus, saga store, and service APIs is real implementation work the playbook guides but doesn't do for you.
  • Choreography can become hard to reason about as steps multiply; the playbook recommends orchestration past a few steps, but that tradeoff still depends on your team's tolerance for a central coordinator vs. distributed event flow.

$Related Playbooks

Developer Tools

Simplicity First Code Gate

A hard correctness gate against over-complex or oversized code — one ordering principle (human readability first, agent traceability second), five enforceable rules, and a pre-finish checklist that treats unnecessary complexity as a bug, not a style opinion.

2 minutes
Beginner
Developer Tools

Slidev Presentation Builder

Build developer-focused presentations with Slidev — Markdown-driven slides with live code, syntax highlighting, Monaco editor embeds, Mermaid/PlantUML diagrams, LaTeX math, click-based animations, and presenter notes, plus a quick-reference table for the exact syntax each feature needs.

5 minutes
Beginner
Developer Tools

Technical Writing Style Guide

Write docstrings, READMEs, commit messages, and PR descriptions that read like human technical documentation instead of LLM output — six concrete 'tells' with before/after rewrites, a smoothness diagnostic for prose that sounds authoritative while stating one fact three times, and industry-metaphor substitution tables ('surfaces' to 'raises/returns/logs', 'wired through' to 'passed as a parameter').

5 minutes
Intermediate
Developer Tools

Three.js Scroll World Builder

Build a scroll-controlled real-time Three.js experience as one persistent 3D world instead of stacked sections — a scene-ledger data model for authoring chapters, native-scroll-to-deterministic-state mapping with separate exact and smoothed progress, cinematic camera composition, a measurable per-device performance budget, and mandatory reduced-motion and WebGL-failure fallbacks.

20 minutes
Advanced
Developer Tools

Secret Scan and Rotation

Find committed credentials in a repository's working tree and full history, triage real secrets from test fixtures, and drive rotation-first remediation — with an absolute rule against ever printing a secret's actual value, even during the scan itself.

5 minutes
Intermediate
Developer Tools

Self-Improvement Loop Design

Design systems where the harness itself is the optimization target — an optimization ladder from prompt to context to workflow to harness code, a two-split empirical acceptance gate, an outside-the-loop invariant for the evaluator, and a catalog of documented reward-hacking and collapse failure modes.

10 minutes
Advanced
Developer Tools

Skill Security Inspector

Review an AI agent skill before installing it using two independent lines — static scanner evidence plus source-aware semantic judgment — checking purpose fit, permission fit, sensitive access, external transmission, execution risk, and persistence, down to a clear APPROVE, CAUTION, or REJECT verdict.

10 minutes
Intermediate
Developer Tools

Semantic Prompt Compression

Re-encode verbose system prompts, tool descriptions, and skill bodies into a dense telegraphic register — punctuation as connectives, label frames, verbless assertions — via re-encoding, not word deletion, with a density gate and a declared-loss verification pass.

5 minutes
Advanced
Developer Tools

Simplified Technical English for Docs

Write or rewrite technical documentation with the ASD-STE100 Simplified Technical English discipline — the aerospace maintenance-manual standard adapted for READMEs, runbooks, error messages, incident reports, and agent instructions.

10 minutes
Intermediate
Developer Tools

Subagent-Driven Development

Execute an implementation plan by dispatching a fresh subagent per task with a spec-and-quality review after each, a ledger that survives compaction, and a 'rulings not stalls' policy that keeps a running plan from waiting on a human at every fork.

10 minutes
Advanced
Developer Tools

Secure Coding Practices

A threat-model-first secure coding reference — trust-boundary mapping, a STRIDE quick-pass, a three-tier always/ask-first/never boundary system, and copy-paste prevention patterns for injection, XSS, broken access control, and SSRF.

10 minutes
Intermediate
Developer Tools

Security Guidance Review

Three-layer continuous security review for AI-generated code — instant regex warnings on edit, an LLM diff review at end of turn, and an agentic commit-time reviewer that traces data flow across files.

10 minutes
Advanced

Browse all Developer Tools playbooks →