Skip to content

Saga Pattern ​

"Compensating transactions might not always succeed" — Microsoft, Saga distributed transactions pattern

Summary: A saga coordinates committed local transactions and business compensations across boundaries that cannot share one atomic transaction. Focus: Choreography, orchestration, durable state, compensation, ambiguous timeouts, pivot decisions, isolation countermeasures and the broker-specific delivery of commands and replies. Learning goal: Design an order workflow that survives duplicate delivery and worker failure, explain what a refund can and cannot undo, and identify when a saga is the wrong consistency boundary.

This chapter owns the saga mechanism. Reliable publication belongs to Transactional Outbox, duplicate effects to Idempotent Consumer, retry schedules to Retry & Backoff, and workflow engines to Durable Workflows. The DDD perspective is in Designing for Failure; a saga does not turn several services into one aggregate.

Page map ​

If you needRead
The basic promise and state namesOne minute
Why local transactions are not enoughWhy
Original database idea and modern servicesHistory
Local commits, compensation and coordinationConcept catalogue
Lost replies and the point of no returnTimeouts, Pivot
Isolation anomalies and six countermeasuresCountermeasures
Persisted state, step log, locks and error policyMechanics
Repairing a stuck business operationSolutions
Go and Laravel implementationsGo, Laravel
Transport boundariesBroker differences
Selecting an architecture and scaling itChoosing, Architecture
Failure experimentsLab
Review, answers and terminologyMisconceptions, Self-check, Glossary

Everything in one minute ​

TermPlain meaningOrder example
Local transactionOne participant commits its own invariantInventory reserves a named quantity
SagaPersisted progress through several such commitsReserve stock, charge, arrange shipment
CompensationA new business action amends an earlier effectRelease reservation; refund a charge
OrchestrationA coordinator chooses the next commandOrder saga sends ReserveStock
ChoreographyParticipants react to factsInventory reacts to OrderPlaced
PivotBusiness boundary after which recovery goes forwardA confirmed payment may commit us to fulfilment
Semantic lockBusiness state blocks conflicting operationsPENDING order cannot be cancelled as APPROVED
StuckAutomatic recovery budget exhaustedRefund requires operator reconciliation
StateWork allowedExit
runningExecute or retry the current forward stepNext step, compensation, completed or stuck
compensatingExecute or retry the current undoPrevious undo, compensated or stuck
completedNo automatic step executionExplicit new business workflow only
compensatedNo automatic forward executionExplicit new attempt with a new saga id
stuckInvestigate; do not silently drop itAudited recovery command after reconciliation

The persisted state is authoritative. An empty broker queue, an HTTP 200, a publisher confirm and a completed saga are four different observations.

Why sagas exist ​

An order database cannot roll back a payment provider's committed charge. Holding a database transaction open while waiting for the provider only holds local locks longer; it does not enlist the provider in that transaction. A saga accepts intermediate business states and records how to recover from them.

One local ACID transactionA saga across local transactions
Database commit is the atomic boundaryEach participant has its own commit
Rollback removes uncommitted local changesCompensation amends already visible effects
Database isolation applies inside that boundaryBusiness countermeasures protect cross-step invariants
Usually short-lived locksDurable progress may live for hours or days
Simpler if all required data has one ownerUseful when ownership or external APIs prevent one transaction

Everyday picture: a travel agent books a flight, a hotel and a car. If the car is unavailable, cancelling the flight is a new booking operation, possibly with a cancellation fee. It cannot erase the confirmation email or another traveller's reservation. The agent keeps the booking identifiers so recovery can continue tomorrow.

Three misconceptions to discard: compensation is not database rollback; an orchestrator is not a distributed database lock; and asynchronous transport does not remove the need to persist deadlines and outcomes.

Where it comes from ​

Hector Garcia-Molina and Kenneth Salem introduced Sagas in 1987 to break long-lived database transactions into smaller transactions that could interleave with other work. Their model pairs forward transactions with semantic compensations and a recovery log. It predates microservices: the original problem was the cost of retaining resources for a long transaction.

Modern service sagas apply that idea to independently owned databases and external systems. Richardson distinguishes choreography and orchestration; the EIP Process Manager explains a stateful coordinator's routing role. A process manager becomes a saga coordinator when its business process includes these consistency and compensation rules. Not every workflow needs compensation, and not every event-driven collaboration is a saga.

Concept catalogue ​

Local commits and the saga boundary Must-know ​

In plain words: each service finishes a small transaction; the overall business operation is still unfinished.

Common misunderstanding: "All services use transactions, so checkout is atomic." Those are different transactions, often in different databases.

Definition: a saga is a coordinated sequence of local transactions whose partial execution is recoverable through later forward work or compensating transactions. The business invariant describes acceptable intermediate and final states.

text
1 Orders: INSERT order PENDING + saga state -> local COMMIT
2 Inventory: reserve reservation S1        -> local COMMIT
3 Payments: charge S1                      -> local COMMIT
4 Shipping: schedule S1                    -> local COMMIT
5 Orders: mark APPROVED                    -> local COMMIT

Real scenarios: checkout with a payment gateway, travel booking across suppliers, account onboarding with external identity checks, and provisioning a paid subscription. A single database transfer between two accounts usually needs one local transaction instead.

BoundaryWhat it protectsWhat remains outside
PostgreSQL transactionState and outbox rows on that connectionA remote charge
Kafka transactionRecords and offsets inside its supported Kafka scopeInventory SQL or a bank API
RabbitMQ publisher confirmBroker acceptance at its configured durability boundaryParticipant business success
Redis Streams XACKPending-delivery bookkeepingCompletion of the entire saga

Fix: define service ownership and the invariant first. Keep each participant's effect and dedup record in one local transaction. Publish through an outbox when state and outgoing messages must be atomic; the Go store below demonstrates that boundary.

Compensation is a business operation Must-know ​

In plain words: undo your reservation, not everybody else's changes to stock.

Common misunderstanding: "Compensation restores the old database snapshot." Restoring available=10 after other orders changed stock would overwrite their work.

Definition: a compensating transaction semantically amends a committed effect. It is application-specific, may have fees or visible audit entries, must tolerate repetition and may itself fail. Reverse order is the policy for this linear example, not a universal requirement; independent compensations may run in parallel when their dependencies allow it.

text
1 S1 reserves 2 units: available 10 -> 8
2 S2 reserves 3 units: available 8 -> 5
3 S1 payment rejected
4 S1 releases reservation S1: available 5 -> 7
5 S1 must NOT restore available to 10

Real scenarios: release stock, cancel a supplier booking, issue a refund, revoke a provisional entitlement. An email cannot be unsent; an apology or correction is a new action. A shipment already handed to a carrier might require a return process rather than an undo endpoint.

Forward effectCompensationInformation that must survive
Reserve inventoryRelease that reservationReservation id, immutable SKU and quantity
Capture paymentRefund or void under provider policyProvider operation id and currency/amount
Create provisional accessRevoke provisional accessGrant id and policy version
Reserve supplier bookingCancel bookingSupplier reference and cancellation terms

Fix: store the compensation input before losing access to it. Use separate stable keys such as saga:step:do and saga:step:undo. A retry of undo must not produce a second refund. A refund failure moves the process into recovery, never directly to compensated.

Orchestration and the durable coordinator Must-know ​

In plain words: one component owns the question "what should happen next?"

Common misunderstanding: "Central coordination means one process and a single point of failure." Several workers can coordinate different sagas through durable state; concurrent transitions for one saga still need serialization.

Definition: an orchestrator interprets replies and persisted state, decides a next command, and records recovery information. The coordinator's business logic can be a pure state machine; storage and transport are adapters.

text
1 Reply StockReserved arrives twice
2 Worker A locks saga S1, advances step, records ChargePayment
3 Worker B locks S1 after A commits
4 B sees the stock step is no longer current; duplicate has no effect
5 Relay sends ChargePayment; a crash can cause a repeated command

Real scenarios: an order with several participants, a regulated onboarding process needing an audit trail, or compensation that depends on the exact completed prefix.

ProductCoordination primitiveBoundary
PostgreSQLSaga row + FOR UPDATE + step logOne row's transition, not a remote effect
RabbitMQDurable command/reply queuesDoes not store the business state machine
KafkaKeyed commands and repliesOrder is within a topic partition
Redis StreamsCommands, reply stream and consumer groupsPEL is not a saga state table

Fix: persist the state transition and outgoing command atomically, or explicitly persist a deadline that will recover a missing send. The Go example uses an outbox; the Laravel message-driven example shows durable deadline recovery and states its publication gap.

Choreography and event contracts Important ​

In plain words: each participant reacts to a fact and announces its own result.

Common misunderstanding: "No orchestrator means no coupling." Participants still depend on event meaning, ordering assumptions and compensation policy; the workflow can become harder to discover.

Definition: choreography distributes the transition decisions among participants. A local transaction emits an event that triggers another participant, while failure events trigger recovery actions. Each participant still needs durable state and reliable publication.

text
1 Orders publishes OrderPlaced
2 Inventory reserves stock -> StockReserved
3 Payments declines charge -> PaymentDeclined
4 Inventory releases reservation; Orders rejects PENDING order
5 A status projection correlates all facts by order/saga id

Real scenarios: a short order flow with stable contracts, subscription provisioning across independent teams, or notifications that genuinely follow domain facts. A dozen cyclic subscriptions with hidden dependencies is a reason to reconsider orchestration.

QuestionChoreographyOrchestration
Who chooses next step?Event handlersCoordinator definition
Where is progress visible?Participant state and correlated projectionSaga row and step log
Who changes the business sequence?Several event contracts/handlersCoordinator plus affected participant contracts
Typical riskCycles, implicit workflow, unclear recovery ownerOvergrown coordinator and shared domain logic

Fix: document the event flow, give every recovery action an owner, and publish participant outcomes reliably. The in-memory Go bus and Laravel listener examples are teaching sketches; broker-backed deployment needs the outbox/inbox boundaries linked above.

Orchestration: one durable decision ownerSaga state + coordinatorInventoryPaymentsShippingChoreography: events connect participant decisionsOrderPlacedStockReservedPaymentChargedBoth require durable local state, reliable publication and explicit recovery ownership.

Timeouts, ambiguity and late commands Must-know ​

In plain words: no reply does not tell you whether money moved.

Common misunderstanding: "Timeout is the same as payment declined." A declined reply can state that the local operation did not commit; a timeout says only that the caller has no confirmed result.

Definition: an ambiguous outcome occurs when an effect may have committed but its reply is absent. Recovery may query the participant, retry with the same operation key, or compensate the silent step itself when its cancellation contract supports that safely.

text
1 Payments commits charge S1
2 Reply is lost
3 Coordinator deadline expires; same charge key is retried
4 Retry budget expires; coordinator requests undo for charge S1 too
5 Refund arrives before a delayed duplicate charge: cancellation tombstone rejects late do

Real scenarios: a gateway timeout after a successful charge, a worker killed after a database commit, a reply lost during failover, and a cancellation racing with a delayed command.

ObservationInterpretationNext action
Definitive business rejectionParticipant guarantees no forward commitCompensate preceding steps
Transport timeoutOutcome unknownQuery/retry same key; never invent rejection
Deadline after compensable stepSilent step may have committedInclude it in safe compensation plan
Deadline after pivotBackward recovery is disallowed by policyRetry forward or park for reconciliation
Duplicate or late replyCould describe an earlier transitionCheck saga id, current step and action

Fix: a durable sweeper rechecks the deadline under the saga row lock. Use one authoritative clock for stored deadlines and expiry queries. Broker TTL may discard a command but cannot cancel a committed effect; retain cancellation tombstones long enough to cover replay and retry windows.

Pivot, compensable and retryable steps Important ​

In plain words: decide when the business commits to finishing rather than unwinding.

Common misunderstanding: "Every error should trigger all the compensations." Refunding after an irreversible shipment may create a free shipped order.

Definition: compensable steps support backward recovery. A pivot marks the business point after which subsequent steps must be completed through forward recovery. Microsoft allows the pivot to be the last compensable or the first retryable operation, depending on the process. Retryable describes the recovery policy, not a promise that infrastructure never fails.

text
1 Reserve stock                  compensable
2 Charge payment succeeds       this example's business pivot
3 Schedule shipment fails       retry forward with same key
4 Retry budget exhausted        STUCK; operator reconciles shipment
5 Do not automatically refund merely because step 3 is unavailable

Real scenarios: payment confirmation committing an order to fulfilment, a final airline ticket issue, or approval that requires follow-up provisioning. Pick the pivot with the business owner; different payment authorization/capture policies produce different designs.

Step in this exampleBefore confirmed successAfter confirmed success
Reserve stockReject or retryCan release reservation
Charge paymentUnknown outcome may require cancellation/refundBusiness policy switches to forward recovery
Schedule shipmentRetry/repairSaga completes

Fix: the sample explicitly supports refunding a charge whose success was not confirmed before cancellation, while refusing a late charge after cancellation. That requires the payment participant's cancellation contract. If the provider cannot support it, park and query the provider instead of pretending undo-before-do is safe.

Isolation anomalies and countermeasures Must-know ​

In plain words: other operations can see and modify the partial result of a saga.

Common misunderstanding: "SERIALIZABLE in every service makes the saga serializable." It only serializes each local transaction; the saga releases that boundary between steps.

Definition: saga-level lost updates, dirty reads and nonrepeatable reads concern interleaving committed local states. A saga dirty read can see a locally committed but business-provisional value; it is not necessarily a database dirty read of uncommitted SQL data.

text
1 S1 creates order APPROVAL_PENDING
2 S2 attempts cancel-as-approved while S1 is charging
3 Conditional UPDATE refuses S2: state is not APPROVED
4 S1 completes -> APPROVED, or compensates -> REJECTED
5 S2 re-reads and applies its own valid transition

Real scenarios: two orders racing for final stock, cancellation during payment, prices changing between quote and charge, and a release delivered before reservation.

CountermeasureMechanismCost / limit
Semantic lockBusiness state such as PENDING blocks incompatible transitionsCan remain locked until recovery; every writer must cooperate
Commutative updatesApply deltas rather than restore snapshotsAdmission under stock bounds still depends on order
Pessimistic viewMove externally visible risky updates after the pivotMay change UX and business ordering
Reread valuesCompare the version before the next writeConflict needs a business retry or compensation
Version fileRemember operation history and enforce legal sequencingHistory retention and per-entity serialization
By valueChoose stronger coordination or review for high-risk operationsRequires a real supported stronger boundary, not a magic 2PC flag

Fix: conditional SQL guards a semantic lock; the Go and Laravel examples below also serialize reservation operation records. Catching PostgreSQL 23505 and then committing the already-aborted transaction is wrong: use ON CONFLICT DO NOTHING or rollback/retry the transaction.

