Implement saga patterns for distributed transactions

Saga orchestration

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Saga orchestration cover

Implement saga patterns for distributed transactions and cross-aggregate workflows. Use this skill when implementing distributed transactions across microservices where 2PC is unavailable, designing compensating actions for failed order…

---
name: saga-orchestration
description: Implement saga patterns for distributed transactions and cross-aggregate workflows. Use this skill when implementing distributed transactions across microservices where 2PC is unavailable, designing compensating actions for failed order workflows that span inventory, payment, and shipping services, building event-driven saga coordinators for travel booking systems that must roll back hotel, flight, and car rental reservations atomically, or debugging stuck saga states in production where compensation steps never complete.
---

# Saga Orchestration

Patterns for managing distributed transactions and long-running business processes without two-phase commit.

## Inputs and Outputs

**What you provide:**
- Service boundaries and ownership (which service owns which step)
- Transaction requirements (which steps must be atomic, which can be eventual)
- Failure modes for each step (transient vs. permanent, retry policy)
- SLA requirements per step (informs timeout configuration)
- Existing event/messaging infrastructure (Kafka, RabbitMQ, SQS, etc.)

Overview

Patterns for managing distributed transactions and long-running business processes without two-phase commit.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill saga-orchestration -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/backend-development/skills/saga-orchestration
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/91ea247efbd26ef15a21/saga-orchestration.zip" -OutFile "$env:TEMP\saga-orchestration.zip"; Expand-Archive "$env:TEMP\saga-orchestration.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md5.9 KB
  • references/2 files · 24.7 KB
Read the files here
wshobson/4236bb93 files
SKILL.md
Show the full text118 lines

Saga Orchestration

Patterns for managing distributed transactions and long-running business processes without two-phase commit.

Inputs and Outputs

What you provide:

  • Service boundaries and ownership (which service owns which step)
  • Transaction requirements (which steps must be atomic, which can be eventual)
  • Failure modes for each step (transient vs. permanent, retry policy)
  • SLA requirements per step (informs timeout configuration)
  • Existing event/messaging infrastructure (Kafka, RabbitMQ, SQS, etc.)

What this skill produces:

  • Saga definition with ordered steps, action commands, and compensation commands
  • Orchestrator or choreography implementation for your chosen pattern
  • Compensation logic for each participant service (idempotent, always-succeeds)
  • Step timeout configuration with per-step deadlines
  • Monitoring setup: state machine metrics, stuck saga detection, DLQ recovery

When to Use This Skill

  • Coordinating multi-service transactions without distributed locks
  • Implementing compensating transactions for partial failures
  • Managing long-running business workflows (minutes to hours)
  • Handling failures in distributed systems where atomicity is required
  • Building order fulfillment, approval, or booking processes
  • Replacing fragile two-phase commit with async compensation

Detailed section: Core Concepts

Moved to references/details.md.

Detailed section: Templates

Moved to references/details.md.

Best Practices

Do's
  • Make every step idempotent — Commands may be replayed on broker reconnect
  • Design compensations carefully — They are the most critical code path
  • Use correlation IDs — The saga_id must flow through every event and log
  • Implement per-step timeouts — Never wait indefinitely for a participant reply
  • Log state transitions — saga_id, step_name, old_state → new_state on every change
  • Test compensation paths explicitly — Inject failures at each step index in integration tests
Don'ts
  • Don't assume instant completion — Sagas are async and may take minutes
  • Don't skip compensation testing — The rollback path is the hardest to get right
  • Don't couple services directly — Use async messaging, never synchronous calls inside a saga step
  • Don't ignore partial failures — A step that partially executed still needs compensation
  • Don't use a global timeout — Each step has different latency characteristics

Troubleshooting

Saga stuck in COMPENSATING state

A saga enters compensation but never reaches FAILED. This means a compensation handler is throwing an unhandled exception and never publishing SagaCompensationCompleted. Add dead-letter queue (DLQ) handling to compensation consumers and ensure every compensation action publishes a result event even when the underlying operation was already rolled back.

async def handle_release_reservation(self, command: Dict):
    try:
        await self.release_reservation(command["original_result"]["reservation_id"])
    except ReservationNotFoundError:
        pass  # Already released — treat as success
    # Always publish completion, regardless of outcome
    await self.event_publisher.publish("SagaCompensationCompleted", {
        "saga_id": command["saga_id"],
        "step_name": "reserve_inventory"
    })
