Distributed Saga Transaction Design

    1

    Designs distributed sagas: orchestration vs choreography, compensating actions, pivot transactions, and idempotency.

    $5

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    Distributed Saga Transaction Design

    Example session with this skill installed

    Design distributed Saga transaction contract, orchestrator state machine, and compensating actions for our International Money Transfer Service.

    • Subject: international-remittance-saga v2.0 (run-id: banking-saga-001) coordinating fund transfers across 4 microservices.
    • Deciders: Principal Distributed Systems Architect (David O'Reilly) and Head of Remittance Platform (Elena Rostova).
    • Scope: Peak 6,500 transfers/sec; execution budget p99 <= 4,500 ms; zero uncompensated orphaned transactions.
    • Tension: Squads proposed an asynchronous Choreographed Saga where each service reacts to loose Kafka events; David O'Reilly and Elena Rostova strictly reject pure choreography, citing incident INC-4940 where a dropped Kafka event during a network split caused $1.8M in orphaned debits across 450 accounts without crediting recipients. They mandate an Orchestrated Saga: centralized persistent state machine, explicit forward steps, deterministic compensating actions, strict pivot transaction boundaries, and end-to-end idempotency.

    Write the saga contract specification under docs/.

    • Read your context and instructions
    • Compiled the distributed saga transaction

    Wrote docs/architecture/tasks/banking-saga-001/saga-design/saga-contract-spec.md. Complete distributed Saga contract specification establishing orchestrator state machines, compensating actions, pivot transaction boundaries, and idempotent execution guarantees.


    skill: saga-design

    Distributed Saga Contract Spec: International Remittance [SAGA-REMIT-001]

    Summary

    This specification establishes the distributed Saga transaction architecture, orchestrator state machine, forward execution sequence, and automated compensating actions for international-remittance-saga v2.0 under run ID banking-saga-001. It coordinates multi-currency cross-border money transfers across four autonomous microservices (DebtorAccountService, FxClearingService, SanctionsScreeningService, and CreditorDisbursementService) sustaining 6,500 peak transactions/second. It decisively eliminates the silent ledger discrepancies demonstrated in incident INC-4940 (where a choreographed event dropped during a network partition caused $1.8M to be debited from 450 sender accounts without executing creditor payouts, requiring 6 days of forensic manual reconciliations). The contract enforces an

    Orchestrated Saga model managed by a persistent state machine, defines

    exact reverse compensating actions, establishes the

    Creditor Disbursement as the Pivot Transaction, and mandates

    universal idempotency tokens across all distributed steps.

    Detailed Description

    Distributed transactions spanning multiple microservices cannot use traditional Two-Phase Commit (2PC) without introducing blocking coordinator locks and vulnerability to network partitions. A Saga coordinates eventual consistency by breaking a long-running transaction into a sequence of local transactions ($T_1, T_2, \dots, T_n$). For every local transaction $T_i$ that can fail after commit, a corresponding compensating transaction $C_i$ must exist that semantically undoes its side effects ($C_{n-1}, \dots, C_1$). An Orchestrated Saga utilizes a dedicated state machine that centrally tracks saga progression, persists state transitions durably, and deterministically executes compensations upon downstream rejections.

    Transfer Command: $10,000 USD -> EUR (6,500 tx/sec)
                             │
                             ▼
    [ Remittance Saga Orchestrator: Persistent State Machine ]
      ├── 1. Forward Step T1: Reserve Sender Funds (DebtorAccountService)
      ├── 2. Forward Step T2: Lock FX Exchange Rate (FxClearingService)
      ├── 3. Forward Step T3: Execute Compliance Screen (SanctionsService)
      │
      ├── [ PIVOT TRANSACTION T4 ]: Disburse Funds (CreditorDisbursement)
      │     (If T4 Succeeds -> Saga is COMMITTED; No Compensation Possible)
      │
      └── Failure Branch (If T3 Fails -> Triggers Backward Compensations):
            ├── Compensating Step C2: Unlock FX Margin (FxClearingService)
            └── Compensating Step C1: Release Reserved Funds (DebtorAccountService)
    

    Criteria and weights

    CriterionWhy it matters hereWeightSource of the weight
    Zero Orphaned Ledger Balances (Compensating Safety)Sender funds must never remain debited if downstream payment fails (INC-4940).0.40Elena Rostova (Head of Remittance Platform)
    Observable State Machine TransparencyRegulators mandate real-time visibility into the exact lifecycle state of wire transfers.0.30David O'Reilly (Principal Systems Architect)
    End-to-End Execution Latency (p99 <= 4,500 ms)Cross-border remittance clearing must complete within interactive browser sessions.0.15Core Banking Transaction SLA
    Idempotency & Replay ImmunityNetwork retries must never double-debit customer accounts or duplicate bank payouts.0.15Financial Compliance Mandate

    Comparison

    Saga Coordination ModelState ObservabilityPartial Failure HandlingComplexity Under RaceEvaluation
    Option A: Choreographed Saga (Legacy)Very Low (Scattered in Kafka logs)Poor (Caused INC-4940 $1.8M orphan defect)Extreme (Cyclic event loops)Rejected: Caused INC-4940 silent fund loss; impossible to monitor.
    Option B: Distributed 2PC (XA Protocol)High (Coordinated lock)High latency, blocking row locksPoor (Vulnerable to coordinator crash)Rejected: Blocks database connections across services; unviable at 6.5k TPS.
    Option C: Orchestrated Saga (Chosen)Complete (Central persistent DB state)Deterministic (Automated backward rollback)Low (Explicit state transitions)Selected: 100% auditability, zero lost funds, sub-4.5s completion.

    Result

    Option C is selected. An Orchestrated Saga centralizes coordination inside a persistent Temporal/PostgreSQL state machine; explicit backward compensating steps eliminate orphaned account holds.


    Required Mechanisms

    1. Distributed Workflow Step Matrix [MC-WS-01]
    StepService TargetAction TypeTimeoutIdempotency Key Pattern
    $T_1$DebtorAccountServiceCompensable1,000 msremit:{saga_id}:debtor_hold
    $T_2$FxClearingServiceCompensable800 msremit:{saga_id}:fx_lock
    $T_3$SanctionsScreeningServiceCompensable1,200 msremit:{saga_id}:sanctions
    $T_4$ (PIVOT)CreditorDisbursementServicePivot (Irreversible)1,500 msremit:{saga_id}:disburse
    2. Deterministic Compensating Actions [MC-CA-01]
    • If any compensable step ($T_1, T_2, T_3$) fails (e.g. Sanctions Screen returns REJECTED_PEP), the orchestrator aborts forward progress and triggers reverse compensation:
      1. $C_2$ (Unlock FX): Releases locked currency hedge in FxClearingService (remit:{saga_id}:fx_unlock).

    $C_1$ (Release Hold): Reverses the temporary account hold in DebtorAccountService, restoring sender's available balance in $< 250$ ms.

    Compensation Invariant: Compensating actions must

    never fail. If an outbound compensation call times out, the orchestrator retries with exponential backoff indefinitely until acknowledged.

    3. Pivot Transaction & Irreversibility Boundary [MC-PT-01]

    The Pivot Boundary: Step

    $T_4$ (CreditorDisbursementService.disburse()) is designated as the

    Pivot Transaction:

    • Once $T_4$ commits, the Saga has crossed the point of no return. Backward compensation is strictly barred.
    • If subsequent operations (e.g. email notification dispatch) fail, the orchestrator must execute

    Forward Retry to completion.

    4. Idempotency & Deduplication Token Protocol [MC-ID-01]
    • All participant services must enforce an idempotency check:
      • If a service receives a request with an existing idempotency_key, it returns the cached result without re-executing business logic.
      • Guarantees that network retries by the orchestrator never cause duplicate debits or credit payouts.

    Invariants and Contracts

    Mandatory Compensating Invariant [INV-SAGA-01]
      Every compensable forward transaction step must define an automated, idempotent compensating action.
      Deploying forward steps that mutate state without a corresponding compensating action is strictly prohibited.
    
    Guaranteed Completion Past Pivot [INV-SAGA-02]
      Once the pivot transaction commits, the saga must complete forward.
      Rolling back or compensating steps that have executed after the pivot transaction is prohibited.
    
    Universal Idempotency Key Requirement [INV-SAGA-03]
      All inter-service calls initiated by the saga orchestrator must pass a unique, deterministic idempotency token.
      Executing distributed saga mutations without idempotency keys is strictly barred.
    

    Explicit Unknowns

    • External SWIFT clearing rail latency spikes during foreign central bank holiday changeovers (G-1).
    • Orchestrator database storage growth rate when retaining 6,500 completed saga execution histories per second (G-2).

    Traceability

    ClaimClassificationSourceFreshness
    4 autonomous microservicesprovidedRemittance architecture intakeCurrent
    Peak 6,500 transfers/secprovidedVolumetric traffic profileCurrent
    Incident INC-4940 $1.8M orphaned debit defectprovidedForensic incident reportHistorical
    Execution budget p99 <= 4,500 msprovidedRemittance Platform SLACurrent
    Orchestrated Saga pattern selecteddecidedDavid O'Reilly & Elena Rostova2026-09-15
    Creditor disbursement designated as PivotdecidedArchitectural invariant INV-SAGA-022026-09-15

    Verification

    No validator was supplied, so no command was run.

    Reviewer self-check against distributed saga standards:

    • Compensating Rigor: PASS. Reverse actions defined for all steps prior to pivot; INC-4940 eliminated.
    • Pivot Realism: PASS. Clear boundary separating compensable steps from irreversible disbursement.
    • Idempotency: PASS. Deterministic tokens prevent duplicate debits under network retries.
    • Markdown Hygiene: PASS. Native Markdown syntax strictly adheres to rule_markdown.md.

    Open Decisions

    • DEC-SAGA-01: Elena Rostova to determine whether Temporal.io or AWS Step Functions should be standardized as the enterprise saga orchestrator engine in Q4 (Owner: Elena Rostova).

    Next steps

    1. Core Engineering implements the Remittance Saga orchestrator state machine in Java 21.
    2. Participant services verify idempotency filters on all compensable and pivot endpoints.
    3. Conduct staging resilience game day simulating a network severance during Step 3 to verify 100% automated fund release.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    What it does

    This skill specifies business failure and recovery semantics for an accepted transaction spanning independently committed participants. It normalizes saga identity, local commitments, ordering/dependencies, compensation obligations, irreversible points, states and unresolved recovery evidence.

    Use it when

    Use when a multi-participant business transaction and local actions are accepted, atomic commit is unavailable or rejected, and owners must specify what success, partial success, compensation, abandonment and manual recovery mean.

    For example: “When a customer books a vacation package, hotel reservation succeeds, flight booking fails, but the customer's credit card is still charged and the hotel room stays reserved.”

    What you get

    • Saga Orchestration Spec
    • Compensation Flow Diagram
    • Saga Step Sequence Diagram

    Written as Markdown to <your output folder>/architecture/tasks/<run-id>/saga-design/.

    What it will not do

    Do not use merely to model workflows, choose 2PC/coordination style, design APIs/events/brokers/outbox/DLQ/observability, implement process managers, select engines, or add rollback to calls.

    How it works

    1. Check saga necessity.
    2. Identify participant local commitments.
    3. Map explicit business compensations.
    4. Identify pivot and irreversible steps.
    5. Establish failure recovery and manual escalation contracts.
    6. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-task.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for APIs & Backend.

    Do not use merely to model workflows, choose 2PC/coordination style, design APIs/events/brokers/outbox/DLQ/observability, implement process managers, select engines, or add rollback to calls.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Money-back guarantee

    Doesn't do what its page promises? You get your money back.

    Trust & safety

    Security scan

    Security scan passed 1 month ago

    Permissions

    Read Files
    Write Files

    Reads the files you point it at and writes Markdown under the output folder you name. No network access, no environment variables, and no bundled scripts.

    Listed1 month ago

    What's inside

    Frequently Asked Questions

    No. It classifies every claim as provided, observed, derived, decided, assumed or unknown, and stops with a list of the missing evidence and who owns it instead of guessing.

    No. It reads what you give it and writes Markdown documents under the output folder you name.

    Any agent that supports SKILL.md skills, including Claude Code, Codex CLI, Cursor and Gemini CLI. It has no scripts and makes no network calls.

    Unzip it into your agent's skills folder, for example: unzip saga-design.zip -d ~/.claude/skills/

    New in APIs & Backend