sql
UPDATE orders SET status = 'CANCEL_PENDING', version = version + 1
WHERE id = 'o-1' AND status = 'APPROVED';
-- expected: 0 rows while APPROVAL_PENDING; caller re-reads instead of cancelling blindly.
SELECT pg_advisory_xact_lock(hashtextextended('reservation-S1', 0));
-- In a short local transaction: serialize reserve and release for the same reservation.
go
// Package countermeasures maps Richardson's saga countermeasures to code in
// one participant (inventory) and in the order service, using pgx. Each
// function is one local transaction; none of them is a saga by itself.
package countermeasures

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

const Schema = `
CREATE TABLE orders (
    id      text PRIMARY KEY,
    status  text NOT NULL,           -- APPROVAL_PENDING | APPROVED | CANCEL_PENDING | ...
    total   bigint NOT NULL,
    version int  NOT NULL DEFAULT 0  -- for reread value
);
CREATE TABLE stock (
    sku       text PRIMARY KEY,
    available int NOT NULL CHECK (available >= 0)
);
-- Version file: every operation on a reservation, in arrival order.
CREATE TABLE reservation_ops (
    saga_id text NOT NULL,
    op      text NOT NULL,           -- 'reserve' | 'release'
    at      timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (saga_id, op)
);`

var (
	ErrLocked     = errors.New("record is held by another saga, retry later")
	ErrNoStock    = errors.New("not enough stock")
	ErrStale      = errors.New("record changed since the saga read it")
	ErrLateDo     = errors.New("already released: refusing a late reserve")
	ErrNeedsHuman = errors.New("high value: route to the 2PC/manual path")
)

// SemanticLock: cancelling is allowed only from a final state. While a
// create-order saga runs, the order is APPROVAL_PENDING and cancel is refused.
func SemanticLock(ctx context.Context, db *pgxpool.Pool, orderID string) error {
	tag, err := db.Exec(ctx,
		`UPDATE orders SET status = 'CANCEL_PENDING', version = version + 1
		  WHERE id = $1 AND status = 'APPROVED'`, orderID)
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrLocked // still *_PENDING: the client retries later
	}
	return nil
}

// CommutativeReserve: "subtract 3" commutes with any other subtract or
// add arithmetically; admission under a stock constraint still depends on order.
// Conditional atomic SQL avoids the lost-update race of read-modify-write. The CHECK constraint is the business rule.
func CommutativeReserve(ctx context.Context, db *pgxpool.Pool, sku string, qty int) error {
	if qty <= 0 {
		return ErrNoStock
	}
	tag, err := db.Exec(ctx,
		`UPDATE stock SET available = available - $2 WHERE sku = $1 AND available >= $2`,
		sku, qty)
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrNoStock
	}
	return nil
}

// RereadValue: the saga carried the version it read in an earlier step;
// the update only applies if nobody changed the row since (compare-and-set).
func RereadValue(ctx context.Context, db *pgxpool.Pool, orderID string, readVersion int) error {
	tag, err := db.Exec(ctx,
		`UPDATE orders SET status = 'APPROVED', version = version + 1
		  WHERE id = $1 AND version = $2 AND status = 'APPROVAL_PENDING'`,
		orderID, readVersion)
	if err != nil {
		return err
	}
	if tag.RowsAffected() == 0 {
		return ErrStale // stop this step; the orchestrator compensates or restarts
	}
	return nil
}

