All skills
wshobson avatar

/saga-orchestration

@be57c0b
by Seth Hobsonwshobson/agents40k stars
4,281

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.

Use this Skill: https://skilld.dev/gh/wshobson/agents/saga-orchestration

This session only. Nothing lands on disk.

SKILL.md

β‰ˆ137 tokens always: the name and description. β‰ˆ1.4k when used: this file. β‰ˆ6.3k more on demand in 2 files.

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.

Related Skills

  • 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

Source: SKILL.md on GitHub

No alerts16d5 checks Β· Risk SAFE
  • Gen Agent Trust Hub16d

    The skill is safe and contains standard software engineering templates and documentation for implementing Saga Orchestration patterns in distributed systems.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW Β· No issues

  • Runlayer6mo

    1 file scanned Β· No issues

  • ZeroLeaks5mo

    Score: 93/100 Β· 2 sections analyzed

Signed by skilld at be57c0b. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 3 days ago.

Activeupdated 4 months ago
  • saga
  • distributed-transactions
  • microservices
  • event-driven
  • compensation
  • orchestration
  • workflow
  • async-messaging

README badge

README badge for wshobson/agents/saga-orchestration

Implements saga patterns for distributed transactions across microservices, handling compensating actions when steps fail and managing long-running workflows without two-phase commit. Targets order fulfillment, booking, and approval processes that span multiple services with async messaging (Kafka, RabbitMQ, SQS) where atomicity is required but distributed locks are unavailable.

Generated from the current SKILL.md.

Does this skill cover both orchestration and choreography patterns?
Yes. The skill describes both patterns β€” orchestrator-based (centralized coordination) and choreography-based (event-driven, decentralized). The templates and examples cover both approaches.
What messaging systems does this skill support?
The skill is agnostic to the underlying broker. It works with Kafka, RabbitMQ, SQS, and any durable message system you provide as input.
How does this handle compensation failures where a rollback step itself fails?
The skill emphasizes making compensation idempotent and always-succeeding, with dead-letter queue handling for unhandled exceptions. Advanced patterns in references/ cover DLQ recovery workers.
Can I use this skill with synchronous RPC calls instead of async messaging?
No. The skill explicitly requires async messaging and warns against coupling services directly with synchronous calls inside saga steps.
Does this skill provide monitoring and alerting configuration?
Yes. It includes monitoring setup for state machine metrics, stuck saga detection, and references/ contains Prometheus instrumentation and PromQL alerts for production use.

Generated from the current SKILL.md. These answers refresh after source changes.