Duplicate saga executions on restart

If your orchestrator service restarts mid-saga, it may replay events and re-execute already-completed steps. Guard every step action with an idempotency key — see Template 3 above.

Choreography saga losing events

In a choreography-based saga, a downstream service may miss an event if it was offline when published. Use a durable message broker (Kafka with replication, RabbitMQ with persistence) and store the current saga state in a dedicated saga_log table so you can replay from the last known good step.

Timeout firing before a slow-but-valid step completes

A step like create_shipment might take up to 15 minutes during peak load but your global timeout is 5 minutes, causing spurious compensation. Make step timeouts configurable per step type — see references/advanced-patterns.md for the TimeoutSagaOrchestrator implementation and the STEP_TIMEOUTS dict pattern.

Compensation order not matching execution order

When two steps both complete before a failure is detected, compensation must run in strict reverse order or you leave data in an inconsistent state. Verify that _compensate() iterates from current_step - 1 down to 0, and add an integration test that deliberately fails at each step index to confirm correct rollback order.


Advanced Patterns

The references/ directory contains production-grade implementations not needed for most sagas:

  • references/advanced-patterns.md — Full SagaOrchestrator abstract base class, TimeoutSagaOrchestrator with per-step deadlines, detailed bank transfer compensating transaction chain, Prometheus instrumentation, stuck saga PromQL alerts, and DLQ recovery worker.

  • cqrs-implementation — Pair sagas with CQRS for read-model updates after each step completes
  • event-store-design — Store saga events in an event store for full audit trail and replay capability
  • workflow-orchestration-patterns — Higher-level workflow engines (Temporal, Conductor) that build on saga concepts