// VersionFile: record each operation; a release that arrives before its
// reserve (reordered or retried messages) is remembered, and the late
// reserve is refused instead of leaking stock forever.
func VersionFile(ctx context.Context, db *pgxpool.Pool, sagaID, op, sku string, qty int) error {
	if (op != "reserve" && op != "release") || qty <= 0 {
		return errors.New("invalid reservation operation")
	}
	return pgx.BeginFunc(ctx, db, func(tx pgx.Tx) error {
		// Serialize BOTH operation kinds for this reservation, even before rows exist.
		// Hash collisions only serialize unrelated reservations; they do not lose data.
		if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, sagaID); err != nil {
			return err
		}
		tag, err := tx.Exec(ctx, `INSERT INTO reservation_ops (saga_id,op) VALUES ($1,$2) ON CONFLICT DO NOTHING`, sagaID, op)
		if err != nil {
			return err
		}
		if tag.RowsAffected() == 0 {
			return nil
		}
		var other bool
		if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM reservation_ops WHERE saga_id=$1 AND op<>$2)`, sagaID, op).Scan(&other); err != nil {
			return err
		}
		switch {
		case op == "reserve" && other:
			return ErrLateDo
		case op == "release" && !other:
			return nil
		case op == "reserve":
			tag, err = tx.Exec(ctx, `UPDATE stock SET available=available-$2 WHERE sku=$1 AND available >= $2`, sku, qty)
		default:
			tag, err = tx.Exec(ctx, `UPDATE stock SET available=available+$2 WHERE sku=$1`, sku, qty)
		}
		if err != nil {
			return err
		}
		if tag.RowsAffected() != 1 {
			return ErrNoStock
		}
		return nil
	})
}

// ByValue: pick the mechanism by business risk. Low value goes through the
// saga; high value takes a path with stronger guarantees or a human.
func ByValue(totalCents int64) error {
	if totalCents > 1_000_000 {
		return ErrNeedsHuman
	}
	return nil
}
php
<?php
namespace App\Sagas;

use Illuminate\Support\Facades\DB;
use RuntimeException;

final class Countermeasures
{
    public static function cancel(string $orderId): void
    {
        if (DB::table('orders')->where('id',$orderId)->where('status','approved')->update(['status'=>'cancel_pending'])!==1) {
            throw new RuntimeException('Semantic lock: order not ready to cancel');
        }
    }
    public static function reread(string $orderId,int $version): void
    {
        if (DB::table('orders')->where('id',$orderId)->where('version',$version)->where('status','pending')
            ->update(['status'=>'approved','version'=>$version+1])!==1) { throw new RuntimeException('Version changed'); }
    }
    /** PostgreSQL; reservation_ops has PRIMARY KEY(saga_id,op). SKU/qty are immutable per reservation. */
    public static function reservation(string $id,string $op,string $sku,int $qty): void
    {
        if (!in_array($op,['reserve','release'],true)||$qty<1) { throw new RuntimeException('Invalid operation'); }
        DB::transaction(function () use ($id,$op,$sku,$qty) {
            DB::select('SELECT pg_advisory_xact_lock(hashtextextended(?,0))',[$id]);
            if (DB::table('reservation_ops')->insertOrIgnore(['saga_id'=>$id,'op'=>$op,'at'=>DB::raw('CURRENT_TIMESTAMP')])===0) { return; }
            $other=DB::table('reservation_ops')->where('saga_id',$id)->where('op','!=',$op)->exists();
            if ($op==='reserve' && $other) { throw new RuntimeException('Late reserve refused'); }
            if ($op==='release' && !$other) { return; } // tombstone fences a late do
            $q=DB::table('stock')->where('sku',$sku);
            $n=$op==='reserve'?$q->where('available','>=',$qty)->decrement('available',$qty):$q->increment('available',$qty);
            if ($n!==1) { throw new RuntimeException('Stock unavailable'); }
        });
    }
}
Protect business state across local commitsSaga S1: reserveSaga S2: cancelConditional state guardSerialize reservation operationsReserve first: hold stockRelease first: tombstoneLate reserve: refuseAn operation log needs serialization and retention; logging alone does not prevent a race.

Durable recovery and stuck sagas Must-know ​

In plain words: a business process must survive the process that was executing it.

Common misunderstanding: "The broker will redeliver, so I do not need a saga log." Redelivery cannot reconstruct which compensations are still required unless the needed facts survive somewhere.

Definition: durable recovery persists current step, direction, attempts, deadline, version, compensation inputs and terminal outcome. A saga execution coordinator (SEC) log records committed transitions; an operational log line emitted before commit is only an attempted transition.

text
1 Coordinator commits state=compensating, step=charge-payment
2 Worker refunds; dies before reply reaches coordinator
3 Deadline resends same undo key
4 Participant returns stored refund result; no second refund
5 Coordinator records undo success and advances to release-stock

Real scenarios: deploy during a day-long workflow, database failover during a transition, permanently rejected compensation, and recovery after an operator fixes an account mapping.

PersistWhyAvoid
Saga id, definition type/versionCorrelation and compatible recoveryReinterpreting old state with a reordered definition
Current step and actionDetermines legal next replyTreating any success as current success
Attempts and deadlineBounds automatic workInfinite hot-loop retry
Compensation inputsAllows semantic undo tomorrowReconstructing historical price from today's catalogue
Step log and reasonExplains decisions and manual recoveryRecording sensitive payloads in error logs

Fix: park exhausted work as stuck, alert on its age, and provide audited resume/cancel/reconcile commands. The example pins one definition; production deployments must retain the definition version needed by in-flight sagas. Retain dedup records and provider operation ids for at least the recovery/replay horizon.

Linear order saga: recovery depends on the business boundaryReserve stockCharge paymentSchedule shipmentConfirmed payment = pivot hereRelease reservationRefund / cancel chargeRetry forwardDefinitive rejection: undo preceding stepsUnknown outcome: include the silent compensable step; fence late do after undo.Budget exhausted: STUCKNever label a failed compensation as completed.

Mechanics: persisted transitions and delivery ​

The Go schema has sagas, saga_steps and saga_outbox. A reply handler locks one saga, evaluates a pure transition, updates its version, inserts the audit entry and records the next command in the same PostgreSQL transaction. The broker ack happens after that commit. A relay crash can repeat a command, so participants still need stable idempotency keys.

The example's polling relay keeps row locks while publishing, illustrating a small batch rather than a production throughput recommendation. Multiple relays can interleave commands. Correctness must survive reordered do/undo; for relay strategies and ordering limits read Outbox. A broker outage should not hold a database connection indefinitely: bound I/O and batch duration and monitor the pool.

Knob / identifierSample policyMeaning
MaxAttempts5Bound retries before compensation or Stuck
StepTimeout30 seconds in executable wiringReply silence threshold, not cancellation of remote work
versionIncrement per committed transitionDetect stale writes and key audit entries
FOR UPDATE SKIP LOCKEDSweeper/relay batchesDistribute local work without waiting behind locked rows
saga_id:step:actionStable across retriesDo and undo have different dedup identities
RabbitMQ prefetch_count32 for repliesBounds unsettled delivery, not total open sagas
Kafka DisableAutoCommitEnabled in Go exampleCommit only after durable state handling
Kafka BlockRebalanceOnPollEnabled in Go exampleBound handler work; allow rebalance after commit
Redis XAUTOCLAIM60 seconds minimum idle, cursor scanReclaim abandoned delivery; not business timeout
Laravel UniqueFor60 seconds in optional jobDispatch suppression window, not exactly-once effects
Error / conditionInterpretationPolicy
PostgreSQL 40001Serialization conflictRetry the whole local transaction with a budget
PostgreSQL 40P01Deadlock victimRetry transaction; review lock order
PostgreSQL 23505Unique conflictIdentify intended dedup conflict; do not swallow arbitrary conflicts
PostgreSQL 25P02Transaction already abortedRoll back; do not keep issuing business SQL
AMQP 406 PRECONDITION_FAILEDDeclaration or protocol precondition mismatchFix configuration; reconnect a usable channel
basic.returnMandatory publication was unroutableDo not treat a positive confirm as business delivery
Kafka commit/fetch failureProcessing position may be uncertainClose/recreate client; resume committed offsets
Redis BUSYGROUPExisting consumer groupIgnore only this known setup condition
Malformed replyContract or poison-message issuePreserve for repair; do not silently skip and commit
Payment timeoutUnknown business outcomeQuery/retry same idempotency key or reconcile

A unique key is scoped to a stable payload. Reusing a reservation id with a different SKU or quantity violates the sample contract; production inboxes should reject key/payload mismatches. The pure state machine tests verify decisions, not remote provider behavior or database failover.

Solutions to the classic problems ​

ProblemPreferred solutionBenefitLimit
Charge succeeded, reply lostRepeat/query with stable operation keyRecovers known resultProvider must retain key/result long enough
Undo reaches participant firstCancellation tombstone and serialized per-reservation transitionsBlocks a late forward effectTombstone retention is part of correctness
Saga state committed, command missingState + outbox in one transactionDurable publish intentRelay is at-least-once
Laravel after-commit callback lostDurable deadline sweeper resends the current commandExplicit recovery for this exampleDelay until deadline; attempt budget may end in compensation
Two reply handlers raceRow lock plus version/audit updateOne legal transition at a timeLong remote work must remain outside that lock
Compensation repeatedly failsBounded retries, Stuck state, alert and reconciliationPrevents silent abandonmentRequires an operational owner
Workflow changes during deploymentPin definition version per sagaOld work retains its meaningMust maintain compatible old handlers
User retries checkoutBusiness request key mapped to one order/sagaAvoids two separate sagasTransport correlation id alone does not solve it
Operator replays old repliesStep/action checks and retention policyIgnores stale resultsOld forward commands still need participant fencing
Irreversible action is too earlyReorder around a pivot or redesign boundaryShrinks compensation burdenBusiness may reject changed timing

Recovery runbook: find the saga and provider operation ids; query participant truth; distinguish a missing reply from a missing effect; select forward recovery or compensation under the recorded policy; record the operator decision; reuse the original operation key; verify final participant and order states. Deleting a stuck row only deletes evidence.

Choosing a coordination model ​

SituationChooseAddReason
One database owns the invariantLocal transactionAppropriate isolationSaga adds needless intermediate states
Few stable event dependenciesChoreographyTraceable contract and recovery ownerKeeps reactions near participants
Many conditional/compensating stepsOrchestrationDurable state, timers, auditMakes decisions visible
Long waits, human approvals, complex timersWorkflow engineIdempotent activities and business compensationEngine persists execution mechanics
Temporary inconsistency unacceptableRevisit service boundary or supported atomic protocolExplicit availability/latency analysisCompensation does not provide instantaneous atomicity
High-value external paymentReconciliation and provider-specific state modelManual escalation, not blind retryCost of ambiguity dominates throughput
Read-only fan-out queryAPI compositionDeadline and partial-result policyNo committed effects to compensate

Temporal/Cadence-style durable execution can host a saga, but it does not invent the refund or isolation policy. Compare Durable Workflows, Request-Reply and Distributed Transactions.

Go ​

Before: sequential calls with no recovery ​

go
// Package main places an order by calling three services in a row over HTTP
// and calls the whole thing a "transaction". It is not one: each call commits
// in its own database, and nothing undoes the earlier calls when a later one
// fails or when this process dies half way through.
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

type Order struct {
	ID         string `json:"id"`
	CustomerID string `json:"customer_id"`
	SKU        string `json:"sku"`
	Qty        int    `json:"qty"`
	TotalCents int64  `json:"total_cents"`
}

type Checkout struct {
	client *http.Client
}

func (c *Checkout) post(ctx context.Context, url string, body any) error {
	b, err := json.Marshal(body)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(b))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := c.client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		return fmt.Errorf("%s: %s", url, resp.Status)
	}
	return nil
}

// PlaceOrder looks atomic in the code and is not atomic in the world.
func (c *Checkout) PlaceOrder(ctx context.Context, o Order) error {
	// Step 1 commits in the inventory database.
	if err := c.post(ctx, "http://inventory/reservations", o); err != nil {
		return err
	}
	// Step 2 commits in the payment provider. If it fails, the stock
	// reserved in step 1 stays reserved forever.
	if err := c.post(ctx, "http://payments/charges", o); err != nil {
		return err
	}
	// Step 3: if this times out, the customer is charged, the stock is held,
	// and nobody knows whether a shipment exists. A crash of this process
	// between any two lines leaves the same mess with no record of it.
	return c.post(ctx, "http://shipping/shipments", o)
}

func main() {
	c := &Checkout{client: &http.Client{Timeout: 5 * time.Second}}
	err := c.PlaceOrder(context.Background(), Order{ID: "o-1", CustomerID: "c-1", SKU: "book", Qty: 1, TotalCents: 2500})
	if err != nil {
		log.Println("order failed, state unknown:", err)
	}
}

After: pure decisions, durable state, separate transport ​

go
// Package saga is a small orchestrator: a saga definition (steps with
// compensations), a pure state machine that decides the next command, and a
// Postgres store that persists the state and the outgoing command in one
// local transaction (a transactional outbox).
package saga

import (
	"context"
	"encoding/json"
	"fmt"
)

type Status string

const (
	Running      Status = "running"
	Compensating Status = "compensating"
	Completed    Status = "completed"
	Compensated  Status = "compensated"
	Stuck        Status = "stuck" // a compensation keeps failing: a human decides
)

type Action string

const (
	Do   Action = "do"
	Undo Action = "undo"
)

// Step is one local transaction in one participant. Steps before the pivot
// are compensable; steps after it are marked Retry and are never compensated,
// only retried until they succeed (forward recovery).
type Step struct {
	Name        string // "reserve-stock"
	Participant string // logical destination: "inventory"
	Retry       bool
}

type Definition struct {
	Type  string
	Steps []Step
	// MaxAttempts bounds every retry loop: a silent step, a post-pivot
	// step that keeps failing, and a compensation that keeps failing.
	// Past it the saga is parked as Stuck (the saga dead-letter).
	MaxAttempts int
}

// Command is what the orchestrator asks a participant to do.
type Command struct {
	SagaID  string          `json:"saga_id"`
	Step    string          `json:"step"`
	Action  Action          `json:"action"`
	Attempt int             `json:"attempt"`
	Payload json.RawMessage `json:"payload"`
}

// IdempotencyKey is identical across retries of the same command, so the
// participant can deduplicate it in its inbox table.
func (c Command) IdempotencyKey() string {
	return fmt.Sprintf("%s:%s:%s", c.SagaID, c.Step, c.Action)
}

// Reply is what a participant sends back. OK=false on a Do means "my local
// transaction rolled back for a business reason".
type Reply struct {
	SagaID string `json:"saga_id"`
	Step   string `json:"step"`
	Action Action `json:"action"`
	OK     bool   `json:"ok"`
	Reason string `json:"reason,omitempty"`
}

// State is one row of the sagas table.
type State struct {
	ID       string
	Status   Status
	Step     int // index of the step whose command is in flight
	Attempts int
	Version  int // bumped on every transition: optimistic check + step log key
	Reason   string
	Payload  json.RawMessage
}

// Sender publishes a command to a participant. One implementation per broker.
type Sender interface {
	Send(ctx context.Context, participant string, cmd Command) error
}

// ReplySource delivers replies to handle and acknowledges a reply only after
// handle returned nil. One implementation per broker.
type ReplySource interface {
	Replies(ctx context.Context, handle func(context.Context, Reply) error) error
}

func (d Definition) command(s State, a Action) *Command {
	return &Command{SagaID: s.ID, Step: d.Steps[s.Step].Name, Action: a, Attempt: s.Attempts, Payload: s.Payload}
}

// Validate rejects empty, ambiguous or unbounded definitions before persistence.
func (d Definition) Validate() error {
	if len(d.Steps) == 0 || d.MaxAttempts < 1 {
		return fmt.Errorf("steps and positive MaxAttempts required")
	}
	seen := map[string]bool{}
	retryOnly := false
	for _, st := range d.Steps {
		if st.Name == "" || st.Participant == "" || seen[st.Name] || (retryOnly && !st.Retry) {
			return fmt.Errorf("invalid or ambiguous saga definition")
		}
		seen[st.Name] = true
		retryOnly = retryOnly || st.Retry
	}
	return nil
}
func (d Definition) valid(s State) bool {
	return d.Validate() == nil && s.Step >= 0 && s.Step < len(d.Steps) && s.Attempts >= 0
}

// Begin returns the first command of a new saga; Store validates first.
func (d Definition) Begin(s State) *Command {
	if !d.valid(s) {
		return nil
	}
	return d.command(s, Do)
}

// Next is the whole state machine. It is pure: no I/O, easy to test.
// A reply that does not match the step in flight is a duplicate or a late
// message, and is ignored (nil command, unchanged state).
func (d Definition) Next(s State, r Reply) (State, *Command) {
	if !d.valid(s) {
		s.Status, s.Reason = Stuck, "invalid persisted state"
		return s, nil
	}
	if r.SagaID != s.ID {
		return s, nil
	}
	expected := Do
	if s.Status == Compensating {
		expected = Undo
	}
	if (s.Status != Running && s.Status != Compensating) ||
		r.Step != d.Steps[s.Step].Name || r.Action != expected {
		return s, nil
	}

	switch {
	case s.Status == Running && r.OK:
		s.Step, s.Attempts = s.Step+1, 0
		if s.Step == len(d.Steps) {
			s.Status, s.Step = Completed, len(d.Steps)-1
			return s, nil
		}
		return s, d.command(s, Do)

	case s.Status == Running && d.Steps[s.Step].Retry:
		// Past the pivot there is no going back: retry forward, bounded.
		return d.retry(s, Do, r.Reason)

	case s.Status == Running:
		// A business "no": the participant rolled its local transaction
		// back, so only the steps before this one need undoing.
		s.Reason = r.Reason
		return d.compensateFrom(s, s.Step-1)

	case s.Status == Compensating && r.OK:
		return d.compensateFrom(s, s.Step-1)

	default:
		// A compensation failed. It must eventually succeed, so retry it,
		// and park the saga for a human when it does not.
		return d.retry(s, Undo, r.Reason)
	}
}

// Timeout is what the sweeper calls when the step in flight stayed silent
// past its deadline. Silence is NOT a business "no": the participant may
// have committed and the reply may be lost. So after MaxAttempts resends a
// compensable step is compensated starting with ITSELF (its undo must cope
// with "nothing to undo" and with a late do), not with the step before it.
func (d Definition) Timeout(s State) (State, *Command) {
	if !d.valid(s) {
		s.Status, s.Reason = Stuck, "invalid persisted state"
		return s, nil
	}
	if s.Status != Running && s.Status != Compensating {
		return s, nil
	}
	action := Do
	if s.Status == Compensating {
		action = Undo
	}
	if s.Attempts+1 < d.MaxAttempts {
		s.Attempts++
		return s, d.command(s, action) // resend; participants deduplicate
	}
	if s.Status == Running && !d.Steps[s.Step].Retry {
		s.Reason = "timeout"
		return d.compensateFrom(s, s.Step)
	}
	s.Status, s.Reason = Stuck, "timeout after max attempts"
	return s, nil
}

func (d Definition) retry(s State, a Action, reason string) (State, *Command) {
	s.Attempts++
	if s.Attempts >= d.MaxAttempts {
		s.Status, s.Reason = Stuck, reason
		return s, nil
	}
	return s, d.command(s, a)
}

func (d Definition) compensateFrom(s State, i int) (State, *Command) {
	s.Status, s.Step, s.Attempts = Compensating, i, 0
	if i < 0 {
		s.Status, s.Step = Compensated, 0
		return s, nil
	}
	return s, d.command(s, Undo)
}

// OrderSaga is the running example: stock, then payment (the pivot, the last
// compensable step under this business policy), then shipping, which may only
// be retried. An unknown charge outcome is refunded before that boundary is
// confirmed; participants must fence late do after undo. Real payment policies differ.
var OrderSaga = Definition{
	Type:        "create-order",
	MaxAttempts: 5,
	Steps: []Step{
		{Name: "reserve-stock", Participant: "inventory"},
		{Name: "charge-payment", Participant: "payments"},
		{Name: "schedule-shipment", Participant: "shipping", Retry: true},
	},
}
go
package saga

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"log/slog"
	"time"
)

// Schema is the persisted saga log. The orchestrator itself is stateless:
// any instance can pick up any saga after a crash.
const Schema = `
CREATE TABLE IF NOT EXISTS sagas (
    id          text PRIMARY KEY,
    type        text NOT NULL,
    status      text NOT NULL,
    step        int  NOT NULL,
    attempts    int  NOT NULL DEFAULT 0,
    version     int  NOT NULL DEFAULT 0,
    reason      text,
    payload     jsonb NOT NULL,
    deadline_at timestamptz NOT NULL,
    updated_at  timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS sagas_open_by_deadline
    ON sagas (deadline_at) WHERE status IN ('running', 'compensating');

-- The step log: one row per transition. It answers "what happened to
-- saga X" and is the audit trail a human reads before fixing a stuck saga.
CREATE TABLE IF NOT EXISTS saga_steps (
    saga_id     text NOT NULL REFERENCES sagas (id),
    version     int  NOT NULL,
    step        text NOT NULL,
    from_status text NOT NULL,
    to_status   text NOT NULL,
    attempts    int  NOT NULL,
    reason      text,
    at          timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (saga_id, version)
);

CREATE TABLE IF NOT EXISTS saga_outbox (
    id           bigserial PRIMARY KEY,
    participant  text NOT NULL,
    command      jsonb NOT NULL,
    published_at timestamptz
);`

type Store struct {
	DB          *sql.DB
	Def         Definition
	StepTimeout time.Duration // how long a step may stay silent
}

// ErrConcurrentUpdate means another orchestrator instance moved the saga
// between our read and our write. With the row lock below it cannot
// happen; it guards code paths that read without FOR UPDATE.
var ErrConcurrentUpdate = errors.New("saga: version changed underneath us")

// Start inserts the saga and its first command in one local transaction.
func (s *Store) Start(ctx context.Context, id string, payload json.RawMessage) error {
	if err := s.Def.Validate(); err != nil {
		return err
	}
	if s.StepTimeout <= 0 {
		return errors.New("positive step timeout required")
	}
	st := State{ID: id, Status: Running, Payload: payload}
	return s.inTx(ctx, func(tx *sql.Tx) error {
		_, err := tx.ExecContext(ctx,
			`INSERT INTO sagas (id, type, status, step, payload, deadline_at)
			 VALUES ($1, $2, $3, 0, $4, now() + make_interval(secs => $5))`,
			id, s.Def.Type, st.Status, payload, s.StepTimeout.Seconds())
		if err != nil {
			return err
		}
		return s.enqueue(ctx, tx, st, s.Def.Begin(st))
	})
}

// HandleReply is the message-driven step runner: lock the row, run the state
// machine, persist the new state and the next command atomically.
func (s *Store) HandleReply(ctx context.Context, r Reply) error {
	return s.inTx(ctx, func(tx *sql.Tx) error {
		old, err := s.load(ctx, tx, r.SagaID)
		if errors.Is(err, sql.ErrNoRows) {
			return nil // unknown saga: nothing to do, ack the message
		}
		if err != nil {
			return err
		}
		next, cmd := s.Def.Next(old, r)
		return s.save(ctx, tx, old, next, cmd)
	})
}

// Sweep handles dead sagas: steps whose reply never came. The decision is
// the pure Definition.Timeout: resend (participants deduplicate), then
// compensate starting with the silent step, then park as Stuck.
func (s *Store) Sweep(ctx context.Context) error {
	return s.inTx(ctx, func(tx *sql.Tx) error {
		rows, err := tx.QueryContext(ctx,
			`SELECT id FROM sagas
			  WHERE status IN ('running', 'compensating') AND deadline_at < now()
			  ORDER BY deadline_at LIMIT 100 FOR UPDATE SKIP LOCKED`)
		if err != nil {
			return err
		}
		var ids []string
		for rows.Next() {
			var id string
			if err := rows.Scan(&id); err != nil {
				rows.Close()
				return err
			}
			ids = append(ids, id)
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			return err
		}

		for _, id := range ids {
			old, err := s.load(ctx, tx, id)
			if err != nil {
				return err
			}
			next, cmd := s.Def.Timeout(old)
			if err := s.save(ctx, tx, old, next, cmd); err != nil {
				return err
			}
		}
		return nil
	})
}

// Relay publishes pending commands. It is a polling outbox relay; see the
// outbox page for CDC-based relays and their ordering guarantees.
func (s *Store) Relay(ctx context.Context, out Sender) error {
	return s.inTx(ctx, func(tx *sql.Tx) error {
		rows, err := tx.QueryContext(ctx,
			`SELECT id, participant, command FROM saga_outbox
			  WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED`)
		if err != nil {
			return err
		}
		type pending struct {
			id          int64
			participant string
			cmd         Command
		}
		var batch []pending
		for rows.Next() {
			var p pending
			var raw []byte
			if err := rows.Scan(&p.id, &p.participant, &raw); err != nil {
				rows.Close()
				return err
			}
			if err := json.Unmarshal(raw, &p.cmd); err != nil {
				rows.Close()
				return err
			}
			batch = append(batch, p)
		}
		rows.Close()
		if err := rows.Err(); err != nil {
			return err
		}
		for _, p := range batch {
			// At-least-once: a crash after Send and before the UPDATE
			// publishes the command again. Participants deduplicate.
			if err := out.Send(ctx, p.participant, p.cmd); err != nil {
				return err
			}
			if _, err := tx.ExecContext(ctx,
				`UPDATE saga_outbox SET published_at = now() WHERE id = $1`, p.id); err != nil {
				return err
			}
		}
		return nil
	})
}

func (s *Store) load(ctx context.Context, tx *sql.Tx, id string) (State, error) {
	st := State{ID: id}
	err := tx.QueryRowContext(ctx,
		`SELECT status, step, attempts, version, coalesce(reason, ''), payload
		   FROM sagas WHERE id = $1 FOR UPDATE`, id).
		Scan(&st.Status, &st.Step, &st.Attempts, &st.Version, &st.Reason, &st.Payload)
	if err == nil && !s.Def.valid(st) {
		return st, errors.New("invalid saga state: operator repair required")
	}
	return st, err
}

func (s *Store) save(ctx context.Context, tx *sql.Tx, old, next State, cmd *Command) error {
	if cmd == nil && next.Status == old.Status && next.Step == old.Step && next.Attempts == old.Attempts {
		return nil // duplicate or late reply
	}
	next.Version = old.Version + 1
	res, err := tx.ExecContext(ctx,
		`UPDATE sagas SET status = $2, step = $3, attempts = $4, version = $5,
		        reason = nullif($6, ''), deadline_at = now() + make_interval(secs => $7), updated_at = now()
		  WHERE id = $1 AND version = $8`,
		next.ID, next.Status, next.Step, next.Attempts, next.Version,
		next.Reason, s.StepTimeout.Seconds(), old.Version)
	if err != nil {
		return err
	}
	if n, err := res.RowsAffected(); err != nil {
		return err
	} else if n != 1 {
		return ErrConcurrentUpdate
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO saga_steps (saga_id, version, step, from_status, to_status, attempts, reason)
		 VALUES ($1, $2, $3, $4, $5, $6, nullif($7, ''))`,
		next.ID, next.Version, s.Def.Steps[next.Step].Name, old.Status, next.Status,
		next.Attempts, next.Reason); err != nil {
		return err
	}
	// This is an attempted transition log; transaction commit may still fail.
	// The committed saga_steps table is the authoritative audit trail.
	slog.InfoContext(ctx, "saga transition", "saga_id", next.ID, "type", s.Def.Type,
		"from", old.Status, "to", next.Status, "step", s.Def.Steps[next.Step].Name,
		"attempts", next.Attempts)
	return s.enqueue(ctx, tx, next, cmd)
}

func (s *Store) enqueue(ctx context.Context, tx *sql.Tx, st State, cmd *Command) error {
	if cmd == nil {
		return nil
	}
	body, err := json.Marshal(cmd)
	if err != nil {
		return err
	}
	_, err = tx.ExecContext(ctx,
		`INSERT INTO saga_outbox (participant, command) VALUES ($1, $2)`,
		s.Def.Steps[st.Step].Participant, body)
	return err
}

func (s *Store) inTx(ctx context.Context, fn func(*sql.Tx) error) error {
	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	if err := fn(tx); err != nil {
		return err
	}
	return tx.Commit()
}
go
// Package main wires the orchestrator to one broker, chosen by SAGA_BROKER.
// It exits immediately when the environment is not configured, so it builds
// and vets without Postgres or a broker running.
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
	amqp "github.com/rabbitmq/amqp091-go"
	"github.com/redis/go-redis/v9"

	"academy/saga-pattern/after/kafka"
	"academy/saga-pattern/after/rabbitmq"
	"academy/saga-pattern/after/redisstreams"
	"academy/saga-pattern/after/saga"
)

type transport interface {
	saga.Sender
	saga.ReplySource
}

func main() {
	dsn, broker, addr := os.Getenv("DATABASE_URL"), os.Getenv("SAGA_BROKER"), os.Getenv("BROKER_ADDR")
	if dsn == "" || broker == "" || addr == "" {
		log.Println("set DATABASE_URL, SAGA_BROKER (rabbitmq|kafka|redis) and BROKER_ADDR")
		return
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	if _, err := db.ExecContext(ctx, saga.Schema); err != nil {
		log.Fatal(err)
	}
	store := &saga.Store{DB: db, Def: saga.OrderSaga, StepTimeout: 30 * time.Second}

	var t transport
	switch broker {
	case "rabbitmq":
		conn, err := amqp.Dial(addr)
		if err != nil {
			log.Fatal(err)
		}
		defer conn.Close()
		ch, err := conn.Channel()
		if err != nil {
			log.Fatal(err)
		}
		if t, err = rabbitmq.New(ch, "inventory", "payments", "shipping"); err != nil {
			log.Fatal(err)
		}
	case "kafka":
		if t, err = kafka.New(addr); err != nil {
			log.Fatal(err)
		}
	case "redis":
		host, _ := os.Hostname()
		rdb := redis.NewClient(&redis.Options{Addr: addr, ContextTimeoutEnabled: true, DialTimeout: 3 * time.Second, ReadTimeout: 6 * time.Second, WriteTimeout: 3 * time.Second})
		defer rdb.Close()
		rt := redisstreams.New(rdb, fmt.Sprintf("%s-%d-%d", host, os.Getpid(), time.Now().UnixNano()))
		t = rt
		go every(ctx, 15*time.Second, func() error { return rt.Reclaim(ctx, store.HandleReply) })
	default:
		log.Fatal("unsupported SAGA_BROKER")
	}

	// Three loops: the relay publishes commands, the sweeper finds dead
	// sagas, and the reply consumer drives the state machine.
	go every(ctx, time.Second, func() error { return store.Relay(ctx, t) })
	go every(ctx, 10*time.Second, func() error { return store.Sweep(ctx) })

	payload, _ := json.Marshal(map[string]any{"order_id": "o-1", "sku": "book", "qty": 1, "total_cents": 2500})
	if err := store.Start(ctx, "o-1", payload); err != nil {
		log.Println("start:", err)
	}
	if err := t.Replies(ctx, store.HandleReply); err != nil && ctx.Err() == nil {
		log.Fatal(err)
	}
}

func every(ctx context.Context, d time.Duration, fn func() error) {
	tick := time.NewTicker(d)
	defer tick.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-tick.C:
			if err := fn(); err != nil {
				log.Println(err)
			}
		}
	}
}

The Go angle ​

The state machine has no broker dependency. context.Context bounds cooperative I/O; cancellation is not a business rejection. The in-process runner gives compensation a separate bounded cleanup context, but it is not crash-durable. Its fake participants are useful for learning the sequence, not a substitute for the persisted store.

go
// Package main is an in-process saga runner for a (modular) monolith: the
// steps are calls into modules or remote APIs, the saga runs in one
// goroutine, and each step has its own retries and its own deadline. It is
// the Step interface with Execute and Compensate that the message-driven
// orchestrator generalises. Run it: go run ./inprocess
package main

import (
	"context"
	"errors"
	"fmt"
	"time"
)

// Step is one local transaction plus its semantic undo.
type Step interface {
	Name() string
	Execute(ctx context.Context) error
	Compensate(ctx context.Context) error
}

// ErrRejected is a business "no": do not retry, start compensating.
var ErrRejected = errors.New("rejected")

// Policy is per step: how often to retry a transient error and how long
// one attempt may take (the step deadline).
type Policy struct {
	Attempts int
	Timeout  time.Duration
	Backoff  time.Duration
	Pivot    bool // the point of no return: later steps are retry-only
}

type planned struct {
	step   Step
	policy Policy
}

// Saga runs steps in order and compensates in reverse on failure.
type Saga struct {
	steps []planned
	log   func(format string, args ...any)
}

func (s *Saga) Add(st Step, p Policy) *Saga {
	s.steps = append(s.steps, planned{st, p})
	return s
}

// ErrNeedsHuman is returned when a compensation, or a step past the pivot,
// cannot be completed: the saga must be parked, never silently dropped.
var ErrNeedsHuman = errors.New("saga stuck: manual intervention needed")

func (s *Saga) Run(ctx context.Context) error {
	pastPivot := false
	for i, p := range s.steps {
		if p.policy.Attempts < 1 || p.policy.Timeout <= 0 {
			return errors.New("positive attempts and timeout required")
		}
		err := s.attempt(ctx, p, p.step.Execute)
		if err == nil {
			pastPivot = pastPivot || p.policy.Pivot
			continue
		}
		if pastPivot {
			s.log("%s failed after the pivot: %v", p.step.Name(), err)
			return ErrNeedsHuman
		}
		// A timeout is not a "no": the step may have committed. Undo it too.
		from := i - 1
		if !errors.Is(err, ErrRejected) {
			from = i
		}
		s.log("%s failed (%v): compensating from step %d", p.step.Name(), err, from)
		cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
		defer cancel()
		for j := from; j >= 0; j-- {
			c := s.steps[j]
			if err := s.attempt(cleanup, c, c.step.Compensate); err != nil {
				s.log("compensation %s failed: %v", c.step.Name(), err)
				return ErrNeedsHuman
			}
		}
		return fmt.Errorf("saga compensated: %w", err)
	}
	return nil
}

func (s *Saga) attempt(ctx context.Context, p planned, fn func(context.Context) error) error {
	var err error
	for n := 1; n <= p.policy.Attempts; n++ {
		stepCtx, cancel := context.WithTimeout(ctx, p.policy.Timeout)
		err = fn(stepCtx)
		cancel()
		if err == nil || errors.Is(err, ErrRejected) {
			return err
		}
		s.log("  %s attempt %d: %v", p.step.Name(), n, err)
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(p.policy.Backoff * time.Duration(n)):
		}
	}
	return err
}

// fake is a participant whose behaviour the demo scripts.
type fake struct {
	name     string
	slowOnce bool // the first call blocks past the deadline
	reject   bool
	calls    int
}

func (f *fake) Name() string { return f.name }

func (f *fake) Execute(ctx context.Context) error {
	f.calls++
	if f.slowOnce && f.calls == 1 {
		<-ctx.Done() // a hung dependency: only the deadline gets us out
		return ctx.Err()
	}
	if f.reject {
		return fmt.Errorf("%s: %w", f.name, ErrRejected)
	}
	fmt.Printf("  do   %s\n", f.name)
	return nil
}

func (f *fake) Compensate(ctx context.Context) error {
	fmt.Printf("  undo %s\n", f.name)
	return nil
}

func main() {
	logf := func(format string, args ...any) { fmt.Printf(format+"\n", args...) }
	p := Policy{Attempts: 3, Timeout: 50 * time.Millisecond, Backoff: 10 * time.Millisecond}
	pivot := p
	pivot.Pivot = true

	fmt.Println("run 1: payment declined")
	s := (&Saga{log: logf}).
		Add(&fake{name: "reserve-stock", slowOnce: true}, p).
		Add(&fake{name: "charge-payment", reject: true}, pivot).
		Add(&fake{name: "schedule-shipment"}, p)
	fmt.Println("result:", s.Run(context.Background()))

	fmt.Println("run 2: happy path")
	s = (&Saga{log: logf}).
		Add(&fake{name: "reserve-stock"}, p).
		Add(&fake{name: "charge-payment"}, pivot).
		Add(&fake{name: "schedule-shipment"}, p)
	fmt.Println("result:", s.Run(context.Background()))
}
go
// Package main is the choreographed version of the order saga: no
// orchestrator, only event handlers. Each service subscribes to the events
// it cares about, does one local transaction, and publishes its own event.
// The bus here is an in-memory FIFO so the program runs anywhere; in
// production each Publish is an outbox insert and each handler a consumer
// with an inbox. Run it: go run ./choreography
package main

import "fmt"

type Event struct {
	Type    string
	OrderID string // the correlation id: every event of one saga carries it
	Reason  string
}

type Bus struct {
	subs  map[string][]func(Event)
	queue []Event
}

func (b *Bus) Subscribe(t string, h func(Event)) { b.subs[t] = append(b.subs[t], h) }
func (b *Bus) Publish(e Event)                   { b.queue = append(b.queue, e) }

// Drain delivers events in order. Handlers publish more events, which is
// exactly how the saga "moves" in choreography.
func (b *Bus) Drain() {
	for len(b.queue) > 0 {
		e := b.queue[0]
		b.queue = b.queue[1:]
		fmt.Printf("  event %-16s order=%s %s\n", e.Type, e.OrderID, e.Reason)
		for _, h := range b.subs[e.Type] {
			h(e)
		}
	}
}

// Orders owns the order status. PENDING is the semantic lock.
type Orders struct{ status map[string]string }

// Inventory keeps reservations keyed by order id: that key makes the
// handlers idempotent and lets a release arrive before a reserve.
type Inventory struct {
	available int
	reserved  map[string]int
	released  map[string]bool // version file: remembers "release before reserve"
}

type Payments struct{ limit int }

func wire(b *Bus, o *Orders, inv *Inventory, pay *Payments) {
	b.Subscribe("OrderPlaced", func(e Event) {
		if inv.released[e.OrderID] || inv.reserved[e.OrderID] > 0 {
			return // late or duplicate: already handled
		}
		if inv.available < 1 {
			b.Publish(Event{Type: "StockRejected", OrderID: e.OrderID, Reason: "out of stock"})
			return
		}
		inv.available-- // a commutative decrement in SQL: available = available - 1
		inv.reserved[e.OrderID] = 1
		b.Publish(Event{Type: "StockReserved", OrderID: e.OrderID})
	})
	b.Subscribe("StockReserved", func(e Event) {
		if pay.limit < 25 {
			b.Publish(Event{Type: "PaymentDeclined", OrderID: e.OrderID, Reason: "card declined"})
			return
		}
		b.Publish(Event{Type: "PaymentCharged", OrderID: e.OrderID})
	})
	// Compensation lives in the participant that owns the data.
	b.Subscribe("PaymentDeclined", func(e Event) {
		if n := inv.reserved[e.OrderID]; n > 0 {
			inv.available += n
			delete(inv.reserved, e.OrderID)
		}
		inv.released[e.OrderID] = true
	})
	// The order service listens to the end of every path. Note how the
	// flow is only visible by reading all these subscriptions together.
	for _, t := range []string{"StockRejected", "PaymentDeclined"} {
		b.Subscribe(t, func(e Event) { o.status[e.OrderID] = "REJECTED" })
	}
	b.Subscribe("PaymentCharged", func(e Event) { o.status[e.OrderID] = "APPROVED" })
}

func main() {
	for _, limit := range []int{100, 10} {
		b := &Bus{subs: map[string][]func(Event){}}
		o := &Orders{status: map[string]string{}}
		inv := &Inventory{available: 1, reserved: map[string]int{}, released: map[string]bool{}}
		wire(b, o, inv, &Payments{limit: limit})

		fmt.Printf("card limit %d:\n", limit)
		o.status["o-1"] = "PENDING"
		b.Publish(Event{Type: "OrderPlaced", OrderID: "o-1"})
		b.Drain()
		fmt.Printf("  order=%s available=%d\n", o.status["o-1"], inv.available)
	}
}
go
package saga

import (
	"reflect"
	"testing"
)

// drive feeds replies into the pure state machine and records every
// command it emits, like an orchestrator with a perfect broker.
func drive(t *testing.T, replies func(Command) Reply) (State, []string) {
	t.Helper()
	s := State{ID: "o-1", Status: Running}
	var log []string
	cmd := OrderSaga.Begin(s)
	for i := 0; cmd != nil; i++ {
		if i > 50 {
			t.Fatal("saga did not terminate")
		}
		log = append(log, string(cmd.Action)+":"+cmd.Step)
		s, cmd = OrderSaga.Next(s, replies(*cmd))
	}
	return s, log
}

// failAt answers "no" to one (step, action) and "ok" to everything else.
func failAt(step string, action Action, times int) func(Command) Reply {
	failures := 0
	return func(c Command) Reply {
		ok := !(c.Step == step && c.Action == action && failures < times)
		if !ok {
			failures++
		}
		return Reply{SagaID: c.SagaID, Step: c.Step, Action: c.Action, OK: ok, Reason: "test"}
	}
}

func TestStepFailures(t *testing.T) {
	tests := []struct {
		name   string
		reply  func(Command) Reply
		status Status
		log    []string
	}{
		{"happy path", failAt("", Do, 0), Completed,
			[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment"}},
		{"stock rejected: nothing to undo", failAt("reserve-stock", Do, 1), Compensated,
			[]string{"do:reserve-stock"}},
		{"payment declined: release stock", failAt("charge-payment", Do, 1), Compensated,
			[]string{"do:reserve-stock", "do:charge-payment", "undo:reserve-stock"}},
		{"shipping fails twice after the pivot: retried forward", failAt("schedule-shipment", Do, 2), Completed,
			[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment",
				"do:schedule-shipment", "do:schedule-shipment"}},
		{"shipping never succeeds: stuck, never refunded", failAt("schedule-shipment", Do, 99), Stuck,
			[]string{"do:reserve-stock", "do:charge-payment", "do:schedule-shipment",
				"do:schedule-shipment", "do:schedule-shipment", "do:schedule-shipment", "do:schedule-shipment"}},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			s, log := drive(t, tt.reply)
			if s.Status != tt.status {
				t.Fatalf("status = %s, want %s", s.Status, tt.status)
			}
			if !reflect.DeepEqual(log, tt.log) {
				t.Fatalf("commands = %v\nwant       %v", log, tt.log)
			}
		})
	}
}

func TestCompensationThatKeepsFailingParksTheSaga(t *testing.T) {
	declineThenFailUndo := func(c Command) Reply {
		ok := !(c.Step == "charge-payment" && c.Action == Do) &&
			!(c.Step == "reserve-stock" && c.Action == Undo)
		return Reply{SagaID: c.SagaID, Step: c.Step, Action: c.Action, OK: ok}
	}
	s, _ := drive(t, declineThenFailUndo)
	if s.Status != Stuck {
		t.Fatalf("status = %s, want stuck", s.Status)
	}
}

func TestDuplicateAndLateRepliesAreIgnored(t *testing.T) {
	s := State{ID: "o-1", Status: Running, Step: 1}
	late := Reply{SagaID: "o-1", Step: "reserve-stock", Action: Do, OK: true} // redelivered
	next, cmd := OrderSaga.Next(s, late)
	if cmd != nil || !reflect.DeepEqual(next, s) {
		t.Fatalf("a stale reply changed the saga: %+v %+v", next, cmd)
	}
}

// TestTimeoutCompensatesTheSilentStepItself: the charge may have succeeded
// with its reply lost, so the refund must be attempted too.
func TestTimeoutCompensatesTheSilentStepItself(t *testing.T) {
	s := State{ID: "o-1", Status: Running, Step: 1, Attempts: OrderSaga.MaxAttempts - 1}
	next, cmd := OrderSaga.Timeout(s)
	if next.Status != Compensating || cmd == nil || cmd.Step != "charge-payment" || cmd.Action != Undo {
		t.Fatalf("got %+v %+v, want undo:charge-payment", next, cmd)
	}
}

func TestTimeoutResendsBeforeGivingUp(t *testing.T) {
	s := State{ID: "o-1", Status: Running, Step: 0}
	next, cmd := OrderSaga.Timeout(s)
	if next.Status != Running || next.Attempts != 1 || cmd.Action != Do {
		t.Fatalf("got %+v %+v, want a resend", next, cmd)
	}
}

// TestReplayIsDeterministic: replaying the same reply log (as after a crash
// that lost the in-memory state) reaches the same state, and replaying it a
// second time on top changes nothing.
func TestReplayIsDeterministic(t *testing.T) {
	replies := []Reply{
		{SagaID: "o-1", Step: "reserve-stock", Action: Do, OK: true},
		{SagaID: "o-1", Step: "charge-payment", Action: Do, OK: false, Reason: "card declined"},
		{SagaID: "o-1", Step: "reserve-stock", Action: Undo, OK: true},
	}
	play := func(s State) State {
		for _, r := range replies {
			s, _ = OrderSaga.Next(s, r)
		}
		return s
	}
	once := play(State{ID: "o-1", Status: Running})
	twice := play(once)
	if once.Status != Compensated || !reflect.DeepEqual(once, twice) {
		t.Fatalf("once = %+v, twice = %+v", once, twice)
	}
}

func TestWrongSagaAndInvalidState(t *testing.T) {
	s := State{ID: "ours", Status: Running}
	next, cmd := OrderSaga.Next(s, Reply{SagaID: "other", Step: "reserve-stock", Action: Do, OK: true})
	if cmd != nil || !reflect.DeepEqual(s, next) {
		t.Fatal("wrong saga accepted")
	}
	s.Step = 100
	next, cmd = OrderSaga.Timeout(s)
	if next.Status != Stuck || cmd != nil {
		t.Fatal("corrupt state not parked")
	}
	if (Definition{}).Validate() == nil {
		t.Fatal("empty definition accepted")
	}
}

The executable starts only when its environment is configured. It wires an orchestrator and transport, not complete Inventory/Payments/Shipping services. Implement participants against the command contract; persist their local effects and dedup outcomes together. Go's PostgreSQL countermeasure examples assume immutable reservation inputs and cooperative writers.

Laravel 13 ​

Before: local rollback cannot undo remote calls ​

php
<?php

// app/Http/Controllers/OrderController.php
// Three services, three commits, one controller pretending they are one
// transaction. DB::transaction() here would only wrap the local insert; it
// cannot roll back a reservation or a charge made in another service.
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

final class OrderController
{
    public function store(Request $request): JsonResponse
    {
        $order = Order::create($request->validate([
            'customer_id' => ['required', 'integer'],
            'sku' => ['required', 'string'],
            'qty' => ['required', 'integer', 'min:1'],
            'total_cents' => ['required', 'integer', 'min:1'],
        ]) + ['status' => 'pending']);

        // Commits in the inventory service.
        Http::post(config('services.inventory.url').'/reservations', [
            'order_id' => $order->id, 'sku' => $order->sku, 'qty' => $order->qty,
        ])->throw();

        // Commits at the payment provider. If this throws, the stock above
        // stays reserved and nothing will ever release it.
        Http::post(config('services.payments.url').'/charges', [
            'order_id' => $order->id, 'amount' => $order->total_cents,
        ])->throw();

        // If this times out the customer is charged and the order is stuck in
        // "pending"; if the PHP worker is killed here, there is no record of
        // which of the three calls happened.
        Http::post(config('services.shipping.url').'/shipments', [
            'order_id' => $order->id,
        ])->throw();

        $order->update(['status' => 'approved']);

        return response()->json($order, 201);
    }
}

After: explicit state and recovery deadline ​

php
<?php

// database/migrations/2026_01_01_000000_create_sagas_table.php
// The persisted saga log. Every step and every compensation reads and writes
// this row under a row lock, so any worker can resume any saga after a crash.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('sagas', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('type');                    // 'create_order'
            $table->unsignedInteger('version')->default(0);
            $table->unsignedInteger('attempts')->default(0);
            $table->string('status');                  // running|compensating|completed|compensated|stuck
            $table->json('payload');                   // order id, amounts, sku...
            $table->json('completed_steps');           // ordered list, the compensation plan
            $table->string('current_step')->nullable();
            $table->text('failure_reason')->nullable();
            $table->timestamp('deadline_at');          // when a silent saga counts as dead
            $table->timestamps();

            $table->index(['status', 'deadline_at']);
        });
        Schema::create('saga_steps', function (Blueprint $table) {
            $table->uuid('saga_id'); $table->unsignedInteger('version');
            $table->string('step'); $table->string('from_status'); $table->string('to_status');
            $table->unsignedInteger('attempts'); $table->text('reason')->nullable(); $table->timestamp('created_at');
            $table->primary(['saga_id','version']); $table->foreign('saga_id')->references('id')->on('sagas');
        });
        Schema::create('saga_inbox', function (Blueprint $table) {
            $table->string('key')->primary(); $table->json('reply'); $table->timestamp('created_at');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('saga_inbox');
        Schema::dropIfExists('saga_steps');
        Schema::dropIfExists('sagas');
    }
};
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;

final class Saga extends Model
{
    use HasUuids;

    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'payload' => 'array', 'version'=>'integer', 'attempts'=>'integer',
            'completed_steps' => 'array',
            'deadline_at' => 'datetime',
        ];
    }
}

// app/Sagas/StepRejected.php — a business "no" from a participant.
php
<?php

namespace App\Sagas\Messaging;

use InvalidArgumentException;

/** Pure decisions: callers persist the returned state before sending commands. */
final class Definition
{
    public const STEPS = ['reserve-stock' => 'inventory', 'charge-payment' => 'payments', 'schedule-shipment' => 'shipping'];
    public const MAX_ATTEMPTS = 5;

    /** @return array{0: array, 1: ?array} */
    public static function next(array $s, ?array $reply = null, bool $timeout = false): array
    {
        $names = array_keys(self::STEPS);
        $i = array_search($s['current_step'], $names, true);
        if ($i === false || $s['attempts'] < 0) { throw new InvalidArgumentException('Invalid persisted saga state'); }
        if (!in_array($s['status'], ['running', 'compensating'], true)) { return [$s, null]; }
        $action = $s['status'] === 'compensating' ? 'undo' : 'do';
        if (!$timeout) {
            if ($reply === null || !isset($reply['saga_id'], $reply['step'], $reply['action'], $reply['ok']) || !is_bool($reply['ok'])) {
                throw new InvalidArgumentException('Invalid reply contract');
            }
            if ($reply['saga_id'] !== $s['id'] || $reply['step'] !== $s['current_step'] || $reply['action'] !== $action) { return [$s, null]; }
        }
        if ($timeout || ($s['status'] === 'compensating' && !$reply['ok']) || ($s['status'] === 'running' && $i === 2 && !$reply['ok'])) {
            $s['attempts']++;
            if ($s['attempts'] < self::MAX_ATTEMPTS) { return [$s, self::command($s, $action)]; }
            if ($timeout && $s['status'] === 'running' && $i < 2) {
                $s['failure_reason'] = 'timeout: outcome unknown';
                return self::undoFrom($s, $i); // include silent step, not only completed steps
            }
            $s['status'] = 'stuck'; $s['failure_reason'] = $reply['reason'] ?? 'attempt budget exhausted';
            return [$s, null];
        }
        if ($s['status'] === 'running' && $reply['ok']) {
            $s['attempts'] = 0;
            if ($i === count($names)-1) { $s['status'] = 'completed'; return [$s, null]; }
            $s['current_step'] = $names[$i+1];
            return [$s, self::command($s, 'do')];
        }
        if ($s['status'] === 'running') { $s['failure_reason'] = $reply['reason'] ?? 'business rejection'; }
        return self::undoFrom($s, $i-1);
    }

    private static function undoFrom(array $s, int $i): array
    {
        $s['attempts'] = 0;
        if ($i < 0) { $s['status'] = 'compensated'; return [$s, null]; }
        $s['status'] = 'compensating'; $s['current_step'] = array_keys(self::STEPS)[$i];
        return [$s, self::command($s, 'undo')];
    }

    public static function command(array $s, string $action): array
    {
        return ['saga_id'=>$s['id'], 'step'=>$s['current_step'], 'action'=>$action, 'attempt'=>$s['attempts'], 'payload'=>$s['payload']];
    }
}
php
<?php

namespace App\Sagas\Messaging;

use App\Models\Order;
use App\Models\Saga;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;

/** Durable state plus a durable deadline. See outbox-pattern for atomic publication. */
final class SagaOrchestrator
{
    public function __construct(private SagaTransport $transport) {}

    public function start(Order $order): Saga
    {
        return DB::transaction(function () use ($order) {
            $saga = Saga::create([
                'type'=>'create_order_messages', 'status'=>'running', 'version'=>0, 'attempts'=>0,
                'payload'=>$order->only(['sku','qty','total_cents'])+['order_id'=>$order->id],
                'completed_steps'=>[], 'current_step'=>'reserve-stock', 'deadline_at'=>$this->deadline(),
            ]);
            $command = Definition::command($this->state($saga), 'do');
            // The committed deadline is the recovery mechanism if this callback is lost.
            DB::afterCommit(fn () => $this->send($command));
            return $saga;
        });
    }

    public function onReply(array $reply): void
    {
        if (!isset($reply['saga_id'])) { throw new \InvalidArgumentException('Missing saga id'); }
        DB::transaction(function () use ($reply) {
            $saga=Saga::whereKey($reply['saga_id'])->where('type','create_order_messages')->lockForUpdate()->first();
            if ($saga===null) { return; }
            $old=$this->state($saga);
            [$next,$command]=Definition::next($old,$reply);
            $this->persist($saga,$old,$next,$command);
        });
    }

    /** Recheck under the lock: a stale sweeper candidate cannot expire a fresh step. */
    public function expire(string $id): void
    {
        DB::transaction(function () use ($id) {
            $saga=Saga::whereKey($id)->where('type','create_order_messages')->whereIn('status',['running','compensating'])
                ->where('deadline_at','<',DB::raw('CURRENT_TIMESTAMP'))->lockForUpdate()->first();
            if ($saga===null) { return; }
            $old=$this->state($saga);
            [$next,$command]=Definition::next($old,timeout:true);
            $this->persist($saga,$old,$next,$command);
        });
    }

    private function persist(Saga $saga,array $old,array $next,?array $command): void
    {
        if ($next===$old && $command===null) { return; }
        $version=$saga->version+1;
        $saga->update([
            'status'=>$next['status'], 'current_step'=>$next['current_step'], 'attempts'=>$next['attempts'],
            'failure_reason'=>$next['failure_reason']??null,'version'=>$version,'deadline_at'=>$this->deadline(),
        ]);
        DB::table('saga_steps')->insert([
            'saga_id'=>$saga->id,'version'=>$version,'step'=>$next['current_step'],
            'from_status'=>$old['status'],'to_status'=>$next['status'],'attempts'=>$next['attempts'],
            'reason'=>$next['failure_reason']??null,'created_at'=>DB::raw('CURRENT_TIMESTAMP'),
        ]);
        if (in_array($next['status'],['completed','compensated'],true)) {
            Order::whereKey($saga->payload['order_id'])->update(['status'=>$next['status']==='completed'?'approved':'rejected']);
        }
        if ($command!==null) { DB::afterCommit(fn () => $this->send($command)); }
    }

    private function state(Saga $s): array
    {
        return ['id'=>(string)$s->id,'status'=>$s->status,'current_step'=>$s->current_step,
            'attempts'=>(int)$s->attempts,'failure_reason'=>$s->failure_reason,'payload'=>$s->payload];
    }

    private function deadline(): CarbonImmutable
    {
        // PostgreSQL clock, shared with the sweeper; 30 s is this example's policy.
        return CarbonImmutable::parse(DB::selectOne('SELECT CURRENT_TIMESTAMP AS clock')->clock)->addSeconds(30);
    }

    public function send(array $command): void
    {
        $this->transport->send(Definition::STEPS[$command['step']],$command);
    }
}
php
<?php

namespace App\Sagas\Messaging;

use Illuminate\Support\Facades\DB;

final class Participant
{
    /** Runs a command once per idempotency key; a duplicate gets the same reply again. */
    public static function run(array $command, StepWork $work): array
    {
        $key = "{$command['saga_id']}:{$command['step']}:{$command['action']}";

        return DB::transaction(function () use ($key, $command, $work) {
            $seen = DB::table('saga_inbox')->where('key', $key)->value('reply');
            if ($seen !== null) {
                return json_decode($seen, true);
            }
            $reply = [
                'saga_id' => $command['saga_id'], 'step' => $command['step'], 'action' => $command['action'],
            ] + $work($command);
            // A concurrent duplicate fails on the primary key and rolls back
            // its local work with it.
            DB::table('saga_inbox')->insert(['key' => $key, 'reply' => json_encode($reply), 'created_at' => now()]);

            return $reply;
        });
    }
}
php
<?php

namespace App\Sagas\Messaging;



interface StepWork
{
    /** Local work only (same DB connection), returns ['ok' => bool, 'reason' => ?string]. */
    public function __invoke(array $command): array;
}

// app/Sagas/Messaging/SagaOrchestrator.php
php
<?php

namespace App\Sagas\Messaging;



interface SagaTransport
{
    /** @param array{saga_id: string, step: string, action: string, payload: array} $command */
    public function send(string $participant, array $command): void;
}

// app/Sagas/Messaging/StepWork.php — bound per participant app.
php
<?php
namespace App\Http\Controllers;

use App\Models\Order;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;

final class MessagingOrderController
{
    public function store(Request $request,SagaOrchestrator $sagas): JsonResponse
    {
        $data=$request->validate(['sku'=>['required','string'],'qty'=>['required','integer','min:1'],'total_cents'=>['required','integer','min:1']]);
        $saga=DB::transaction(function () use ($data,$sagas) {
            $order=Order::create($data+['status'=>'pending']);
            return $sagas->start($order);
        });
        return response()->json(['saga_id'=>$saga->id,'status'=>'pending'],202);
    }
}
php
<?php

use App\Models\Saga;
use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    Saga::where('type','create_order_messages')->whereIn('status',['running','compensating'])->where('deadline_at','<',\Illuminate\Support\Facades\DB::raw('CURRENT_TIMESTAMP'))
        ->select('id')->lazy()->each(fn (Saga $s) => app(SagaOrchestrator::class)->expire($s->id));
})->everyTenSeconds();
// Multiple schedulers are safe: expire() rechecks under a DB row lock.

This variant intentionally demonstrates deadline recovery: DB::afterCommit avoids sending before the transaction commits, but is not atomic publication. If the callback is lost, the stored deadline causes expire() to resend or compensate. Use a transactional outbox for durable outgoing intent without waiting for timeout. The order and initial saga are created in one transaction in the controller. External HTTP calls must not run inside StepWork's local database transaction.

The Laravel angle ​

The documented driver list includes: "including the database, Amazon SQS, Redis, and Beanstalkd drivers". The null driver discards jobs.

Laravel 13 provides database, Redis, SQS, Beanstalkd and synchronous/background queue options; RabbitMQ and Kafka require packages. The Redis queue driver uses lists/sorted sets, not Redis Streams. ShouldBeUnique uses a cache lock to reduce duplicate dispatch; it cannot replace the participant inbox or an external payment idempotency key. Its duration must be chosen with execution and retry timing in mind.

php
<?php

namespace App\Sagas\Messaging;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Attributes\Tries;
use Throwable;

/** Optional standalone job; dispatch uniqueness reduces work, it is not the inbox. */
#[UniqueFor(60)]
#[Tries(5)]
final class ExecuteStep implements ShouldQueue, ShouldBeUnique
{
    use Queueable;
    public function __construct(public array $command) {}
    public function uniqueId(): string { return $this->command['saga_id'].':'.$this->command['step'].':'.$this->command['action']; }
    public function handle(StepWork $work, ReplyPublisher $publisher): void
    {
        $publisher->publish(Participant::run($this->command,$work));
    }
    public function failed(?Throwable $e): void
    {
        // Do NOT fabricate a business rejection after an ambiguous effect.
        // No reply: the persisted orchestrator deadline triggers compensation or Stuck.
        logger()->error('Saga participant exhausted retries',['key'=>$this->uniqueId(),'error'=>$e?->getMessage()]);
    }
}
php
<?php
namespace App\Sagas\Messaging;
interface ReplyPublisher { public function publish(array $reply): void; }

Bus::chain is useful for sequencing jobs, but its failure callback is not a complete durable saga engine. The accompanying chain sketch records the in-flight step before calling a participant, includes an ambiguous step in compensation, and guards completion. It still needs host-app reconciliation for dispatch gaps; prefer the explicit message-driven example for reasoning about durable transitions.

The variants use distinct types, create_order_chain and create_order_messages. The sweeper and reply handler accept only the message-driven type; the chain needs its own reconciliation path. A late duplicate job only compensates in compensating or compensated; it must never automatically refund an already completed or stuck forward-recovery order.

php
<?php

namespace App\Sagas;

use App\Models\Order;
use App\Models\Saga;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Throwable;

final class CreateOrderSaga
{
    /** @var array<string, class-string<SagaStep>> */
    private const STEPS = [
        'reserve-stock' => ReserveStock::class,
        'charge-payment' => ChargePayment::class,
        'schedule-shipment' => ScheduleShipment::class,
    ];

    private const PIVOT = 'charge-payment';

    public static function step(string $name, string $sagaId): SagaStep
    {
        $class = self::STEPS[$name];

        return new $class($sagaId);
    }

    public function start(Order $order): Saga
    {
        $saga = Saga::create([
            'type' => 'create_order_chain',
            'status' => 'running',
            'payload' => $order->only(['sku', 'qty', 'total_cents']) + ['order_id' => $order->id],
            'completed_steps' => [],
            'deadline_at' => now()->addMinutes(15),
        ]);
        $sagaId = $saga->id;

        $jobs = array_map(fn (string $class) => new $class($sagaId), array_values(self::STEPS));
        $jobs[] = static function () use ($sagaId) {
            CreateOrderSaga::complete($sagaId);
        };

        Bus::chain($jobs)
            ->catch(static function (Throwable $e) use ($sagaId) {
                // Serialized and run later by a worker: no $this in here.
                CreateOrderSaga::onStepFailed($sagaId, $e->getMessage());
            })
            ->dispatch();

        return $saga;
    }

    public static function onStepFailed(string $sagaId, string $reason): void
    {
        $saga = Saga::whereKey($sagaId)->where('type','create_order_chain')->first();
        if ($saga===null) { return; }
        if (in_array(self::PIVOT, $saga->completed_steps, true)) {
            // Past the point of no return: park it for a human, never undo.
            Saga::whereKey($sagaId)->where('status','running')->update(['status' => 'stuck', 'failure_reason' => $reason]);

            return;
        }
        CompensateCreateOrder::dispatch($sagaId, $reason);
    }

    public static function complete(string $sagaId): void
    {
        DB::transaction(function () use ($sagaId) {
            $saga = Saga::whereKey($sagaId)->lockForUpdate()->firstOrFail();
            if ($saga->type !== 'create_order_chain' || $saga->status !== 'running' || !in_array('schedule-shipment',$saga->completed_steps,true)) { return; }
            $saga->update(['status' => 'completed']);
            Order::whereKey($saga->payload['order_id'])->update(['status' => 'approved']);
        });
    }
}

// app/Http/Controllers/OrderController.php — answers 202, the saga runs on.
php
<?php
namespace App\Sagas;
final class LateOutcomePolicy
{
    public static function shouldCompensate(string $status): bool
    {
        return in_array($status, ['compensating', 'compensated'], true);
    }
}
php
<?php

namespace App\Sagas;

use App\Models\Saga;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

abstract class SagaStep implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $sagaId) {}

    abstract public static function name(): string;

    // Calls the participant; must be idempotent under $key.
    abstract protected function perform(Saga $saga, string $key): void;

    // Semantic undo; must be idempotent and must cope with "undo before do".
    abstract public function compensate(Saga $saga, string $key): void;

    public function handle(): void
    {
        $saga = Saga::findOrFail($this->sagaId);
        if ($saga->type !== 'create_order_chain' || $saga->status !== 'running' || in_array(static::name(), $saga->completed_steps, true)) {
            return; // duplicate delivery, or the saga is already unwinding
        }

        // Record the in-flight step BEFORE the remote side can commit.
        $saga = DB::transaction(function () {
            $row=Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
            if ($row->type !== 'create_order_chain' || $row->status !== 'running' || in_array(static::name(), $row->completed_steps, true)) { return null; }
            $row->update(['current_step'=>static::name(),'deadline_at'=>now()->addMinutes(15)]);
            return $row;
        });
        if ($saga===null) { return; }
        try {
            // Never hold a row lock across a network call.
            $this->perform($saga, "{$saga->id}:".static::name().':do');
        } catch (StepRejected $e) {
            $this->fail($e); // no retries: the chain's catch() runs now
            return;
        }

        $recorded = DB::transaction(function () {
            $saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
            if ($saga->status !== 'running') {
                // A late duplicate must never refund a completed or forward-recovery saga.
                return LateOutcomePolicy::shouldCompensate($saga->status) ? 'undo' : 'ignore';
            }
            if (in_array(static::name(), $saga->completed_steps, true)) { return 'ignore'; }
            $saga->update([
                'completed_steps' => array_values(array_unique([...$saga->completed_steps, static::name()])),
                'current_step' => static::name(),
                'deadline_at' => now()->addMinutes(15),
            ]);

            return true;
        });

        if ($recorded === 'undo') {
            // A late success after compensation began: undo our own work.
            $this->compensate($saga, "{$saga->id}:".static::name().':undo');
        }
    }
}

// app/Sagas/Steps.php — the three participants, each a step/compensation pair.
php
<?php

namespace App\Sagas;

use App\Models\Order;
use App\Models\Saga;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\RetryFor;
use Illuminate\Support\Facades\DB;
use Throwable;

#[RetryFor(hours: 24)]
#[Backoff([10, 60, 300])]
final class CompensateCreateOrder implements ShouldQueue
{
    use Queueable;

    public function __construct(public string $sagaId, public string $reason) {}

    public function handle(): void
    {
        $saga = DB::transaction(function () {
            $saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
            if ($saga->type !== 'create_order_chain') { return $saga; }
            if ($saga->status === 'running' && in_array('charge-payment', $saga->completed_steps, true)) {
                $saga->update(['status'=>'stuck','failure_reason'=>$this->reason]);
                return $saga; // Recheck pivot under lock; failure selection may be stale.
            }
            if (in_array($saga->status, ['running', 'compensating'], true)) {
                $saga->update(['status' => 'compensating', 'failure_reason' => $this->reason]);
            }

            return $saga;
        });
        if ($saga->type !== 'create_order_chain' || $saga->status !== 'compensating') {
            return;
        }

        // Include the silent in-flight step: its remote effect may have committed.
        // Undo must record a tombstone even when nothing exists yet.
        $undo = array_values(array_unique([...$saga->completed_steps, ...($saga->current_step ? [$saga->current_step] : [])]));
        foreach (array_reverse($undo) as $name) {
            CreateOrderSaga::step($name, $saga->id)->compensate($saga, "{$saga->id}:{$name}:undo");

            DB::transaction(function () use ($name) {
                $saga = Saga::whereKey($this->sagaId)->lockForUpdate()->firstOrFail();
                $saga->update(['completed_steps' => array_values(array_diff($saga->completed_steps, [$name])), 'current_step' => null]);
            });
        }

        DB::transaction(function () use ($saga) {
            Saga::whereKey($saga->id)->update(['status' => 'compensated']);
            // The order left its semantic lock ("pending") for a final state.
            Order::whereKey($saga->payload['order_id'])->update(['status' => 'rejected']);
        });
    }

    public function failed(Throwable $e): void
    {
        // A compensation that cannot succeed is an incident, not a retry.
        Saga::whereKey($this->sagaId)->update(['status' => 'stuck', 'failure_reason' => $e->getMessage()]);
    }
}

// app/Sagas/CreateOrderSaga.php — the orchestrator-lite: a job chain.
php
<?php

namespace App\Sagas;

use App\Models\Saga;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\RetryFor;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

#[Tries(5)]
#[Backoff([5, 30, 120])]
final class ChargePayment extends SagaStep
{
    public static function name(): string
    {
        return 'charge-payment';
    }

    protected function perform(Saga $saga, string $key): void
    {
        $response = Http::withHeaders(['Idempotency-Key' => $key])->connectTimeout(2)->timeout(5)
            ->post(config('services.payments.url').'/charges', [
                'charge_id' => $saga->id,
                'amount' => $saga->payload['total_cents'],
            ]);
        if ($response->status() === 402) {
            throw new StepRejected('card declined');
        }
        $response->throw();
    }

    public function compensate(Saga $saga, string $key): void
    {
        $response=Http::withHeaders(['Idempotency-Key' => $key])->connectTimeout(2)->timeout(5)
            ->post(config('services.payments.url').'/refunds', ['charge_id' => $saga->id]);
        // Contract: 404 records cancellation so a late charge is refused.
        if ($response->status() !== 404) { $response->throw(); }
    }
}

// After the pivot: retried for a day, never compensated.

A 404 from the demonstration refund endpoint means the participant has recorded cancellation even if no charge exists; this is an explicit contract, not a universal payment API rule. The host application supplies Order, participant tables, service bindings, broker configuration and HTTP endpoints. Copy split classes according to their App\... namespaces; there is one namespace per PHP file.

Broker differences ​

RabbitMQ ​

Use durable command queues per participant and a durable reply queue; the Go sample declares quorum queues. Manual reply acknowledgement follows saga-state commit. A publisher confirm must be checked for nack; a mandatory return must also be checked for routing failure. The Go sender serializes publication on a dedicated channel so its one-entry return buffer cannot fill with a batch. A timed-out channel is closed and recreated rather than reused with stale confirmations.

PublishWithContext in amqp091-go cannot interrupt an in-flight socket write; configure connection-level write deadlines in the host application. A context alone is not a hard transport I/O bound.

go
// Package rabbitmq carries saga commands and replies over RabbitMQ: one
// durable command queue per participant, one reply queue for the
// orchestrator, and the saga id as the AMQP correlation id.
package rabbitmq

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"

	amqp "github.com/rabbitmq/amqp091-go"

	"academy/saga-pattern/after/saga"
)

const ReplyQueue = "order-saga.replies"

type Transport struct {
	ch      *amqp.Channel
	mu      sync.Mutex
	returns <-chan amqp.Return
}

func New(ch *amqp.Channel, participants ...string) (*Transport, error) {
	for _, q := range append(participants, ReplyQueue) {
		if q != ReplyQueue {
			q += ".commands"
		}
		// durable=true, autoDelete=false, exclusive=false, noWait=false
		if _, err := ch.QueueDeclare(q, true, false, false, false, amqp.Table{
			"x-queue-type": "quorum",
		}); err != nil {
			return nil, err
		}
	}
	// Publisher confirms: Send only returns after the broker took the message.
	if err := ch.Confirm(false); err != nil {
		return nil, err
	}
	return &Transport{ch: ch, returns: ch.NotifyReturn(make(chan amqp.Return, 1))}, nil
}

func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	body, err := json.Marshal(cmd)
	if err != nil {
		return err
	}
	// The default exchange routes by queue name. One outstanding publish under
	// mu ensures the return buffer cannot overflow. This channel must be dedicated.
	// A timeout closes it: reconnect instead of attributing a late return to a new send.
	conf, err := t.ch.PublishWithDeferredConfirmWithContext(ctx, "", participant+".commands", true, false,
		amqp.Publishing{
			ContentType:   "application/json",
			DeliveryMode:  amqp.Persistent,
			CorrelationId: cmd.SagaID,           // ties the reply to the saga
			ReplyTo:       ReplyQueue,           // where the participant answers
			MessageId:     cmd.IdempotencyKey(), // the participant's dedup key
			Type:          string(cmd.Action),
			Body:          body,
		})
	if err != nil {
		return err
	}
	ok, err := conf.WaitContext(ctx)
	if err != nil {
		_ = t.ch.Close()
		return err
	}
	if !ok {
		return fmt.Errorf("broker nacked saga command")
	}
	select {
	case r, open := <-t.returns:
		if !open {
			return fmt.Errorf("reply channel closed")
		}
		return fmt.Errorf("unroutable saga command: %d %s", r.ReplyCode, r.ReplyText)
	default:
		return nil
	}
}

// Replies consumes the reply queue with manual acks: a reply is acked only
// after the saga row and the next command are committed.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
	if err := t.ch.Qos(32, 0, false); err != nil {
		return err
	}
	deliveries, err := t.ch.ConsumeWithContext(ctx, ReplyQueue, "orchestrator", false, false, false, false, nil)
	if err != nil {
		return err
	}
	for d := range deliveries {
		var r saga.Reply
		if err := json.Unmarshal(d.Body, &r); err != nil {
			return fmt.Errorf("malformed reply remains unacked for operator repair: %w", err)
		}
		r.SagaID = d.CorrelationId
		if err := handle(ctx, r); err != nil {
			if nackErr := d.Nack(false, true); nackErr != nil {
				return nackErr
			}
			return err
		}
		if err := d.Ack(false); err != nil {
			return err
		}
	}
	if ctx.Err() != nil {
		return ctx.Err()
	}
	return fmt.Errorf("RabbitMQ reply consumer closed: reconnect")
}
php
<?php

namespace App\Sagas\Messaging\RabbitMQ;

use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

final class RabbitTransport implements SagaTransport
{
    public function send(string $participant, array $command): void
    {
        SagaCommand::dispatch($command)
            ->onConnection('rabbitmq')
            ->onQueue("{$participant}.commands");
    }
}

// Runs in the participant service: php artisan queue:work rabbitmq --queue=inventory.commands
php
<?php

namespace App\Sagas\Messaging\RabbitMQ;

use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

final class SagaCommand implements ShouldQueue
{
    use Queueable;

    public function __construct(public array $command) {}

    public function handle(StepWork $work): void
    {
        $reply = Participant::run($this->command, $work);

        SagaReply::dispatch($reply)
            ->onConnection('rabbitmq')
            ->onQueue('order-saga.replies');
    }
}

// Runs in the order service: php artisan queue:work rabbitmq --queue=order-saga.replies
php
<?php

namespace App\Sagas\Messaging\RabbitMQ;

use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\SagaOrchestrator;
use App\Sagas\Messaging\SagaTransport;
use App\Sagas\Messaging\StepWork;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

final class SagaReply implements ShouldQueue
{
    use Queueable;

    public function __construct(public array $reply) {}

    public function handle(SagaOrchestrator $orchestrator): void
    {
        // The worker acks the message only after handle() returns.
        $orchestrator->onReply($this->reply);
    }
}

The Laravel adapter uses vladimir-yuldashev/laravel-queue-rabbitmq and serialized Laravel jobs. Both ends need the job classes; external producers need the package's custom RabbitMQJob integration. The verified package publishBasic delegates to basic_publish; do not infer the Go sender's confirm protocol from successful Laravel dispatch. The durable deadline still retries missing commands/replies. For a strict outbox handoff, supply a confirmed publisher and compatible worker envelope. Direct Reply-To is at-most-once and unsuitable as the sole durable record of a saga reply. A malformed Go reply remains unacked for operator repair; configure an explicit parking policy before unattended operation.

Kafka ​

Key by saga id within each command/reply topic. This places one saga's records in a topic partition, but creates no total order across different participant topics. The Go consumer disables automatic commits, stops on failure and closes its client so a new client resumes committed offsets. Re-entering a failed poll loop on the same client can skip its already-fetched local position. Handler duration must fit the rebalance budget.

go
// Package kafka carries saga commands and replies over Kafka: one command
// topic per participant, one reply topic, and the saga id as the record key
// so every message of one saga lands in one partition WITHIN EACH TOPIC. Different topics have no shared order.
package kafka

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"

	"github.com/twmb/franz-go/pkg/kgo"

	"academy/saga-pattern/after/saga"
)

const ReplyTopic = "order-saga.replies"

type Transport struct {
	cl *kgo.Client
}

func New(brokers ...string) (*Transport, error) {
	cl, err := kgo.NewClient(
		kgo.SeedBrokers(brokers...),
		kgo.RequiredAcks(kgo.AllISRAcks()),
		kgo.ConsumerGroup("order-saga-orchestrator"),
		kgo.ConsumeTopics(ReplyTopic),
		kgo.BlockRebalanceOnPoll(),
		kgo.DisableAutoCommit(), // commit only after the saga row is committed
	)
	if err != nil {
		return nil, err
	}
	return &Transport{cl: cl}, nil
}

func (t *Transport) Close() { t.cl.Close() }

func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
	body, err := json.Marshal(cmd)
	if err != nil {
		return err
	}
	rec := &kgo.Record{
		Topic: participant + ".commands",
		Key:   []byte(cmd.SagaID), // same saga, same partition, same order
		Value: body,
		Headers: []kgo.RecordHeader{
			{Key: "reply-topic", Value: []byte(ReplyTopic)},
			{Key: "idempotency-key", Value: []byte(cmd.IdempotencyKey())},
		},
	}
	return t.cl.ProduceSync(ctx, rec).FirstErr()
}

// Replies polls the reply topic. Offsets are committed after the batch is
// handled, so a crash replays replies, which the state machine ignores
// when they no longer match the step in flight.
// Replies owns the client lifecycle: after any exit, create a NEW Transport.
// Handler time must remain below the rebalance timeout.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
	defer t.cl.CloseAllowingRebalance()
	for {
		fetches := t.cl.PollFetches(ctx)
		if fetches.IsClientClosed() || ctx.Err() != nil {
			return ctx.Err()
		}
		var errs []error
		fetches.EachError(func(_ string, _ int32, err error) { errs = append(errs, err) })
		if len(errs) > 0 {
			return errors.Join(errs...)
		}
		var handleErr error
		fetches.EachRecord(func(r *kgo.Record) {
			if handleErr != nil {
				return
			}
			var reply saga.Reply
			if err := json.Unmarshal(r.Value, &reply); err != nil {
				handleErr = fmt.Errorf("malformed reply %s/%d/%d requires repair: %w", r.Topic, r.Partition, r.Offset, err)
				return
			}
			reply.SagaID = string(r.Key)
			handleErr = handle(ctx, reply)
		})
		if handleErr != nil {
			// Do not commit: the group re-reads from the last commit on restart.
			return handleErr
		}
		if err := t.cl.CommitUncommittedOffsets(ctx); err != nil {
			return err
		}
		t.cl.AllowRebalance()
	}
}
php
<?php

namespace App\Sagas\Messaging\Kafka;

use App\Sagas\Messaging\SagaTransport;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;

final class KafkaTransport implements SagaTransport
{
    public function send(string $participant, array $command): void
    {
        $sent = Kafka::publish(config('services.kafka.brokers'))
            ->onTopic("{$participant}.commands")
            ->withMessage(new Message(
                headers: ['reply-topic' => 'order-saga.replies'],
                body: $command,
                key: $command['saga_id'],
            ))
            ->send();
        if (!$sent) { throw new \RuntimeException("Kafka publish not confirmed"); }
    }
}

// app/Console/Commands/ConsumeSagaReplies.php — run under a process monitor.
php
<?php

namespace App\Console\Commands;

use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;

final class ConsumeSagaReplies extends Command
{
    protected $signature = 'saga:consume-replies';

    protected $description = 'Drive the order saga from the order-saga.replies topic.';

    public function handle(SagaOrchestrator $orchestrator): void
    {
        Kafka::consumer(['order-saga.replies'], 'order-saga-orchestrator', config('services.kafka.brokers'))
            ->withManualCommit()->stopOnFailure()
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($orchestrator) {
                $body = $message->getBody();
                $orchestrator->onReply(is_array($body) ? $body : json_decode($body, true, 512, JSON_THROW_ON_ERROR));
                // Commit the offset only after the saga row is committed.
                $consumer->commit($message);
            })
            ->build()
            ->consume();
    }
}

// app/Console/Commands/ConsumeInventoryCommands.php — in the inventory service.
php
<?php

namespace App\Console\Commands;

use App\Sagas\Messaging\Participant;
use App\Sagas\Messaging\StepWork;
use Illuminate\Console\Command;
use Junges\Kafka\Contracts\ConsumerMessage;
use Junges\Kafka\Contracts\MessageConsumer;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;

final class ConsumeInventoryCommands extends Command
{
    protected $signature = 'saga:consume-inventory';

    protected $description = 'Run saga commands addressed to the inventory service.';

    public function handle(StepWork $work): void
    {
        $brokers = config('services.kafka.brokers');

        Kafka::consumer(['inventory.commands'], 'inventory', $brokers)
            ->withManualCommit()->stopOnFailure()
            ->withHandler(function (ConsumerMessage $message, MessageConsumer $consumer) use ($work, $brokers) {
                $body = $message->getBody();
                $reply = Participant::run(is_array($body) ? $body : json_decode($body, true, 512, JSON_THROW_ON_ERROR), $work);

                $sent = Kafka::publish($brokers)
                    ->onTopic('order-saga.replies')
                    ->withMessage(new Message(body: $reply, key: $reply['saga_id']))
                    ->send();
        if (!$sent) { throw new \RuntimeException("Kafka publish not confirmed"); }
                $consumer->commit($message);
            })
            ->build()
            ->consume();
    }
}

Laravel uses mateusjunges/laravel-kafka, withManualCommit() and stopOnFailure(). Commit only after state handling; check producer delivery results. Kafka transactions cannot atomically include the saga's PostgreSQL state or an external charge. Retention must cover maximum recovery time, and compaction of status records is not a substitute for a transition audit log.

Redis Streams ​

Commands use one stream per participant; replies use a consumer group. The sample creates the group at 0 to include existing replies, acknowledges only after the state transition, and scans XAUTOCLAIM with its returned cursor. Reclaim time is an operational idle threshold; a saga deadline is a business recovery threshold. Set them independently.

go
// Package redisstreams carries saga commands and replies over Redis Streams:
// one stream per participant's commands, one reply stream, and a consumer
// group so several orchestrator instances share the replies.
package redisstreams

import (
	"context"
	"encoding/json"
	"errors"
	"strings"
	"time"

	"github.com/redis/go-redis/v9"

	"academy/saga-pattern/after/saga"
)

const (
	ReplyStream = "order-saga:replies"
	Group       = "orchestrator"
)

type Transport struct {
	rdb      *redis.Client
	consumer string // unique per process incarnation, not a shared hostname
}

func New(rdb *redis.Client, consumer string) *Transport {
	return &Transport{rdb: rdb, consumer: consumer}
}

func (t *Transport) Send(ctx context.Context, participant string, cmd saga.Command) error {
	body, err := json.Marshal(cmd)
	if err != nil {
		return err
	}
	return t.rdb.XAdd(ctx, &redis.XAddArgs{
		Stream: participant + ":commands",
		// Retention is an operator policy: do not trim unresolved commands blindly.
		Values: map[string]any{
			"saga_id":         cmd.SagaID,
			"idempotency_key": cmd.IdempotencyKey(),
			"reply_stream":    ReplyStream,
			"body":            body,
		},
	}).Err()
}

// Replies reads with XREADGROUP and acknowledges with XACK after handle
// succeeds. Unacked entries stay in the pending entries list; a reclaimer
// (XAUTOCLAIM) picks them up if this consumer dies.
func (t *Transport) Replies(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
	err := t.rdb.XGroupCreateMkStream(ctx, ReplyStream, Group, "0").Err()
	if err != nil && !strings.HasPrefix(err.Error(), "BUSYGROUP") {
		return err
	}
	for ctx.Err() == nil {
		streams, err := t.rdb.XReadGroup(ctx, &redis.XReadGroupArgs{
			Group:    Group,
			Consumer: t.consumer,
			Streams:  []string{ReplyStream, ">"},
			Count:    32,
			Block:    5 * time.Second,
		}).Result()
		if errors.Is(err, redis.Nil) {
			continue // block timed out, nothing new
		}
		if err != nil {
			return err
		}
		for _, s := range streams {
			for _, msg := range s.Messages {
				body, _ := msg.Values["body"].(string)
				var r saga.Reply
				if err := json.Unmarshal([]byte(body), &r); err != nil {
					continue // malformed: leave it pending for inspection
				}
				if err := handle(ctx, r); err != nil {
					continue // not acked: stays in the PEL and is retried
				}
				if err := t.rdb.XAck(ctx, ReplyStream, Group, msg.ID).Err(); err != nil {
					return err
				}
			}
		}
	}
	return ctx.Err()
}

// Reclaim takes over replies that another orchestrator instance read but
// never acknowledged (it crashed mid-transition). Run it on a ticker in
// every instance; MinIdle must exceed the slowest normal transition.
func (t *Transport) Reclaim(ctx context.Context, handle func(context.Context, saga.Reply) error) error {
	start := "0-0"
	for {
		msgs, next, err := t.rdb.XAutoClaim(ctx, &redis.XAutoClaimArgs{
			Stream:   ReplyStream,
			Group:    Group,
			Consumer: t.consumer,
			MinIdle:  time.Minute,
			Start:    start,
			Count:    32,
		}).Result()
		if err != nil {
			return err
		}
		for _, msg := range msgs {
			body, _ := msg.Values["body"].(string)
			var r saga.Reply
			if json.Unmarshal([]byte(body), &r) != nil || handle(ctx, r) != nil {
				continue
			}
			if err := t.rdb.XAck(ctx, ReplyStream, Group, msg.ID).Err(); err != nil {
				return err
			}
		}
		if next == "0-0" {
			return nil // scanned the whole pending entries list
		}
		start = next
	}
}
php
<?php

namespace App\Sagas\Messaging\Redis;

use App\Sagas\Messaging\SagaTransport;
use Illuminate\Support\Facades\Redis;

final class RedisStreamsTransport implements SagaTransport
{
    public function send(string $participant, array $command): void
    {
        $id=Redis::xadd("{$participant}:commands", '*', [
            'saga_id' => $command['saga_id'],
            'reply_stream' => 'order-saga:replies',
            'body' => json_encode($command),
        ]);
        if ($id===false) { throw new \RuntimeException("XADD failed"); }
    }
}

// app/Console/Commands/ConsumeSagaRepliesFromStream.php
php
<?php
namespace App\Console\Commands;

use App\Sagas\Messaging\SagaOrchestrator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Throwable;

final class ConsumeSagaRepliesFromStream extends Command
{
    protected $signature='saga:consume-replies-redis';
    protected $description='Consume and reclaim saga replies (phpredis client).';
    public function handle(SagaOrchestrator $orchestrator): void
    {
        $stream='order-saga:replies';$group='orchestrator';$consumer=gethostname().'-'.getmypid().'-'.bin2hex(random_bytes(4));
        try { Redis::xgroup('CREATE',$stream,$group,'0',true); }
        catch (Throwable $e) { if (!str_contains($e->getMessage(),'BUSYGROUP')) { throw $e; } }
        $cursor='0-0';$running=true;
        $this->trap([SIGTERM,SIGINT],function () use (&$running) { $running=false; });
        while ($running) {
            $claimed=Redis::xautoclaim($stream,$group,$consumer,60000,$cursor,32);
            if ($claimed===false) { throw new \RuntimeException('XAUTOCLAIM failed'); }
            $cursor=$claimed[0];$this->apply($orchestrator,$stream,$group,$claimed[1]??[]);
            $batch=Redis::xreadgroup($group,$consumer,[$stream=>'>'],32,1000);
            // The facade may prefix returned keys; iterate values, not $batch[$stream].
            foreach ($batch?:[] as $messages) { $this->apply($orchestrator,$stream,$group,$messages); }
        }
    }
    private function apply(SagaOrchestrator $orchestrator,string $stream,string $group,array $messages): void
    {
        foreach ($messages as $id=>$fields) {
            try { $orchestrator->onReply(json_decode($fields['body'],true,512,JSON_THROW_ON_ERROR)); }
            catch (Throwable $e) { report($e); continue; } // pending; repair poison replies explicitly
            if (Redis::xack($stream,$group,[$id])===false) { throw new \RuntimeException('XACK failed'); }
        }
    }
}

The PHP worker targets phpredis argument order, uses a unique consumer incarnation and iterates returned stream values so connection prefixes do not hide messages. Native client timeout settings must exceed the bounded blocking read. Do not trim unresolved commands merely because the stream looks large: trimming can remove bodies referenced by the PEL. Redis persistence/failover settings define durability; XADD success alone is not an unconditional disk guarantee.

In production systems ​

Checkable system behaviorDesign consequence
PostgreSQL locks and transactions govern local state changesKeep remote I/O outside participant transaction locks
RabbitMQ confirms and consumer acknowledgements are separateConfirming a command says nothing about the saga's business result
Kafka consumer offsets govern replay positionStore-before-commit and idempotent transition handling are required
Redis Streams pending entries survive consumer failure within configured durabilityReclaim deliveries, but retain business state separately
Laravel jobs can retry and exhaust attemptsFailure hooks must preserve ambiguous outcomes for recovery
NATS JetStream, Pulsar and SQS provide transport-specific acknowledgement/replay mechanismsNone supplies the business compensation automatically; see Other Brokers

In architecture: from a single process to a distributed system ​

Monolith ​

If stock, orders and balance truly share one database and owner, a local transaction is simpler. Adding a remote payment gateway creates a separate consistency boundary even inside one process. The in-process runner illustrates sequencing, while the durable store is needed if a process crash must not erase progress.

Modular monolith ​

Modules can exchange commands through interfaces while sharing a durable saga table. A PENDING order is a semantic lock visible to other modules. Do not let an unrelated module bypass it with an unconditional status update. Separate databases or external suppliers require the same recovery policy as microservices.

Microservices ​

Order owns coordination, Inventory owns reservations, Payments owns provider operation ids, and Shipping owns shipment state. A command carries saga id, step, action and immutable payload. Each participant commits its local effect and dedup result, then replies; a duplicate command returns the same logical result. Keep domain decisions in their owning service rather than moving all business logic into the orchestrator.

text
1 POST /orders -> Order PENDING + Saga + outgoing intent -> 202
2 Inventory command -> reservation + inbox -> reply
3 Order transition -> payment command -> payment result
4 Order pivot decision -> shipping command
5 Final reply -> Order APPROVED; client polls status or receives notification

Distributed data ​

A stale replica can report PENDING after the primary completed a saga; read authoritative state for decisions. Multi-region active writers require a real single-writer/consensus or conflict-resolution design for each saga. Host clock skew can prematurely expire steps, hence the database clock in the examples. Failover may replay commands or lose a less-durable transport acknowledgement; stable participant keys and reconciliation remain necessary. Links: Replication, Distributed SQL.

Scaling path ​

Load / complexityChangePreserve
Small workflowOne coordinator worker with durable DBExplicit state and recovery ownership
More concurrent sagasMore workers, indexed deadlines, small batchesSerialize one saga transition
Broker/DB pressurePartition by saga id, bound in-flight work, tune batch sizeDo/undo fencing and participant idempotency
Many long timers / branchesAdopt durable workflow executionBusiness compensation and definition versioning
Multi-regionAssign saga ownership and failover policyOne authoritative transition history

Lab: failure experiments ​

All scenarios below are expected, not run. No Docker or broker cluster is started. Host-only compilation/unit checks are recorded in HANDOFF separately. Database and broker experiments need a reader-provisioned development environment and participant implementations.

sh
cd docs/snippets/messaging/saga-pattern/go
# expected, not run: pure state-machine scenarios pass without brokers
go test ./after/saga -v
# expected, not run: first demo compensates; second completes
go run ./inprocess
# expected, not run: in-memory choreography shows approve/reject paths
go run ./choreography
ExperimentActionExpected, not run
Business rejectionReply false for charge-paymentRelease stock; no refund for a definitive uncommitted rejection
Lost charge replyPersist charge, suppress reply until deadline budgetSame do key retried; safe undo includes charge itself
Compensation failureReject every undo attemptState becomes Stuck; stock not falsely marked released
Duplicate repliesDeliver StockReserved twice after advancementVersion advances once for that transition
Reply consumer crashKill after saga commit before broker ackRedelivery has no repeated state effect
Stale sweeperSelect expired candidate, then process valid reply before expire locks itFresh deadline is rechecked; no stale timeout transition
Undo before doApply release tombstone, then delayed reservationLate do refused, stock unchanged
sql
-- Reader-provisioned PostgreSQL; run after loading the sample schema.
SELECT id,status,step,attempts,version,deadline_at FROM sagas ORDER BY id;
SELECT saga_id,version,step,from_status,to_status FROM saga_steps ORDER BY saga_id,version;
SELECT count(*) FROM saga_outbox WHERE published_at IS NULL;
-- expected, not run: committed transitions explain the current state;
-- unconfirmed outgoing commands remain eligible for relay/recovery.
sh
# In a configured Laravel 13 host application:
php artisan migrate
php artisan schedule:work
php artisan saga:consume-replies-redis
# expected, not run: expired running/compensating steps are retried or parked.
# To test the pure PHP decisions without Laravel:
php docs/snippets/messaging/saga-pattern/php/Tests/DefinitionTest.php

Verify the participant's durable effects as well as the saga row. A state-machine test cannot establish that a payment provider honors cancellation tombstones, a refund is idempotent, or a broker configuration survives failover.

Common misconceptions ​

BeliefReality
Saga is distributed rollbackIt uses new semantic transactions after local commits
Compensation erases historyRefunds and cancellations remain visible business events
Local SERIALIZABLE makes the saga serializableCross-step interleaving still exists
Timeout means the step failedThe effect may have committed
Any failure means refundPost-pivot policy can require forward recovery
Broker redelivery replaces saga storageIt does not encode business progress or compensation inputs
Choreography removes couplingIt distributes coupling into event contracts
An orchestrator must be one processWorkers can share serialized durable state
ShouldBeUnique is exactly-onceIt is bounded dispatch suppression, not effect deduplication
Publisher confirm means order completedIt confirms transport acceptance, not business success
A DLQ resolves a stuck sagaIt stores a failed delivery; someone still owns recovery
Delete the row to fix the incidentThat can lose the evidence required to reconcile money

Cheat sheet ​

TopicRemember
BoundaryOne local transaction per participant effect
IdentityStable saga id plus separate do/undo operation keys
StatePersist current step, direction, attempts, deadline and version
PublicationPrefer state + outbox; document any timer-recovered send gap
Reply handlingCommit transition before broker acknowledgement
TimeoutUnknown outcome; do not fabricate a business rejection
CompensationIdempotent, domain-specific, able to fail
PivotDecide where automatic backward recovery stops
IsolationUse semantic locks, deltas, versions and operation history
Late workFence do-after-undo with durable cancellation state
RetentionCover maximum replay, recovery and provider-key windows
OperationsAlert on open/stuck age; reconcile with participant truth
VersioningPreserve definitions required by in-flight workflows
TestingExercise every failure edge, duplicates and ambiguous outcomes

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a local rollback not undo a remote charge? Must-know ​

Answer

Answer: The provider committed outside the local transaction. A separate idempotent refund or reconciliation operation is required.

2 — Why must compensation release a reservation instead of restoring an old stock count? Must-know ​

Answer

Answer: Other orders may have changed stock since reservation. Releasing the named quantity amends this saga's effect without overwriting theirs.

3 — What is different about a declined payment and a timed-out payment? Important ​

Answer

Answer: A definitive decline states that the forward effect did not commit. A timeout leaves the outcome unknown and may require querying, deduplicated retry or cancellation of the silent step.

4 — Which three fields correlate a reply with the current transition? Important ​

Answer

Answer: Saga id, step and action. A separate operation key binds retries to one immutable participant command.

5 — Why can an undo need a tombstone even when nothing exists to undo? Good to know ​

Answer

Answer: A delayed forward command may arrive later. Durable cancellation state prevents it from creating a new effect after compensation.

6 — Does a Kafka transaction make PostgreSQL state and payment capture atomic? Must-know ​

Answer

Answer: No. Its supported Kafka scope does not include arbitrary SQL transactions or an external provider's effect.

7 — What recovers a lost Laravel after-commit send in this example? Important ​

Answer

Answer: The persisted deadline and sweeper. This is a delayed recovery strategy; afterCommit itself is not atomic publication.

8 — What happens when shipment retries are exhausted after the pivot? Important ​

Answer

Answer: The saga becomes Stuck and is reconciled through forward recovery under the business policy; automatic refund is not assumed safe.

9 — Why is catching PostgreSQL 23505 and committing the same failed transaction incorrect? Important ​

Answer

Answer: The transaction is aborted. Use an explicit conflict-safe statement or roll back and retry before continuing work.

10 — Can compensations always run in exact reverse order? Good to know ​

Answer

Answer: Reverse order fits a dependent linear sequence. Actual dependency and risk rules may require another order or permit parallel compensation.

Glossary ​

TermMeaning
SagaCoordinated recoverable sequence of local transactions
Local transactionAtomic commit inside one participant boundary
Long-lived transaction / LLTWork whose duration motivated smaller transaction boundaries
ParticipantOwner of one local effect and its recovery contract
OrchestrationCoordinator-driven choice of next command
ChoreographyParticipant reactions linked by events
Process ManagerStateful component deciding process routing
CompensationNew business transaction amending an earlier effect
Backward recoveryApplying compensations to an executed prefix
Forward recoveryRetrying or repairing remaining forward work
CompensableStep with a defined semantic undo
PivotBusiness boundary after which forward recovery is required
RetryableStep policy permitting repeated execution under one operation identity
Ambiguous outcomeEffect may have committed but result is unknown
DeadlinePersisted time at which recovery becomes eligible
TimeoutFailure to observe completion within a time budget
Semantic lockBusiness state preventing incompatible transitions
Commutative updateDelta whose arithmetic composition is order-independent
Pessimistic viewReordering risky visibility until retryable phases
Reread valuesValidate earlier reads before a later write
Version fileOperation history used to enforce legal sequencing
By valueRisk-based choice of coordination strength
Lost updateOne operation overwrites another's effect
Dirty read at saga levelReading provisional business state already locally committed
Nonrepeatable readDifferent saga steps observe changed values
Idempotency keyIdentity making retries refer to one logical effect
InboxDurable participant dedup/result record
OutboxDurable outgoing intent committed with local state
TombstoneRetained cancellation/terminal fact fencing late work
SEC logSaga execution coordinator's durable recovery history
StuckAutomatic recovery stopped; intervention required
ReconciliationComparing authoritative participant effects to process state
Definition versionVersion of transition rules retained for in-flight work
Publisher confirmRabbitMQ producer-side acceptance acknowledgement
Consumer acknowledgementDelivery settlement after processing
PELRedis Streams pending entries list
XAUTOCLAIMRedis command transferring idle pending entries
ShouldBeUniqueLaravel dispatch suppression contract backed by a cache lock
UniqueForLaravel duration for a unique job's lock
afterCommitDefer action until transaction commit; not an outbox
FOR UPDATEPostgreSQL row lock used to serialize a state transition
SKIP LOCKEDPostgreSQL work-selection behavior that skips locked rows

References ​

Built by Morteza Negahi