1---
2name: saga-orchestration
3description: Implement saga patterns for distributed transactions and cross-aggregate workflows. Use this skill when implementing distributed transactions across microservices where 2PC is unavailable, designing compensating actions for failed order workflows that span inventory, payment, and shipping services, building event-driven saga coordinators for travel booking systems that must roll back hotel, flight, and car rental reservations atomically, or debugging stuck saga states in production where compensation steps never complete.
4---
5 
6# Saga Orchestration
7 
8Patterns for managing distributed transactions and long-running business processes without two-phase commit.
9 
10## Inputs and Outputs
11 
12**What you provide:**
13- Service boundaries and ownership (which service owns which step)
14- Transaction requirements (which steps must be atomic, which can be eventual)
15- Failure modes for each step (transient vs. permanent, retry policy)
16- SLA requirements per step (informs timeout configuration)
17- Existing event/messaging infrastructure (Kafka, RabbitMQ, SQS, etc.)
18 
19**What this skill produces:**
20- Saga definition with ordered steps, action commands, and compensation commands
21- Orchestrator or choreography implementation for your chosen pattern
22- Compensation logic for each participant service (idempotent, always-succeeds)
23- Step timeout configuration with per-step deadlines
24- Monitoring setup: state machine metrics, stuck saga detection, DLQ recovery
25 
26---
27 
28## When to Use This Skill
29 
30- Coordinating multi-service transactions without distributed locks
31- Implementing compensating transactions for partial failures
32- Managing long-running business workflows (minutes to hours)
33- Handling failures in distributed systems where atomicity is required
34- Building order fulfillment, approval, or booking processes
35- Replacing fragile two-phase commit with async compensation
36 
37---
38 
39## Detailed section: Core Concepts
40 
41Moved to `references/details.md`.
42 
43## Detailed section: Templates
44 
45Moved to `references/details.md`.
46 
47## Best Practices
48 
49### Do's
50 
51- **Make every step idempotent** — Commands may be replayed on broker reconnect
52- **Design compensations carefully** — They are the most critical code path
53- **Use correlation IDs** — The `saga_id` must flow through every event and log
54- **Implement per-step timeouts** — Never wait indefinitely for a participant reply
55- **Log state transitions** — `saga_id`, `step_name`, `old_state → new_state` on every change
56- **Test compensation paths explicitly** — Inject failures at each step index in integration tests
57 
58### Don'ts
59 
60- **Don't assume instant completion** — Sagas are async and may take minutes
61- **Don't skip compensation testing** — The rollback path is the hardest to get right
62- **Don't couple services directly** — Use async messaging, never synchronous calls inside a saga step
63- **Don't ignore partial failures** — A step that partially executed still needs compensation
64- **Don't use a global timeout** — Each step has different latency characteristics
65 
66---
67 
68## Troubleshooting
69 
70### Saga stuck in COMPENSATING state
71 
72A saga enters compensation but never reaches FAILED. This means a compensation handler is throwing an unhandled exception and never publishing `SagaCompensationCompleted`. Add dead-letter queue (DLQ) handling to compensation consumers and ensure every compensation action publishes a result event even when the underlying operation was already rolled back.
73 
74```python
75async def handle_release_reservation(self, command: Dict):
76 try:
77 await self.release_reservation(command["original_result"]["reservation_id"])
78 except ReservationNotFoundError:
79 pass # Already released — treat as success
80 # Always publish completion, regardless of outcome
81 await self.event_publisher.publish("SagaCompensationCompleted", {
82 "saga_id": command["saga_id"],
83 "step_name": "reserve_inventory"
84 })
85```
86 
87### Duplicate saga executions on restart
88 
89If your orchestrator service restarts mid-saga, it may replay events and re-execute already-completed steps. Guard every step action with an idempotency key — see **Template 3** above.
90 
91### Choreography saga losing events
92 
93In a choreography-based saga, a downstream service may miss an event if it was offline when published. Use a durable message broker (Kafka with replication, RabbitMQ with persistence) and store the current saga state in a dedicated `saga_log` table so you can replay from the last known good step.
94 
95### Timeout firing before a slow-but-valid step completes
96 
97A step like `create_shipment` might take up to 15 minutes during peak load but your global timeout is 5 minutes, causing spurious compensation. Make step timeouts configurable per step type — see `references/advanced-patterns.md` for the `TimeoutSagaOrchestrator` implementation and the `STEP_TIMEOUTS` dict pattern.
98 
99### Compensation order not matching execution order
100 
101When two steps both complete before a failure is detected, compensation must run in strict reverse order or you leave data in an inconsistent state. Verify that `_compensate()` iterates from `current_step - 1` down to `0`, and add an integration test that deliberately fails at each step index to confirm correct rollback order.
102 
103---
104 
105## Advanced Patterns
106 
107The `references/` directory contains production-grade implementations not needed for most sagas:
108 
109- **`references/advanced-patterns.md`** — Full `SagaOrchestrator` abstract base class, `TimeoutSagaOrchestrator` with per-step deadlines, detailed bank transfer compensating transaction chain, Prometheus instrumentation, stuck saga PromQL alerts, and DLQ recovery worker.
110 
111---
112 
113## Related Skills
114 
115- `cqrs-implementation` — Pair sagas with CQRS for read-model updates after each step completes
116- `event-store-design` — Store saga events in an event store for full audit trail and replay capability
117- `workflow-orchestration-patterns` — Higher-level workflow engines (Temporal, Conductor) that build on saga concepts
118 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillGuides stable API and interface designaddyosmani/agent-skills · by addyosmaniGuides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.★ 98.7k GitHub starsMCPPulls up-to-date, version-specific library docsContext7upstash/context7 · by upstashPulls up-to-date, version-specific library docs and code examples into the prompt so the AI stops inventing old APIs.★ 62.3k GitHub starsSkillFetch up-to-date documentation and code examples for anyContext7 Documentation Lookupupstash/context7 · by upstashFetch up-to-date documentation and code examples for any library, framework, SDK, CLI tool, or cloud service. Use whenever the user asks about a specific library — even well-known ones like React, Next.js, Prisma, Express, Tailwind, Django, or Spring Boot — because training data may not reflect recent API changes or version updates. Always use for: API syntax questions, configuration options, version migration issues, "how do I" questions mentioning a library name, debugging that involves library-specific behavior, setup instructions, and CLI tool usage. Use even when you think you know the answer. Do not rely on training data for API details, signatures, or configuration options — they are frequently out of date. Prefer this over web search for library documentation.★ 62.3k GitHub starsSkillHow to use the Adaptyv Bio Foundry API and Python SDKK-Dense-AI/scientific-agent-skills · by K-Dense-AIHow to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.★ 46k GitHub starsSkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillGuides the usage of Gemini Interactions API on GeminiGemini Interactions API Skillgoogle/skills · by googleGuides the usage of Gemini Interactions API on Gemini Enterprise Agent Platform. Use when the user wants to use the stateful, server-managed Interactions API for multi-turn conversations, background execution, streaming, structured output, and function calling on the Agent Platform.★ 20.9k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars