Skip to content

Designing for Failure & Reliable Messaging in Microservices ​

"A consequence of using services as components, is that applications need to be designed so that they can tolerate the failure of services." — Martin Fowler and James Lewis, Microservices (25 March 2014), section "Design for failure"

Summary: A bounded context stays correct when its neighbours fail by treating every message as possibly late, duplicated, reordered or lost: one aggregate and one outbox row per local transaction, an inbox that makes consumers idempotent, a saga with compensations and deadlines for cross-context processes, and a product that shows "pending" honestly. Focus: The failure taxonomy a context must assume, Helland's entities-and-messages model and why exactly-once is a slogan, aggregates as consistency islands, reliable publishing (outbox, polling vs log tailing, per-aggregate order), reliable consuming (inbox, dedup keys, versions, commutative handlers), retries with backoff and poison handling, the Order → Reserve stock → Charge → Ship saga with failure paths and timeouts, eventual consistency as a product decision, degraded modes, idempotency keys at the API edge, testing by failure injection, observability, and anti-patterns. Learning goal: Given a flow that crosses Sales, Fulfilment and Billing, design the messages, the outbox and inbox tables, the saga state and its compensations so that any single failure, duplicate or reordering ends in a correct, explainable state; implement it in Go and Laravel; and prove it with tests that inject the failures.

This chapter belongs to group DD 03 (Data & APIs in Microservices). It is the DDD and microservices view of failure: how one bounded context keeps its own model correct while the others misbehave. The neighbours own the mechanics, and this page links to them instead of repeating them: the resilience patterns at code level (timeouts, retries, circuit breaker, bulkhead) live in Error Handling & Fault Tolerance in Design; the sync-versus-async decision lives in Service Communication; the outbox, DLQ, idempotent consumer and saga mechanics live in Transactional Outbox, Dead-Letter Queue, Idempotent Consumers & the Inbox and Saga Pattern. Here we place them around the aggregate and use them on one running example.

The running example is the one used across the DDD path: an online ordering and fulfilment business with the contexts Sales, Fulfilment, Billing, Catalog and Identity. The flow is: a customer places an order (Sales), stock is reserved (Fulfilment), the card is charged (Billing), a shipment is created (Fulfilment), the order is confirmed (Sales). Each context has its own database (Data Ownership).

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why a context must assume failureWhy it exists
Sagas 1987, Helland 2007, Nygard, Fowler, SRE, AWSWhere it comes from
The eight failures to assumeThe failure taxonomy
Entities, activities, messages, "exactly-once is a lie"Helland's model
Aggregate as island, one transaction per aggregateConsistency islands
Outbox, polling vs log tailing, per-aggregate orderReliable publishing
Inbox, dedup keys, versions, commutative handlersReliable consuming
Partition keys, version checks, gapsOrdering
Backoff, jitter, poison messages, DLQ, parkingRetries and poison messages
Choreography vs orchestration, compensations, timeoutsSagas
Saga state as an aggregateThe saga as an aggregate
Pending/failed states in the productEventual consistency as a product decision
Stale reads, flags, accepting orders when Billing is downDegraded modes
Timeouts, budgets, breakers at the edgeThe context edge
Idempotency-Key on commandsIdempotent commands at the API edge
Failure injection, replay, contract testsTesting
Correlation, causation, lag, DLQ depthObservability
What not to doAnti-patterns
Full codeGo, Laravel
Concrete problems and fixesSolving the classic problems
Which technique for which situationChoosing
Monolith to distributedIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The eight failures a context must assume (each is a block in the taxonomy):

FailureIn plain wordsWhat it breaks if ignoredMain defence
Neighbour downNobody answersThe caller hangs or crashesTimeout, async messaging, degraded mode
Neighbour slowAnswers after the caller gave upThreads pile up, cascadeDeadline, budget, breaker, bulkhead
GarbageA reply that violates the contract or the meaningCorrupted local stateValidation, ACL, contract tests, DLQ
DuplicateThe same message twiceDouble charge, double reservationInbox, idempotency key, natural idempotency
Out of orderMessage 2 before message 1Old state overwrites newPer-key ordering, versions, commutative handlers
LostSent and never arrivedOrder stuck foreverOutbox, at-least-once, deadlines, reconciliation
Partial failureStep 2 of 4 done, step 3 failedMoney taken, nothing dispatchedSaga with compensations
Clock skewTwo machines disagree about "now"Wrong ordering and deadlinesVersions and sequences, deadlines on one clock

The reliable-messaging toolbox:

Building blockLives whereGives youCost
Aggregate + versionInside a contextImmediate consistency of one islandSmall aggregates, retries on conflict
Transactional outboxProducer's database"State changed" and "event will be sent" are one factA relay and a table to prune
Relay (polling or log tailing)Producer sideAt-least-once publicationDuplicates, lag, one more process
Inbox / processed-ids tableConsumer's databaseEffectively-once processingOne row per message, retention policy
Idempotency keyAPI edge and provider callsSafe client retriesA key store
SagaBetween contextsBusiness-level atomicity by compensationState, timers, compensations to design
DLQ / parking lotConsumer sidePoison messages stop blockingSomeone must read it
Deadlines and timersSaga and edgeNo waiting foreverTimeout choices, late replies

Delivery guarantees in one table (details in Delivery Guarantees):

GuaranteeWhat can go wrongWho must copeTypical use
At-most-onceMessage lostThe business, by reconciliationMetrics, best-effort notifications
At-least-onceMessage duplicatedThe consumer, by idempotencyNearly all business messaging
"Exactly-once"A slogan: at-least-once plus dedup, inside one system's boundaryWhoever claims it, at its boundaryKafka transactions between Kafka topics; your database is outside

Saga outcomes of the running example:

EventSaga reactionCompensation
StockRejectedCancel at onceNone: nothing was done
PaymentDeclinedCompensateRelease stock
ShipmentFailedCompensateRefund payment, release stock
Timeout at any stepCompensate with commands that are safe whatever the neighbour didRelease stock, refund (idempotent, tombstones)
Late reply after cancelUndo it againRelease or refund again

Why it exists ​

In a monolith, "place the order, reserve the stock and charge the card" is one database transaction: all three happen or none. After the split, three databases and a network sit in the middle. Fowler and Lewis put it in one line each: services can fail, and "Distributed transactions are notoriously difficult to implement and as a consequence microservice architectures emphasize transactionless coordination between services, with explicit recognition that consistency may only be eventual consistency and problems are dealt with by compensating operations."

The design question changes from "how do I make this atomic?" to "what is true if only half of it happened, and who fixes it?".

Two-phase commit across servicesLocal transactions + messages + compensation
Looks like the monolithLooks different; the business sees "pending"
Locks held across the networkLocks held only inside one database
Every participant must support it (broker, databases, providers)Works with any database and any at-least-once broker
One slow or dead participant blocks allEach step proceeds or times out on its own
Availability of the whole is the product of the partsEach context stays available for its own work
Failure of the coordinator can leave locks in doubtFailure leaves a saga state and a timer that resume
Hard to run across companies (card networks, couriers)Natural: external steps are just messages

The analogy we reuse on this page: registered mail between three offices. Sales, Fulfilment and Billing are separate offices. They never share a filing cabinet. They send letters. A letter can arrive twice (the clerk resent it because the receipt got lost), late, in the wrong order, or never. Each office keeps its own ledger (its database), stamps every incoming letter number in a "received" book (the inbox), and writes outgoing letters in a "to send" tray in the same moment it updates its own ledger (the outbox). A manager (the saga) has a checklist per order, a deadline per step, and a list of "undo" letters for each step that already succeeded.

SalesFulfilmentBillingOrder aggregateversion, status, invariantsStock / Shipment aggregateown invariantsPayment aggregateown invariantsoutbox row (same tx)inbox row (same tx)inbox row (same tx)own databaseown databaseown databaseBroker: at-least-onceduplicated, delayed, lost, reordered, never in a shared transactionInside an island: ACID. Between islands: messages, ids, versions, compensations.

The picture shows three contexts as islands. Inside an island one local transaction is atomic: an aggregate and an outbox or inbox row. Between islands only messages travel, through a broker that is at-least-once. No transaction spans two islands.

Three common misunderstandings, up front ​

  1. "Our broker guarantees exactly-once, so consumers need no dedup." Exactly-once is a property inside a boundary (Kafka's transactions inside Kafka). The moment your handler writes to PostgreSQL, a crash between the write and the offset commit re-delivers the message. You still need an inbox (Reliable consuming).
  2. "A retry is always safe." A retry of a non-idempotent call after a lost response charges the customer twice. AWS: "a best practice is designing APIs to be idempotent, meaning they can be safely retried." (Idempotent commands).
  3. "If Billing is down, Sales must return an error." Sales can accept the order as pending and finish the work when Billing returns. Whether that is allowed is a product decision, not a technical one (Eventual consistency as a product decision, Degraded modes).

Where it comes from ​

Garcia-Molina and Salem, 1987. The paper Sagas (ACM SIGMOD 1987) split a long-lived transaction into a sequence of sub-transactions, each with a compensating transaction that semantically undoes it, so that locks are not held for the whole duration. I could not read the paper directly (the ACM page blocks automated clients and the open PDF is a scan without a text layer), so this description rests on the secondary source microservices.io, which defines a saga as "a reliably coordinated sequence of local transactions".

Nygard, Release It! (first edition 2007). The stability patterns Timeout, Circuit Breaker and Bulkhead. Fowler's bliki entry credits it: "In his excellent book Release It, Michael Nygard popularized the Circuit Breaker pattern to prevent this kind of catastrophic cascade." We use those patterns only as pointers; they live in Error Handling & Fault Tolerance and in Circuit Breaker.

Helland, 2007. Pat Helland's CIDR paper Life beyond Distributed Transactions: an Apostate's Opinion is the base of this chapter. Its three claims: scalable applications work on uniquely identified entities; "Atomic Transactions Cannot Span Entities"; and messaging between entities is "at-least-once", so recipients must remember what they processed. It is the same idea Evans' aggregate has, as Aggregates & Factories shows. His later article Idempotence Is Not a Medical Condition (ACM Queue, 2012) is cited by many sources; I could not fetch it (Cloudflare blocks automated clients), so nothing on this page is quoted from it.

Fowler and Lewis, 2014. The microservices article names "Design for failure" as a characteristic and "transactionless coordination" with compensations as the consistency style.

Richardson, microservices.io (2018 onward). Catalogue pages for Saga, Transactional Outbox, Polling Publisher, Transaction Log Tailing and Idempotent Consumer give the pattern forms used below.

Google SRE and AWS Builders' Library. The SRE book chapter Addressing Cascading Failures defines the failure mode retries can cause; the AWS articles Timeouts, retries, and backoff with jitter and Avoiding fallback in distributed systems (both published 5 December 2019) give the retry and fallback rules used in Retries and Degraded modes.

text
     Year   Source                                     What it added
1    1987   Garcia-Molina & Salem, Sagas               Long transaction = sub-transactions + compensations
2    2007   Nygard, Release It!                        Timeout, circuit breaker, bulkhead as stability patterns
3    2007   Helland, Life beyond Distributed Tx        Entities, no atomic tx across them, at-least-once messages
4    2014   Fowler & Lewis, Microservices              "Design for failure"; eventual consistency + compensations
5    2016   Google SRE book, Cascading Failures        Retry amplification, deadlines, load shedding
6    2018   Richardson, microservices.io               Saga, outbox, polling publisher, log tailing, idempotent consumer
7    2019   AWS Builders' Library                      Backoff with jitter, retry limits, avoid untested fallback

Dates for rows 1, 2, 5 and 6 (the Sagas paper, the first edition of Release It!, the SRE book and the pattern catalogue) are the publication years as generally cited; they are not printed on the pages I saved. Rows 3, 4 and 7 come from pages I read.

The concept catalogue ​

The failure taxonomy Must-know ​

In plain words: Before designing anything, list how the neighbours can misbehave. There are eight ways, and each needs a different answer.

Common misunderstanding: "Failure means an exception." Most failures in messaging are not exceptions: a duplicate or a reordered message is a perfectly valid message arriving at the wrong time, and a slow neighbour never throws anything.

Definition: The failure model of a context is the set of behaviours of its neighbours, the broker and the network that its design must tolerate. The model used here is: crash/down, slow, garbage, duplicate, out-of-order, lost, partial failure (a multi-step process stops in the middle), and clock skew.

text
     Sales                      Broker                     Billing
1    place order (tx commits)
2    outbox row "OrderPlaced"
3    relay publishes ---------> stored, ack LOST (network)
4    relay: no ack, retry ----> stored again (duplicate)
5                               delivers #1 ------------> charge, commit
6                               delivers #2 ------------> same message id: skipped by inbox
7                                                          reply "PaymentCharged" (outbox)
     Failure seen by Sales at step 3: "lost ack" = unknown outcome, never "failed"
FailureHow it shows upReal scenarioProduct-level symptomDefenceWhere in this page
Neighbour downConnection refused, no consumer on the queueBilling deploy, database failoverCheckout error or "pending"Async messaging, deadline, degraded modeDegraded
Neighbour slowp99 latency grows, then timeoutsCard issuer at 8 sThread pool exhaustion, cascadePer-call timeout, deadline propagation, breakerEdge
GarbageSchema violation, impossible values, unknown typeProducer ships qty: -1Corrupt stockValidate at the edge, ACL, contract test, DLQRetries
DuplicateSame message_id twiceRelay crash after publish, broker redelivery after consumer crashCharged twiceInbox, idempotency keyConsuming
Out of orderOrderCancelled before OrderPlacedTwo partitions, retries, parallel consumersCancelled order shows as confirmedPer-key partition, versions, tombstonesOrdering
LostNever arrivesDual write, crash after commit, acks=0, auto-ack then crashOrder stuck pendingOutbox, deadlines, reconciliation jobPublishing
Partial failureSome steps done, one failedStock reserved, card declinedStock held foreverSaga with compensations and timersSagas
Clock skewcreated_at of B earlier than A though B was caused by ATwo hosts, NTP driftWrong "latest wins", premature timeoutsVersions and sequence numbers; deadlines read on the owner's clockOrdering, Sagas

What provides the defence, by product:

ProductDuplicate sourceOrder guaranteeLoss risk
RabbitMQRedelivery after consumer crash or nack with requeue; publisher retry without confirms dedupPer queue, broken by requeue and multiple consumersAuto-ack + crash; unconfirmed publish; non-durable queue
Apache KafkaProducer retry without idempotence; consumer reprocess after rebalancePer partitionacks=0/1 with leader loss; offset committed before processing
Redis StreamsReclaim of pending entries (XAUTOCLAIM) after consumer crashPer streamPersistence setting (AOF fsync policy), XACK before work
Amazon SQSStandard queue is at-least-once; FIFO has a dedup windowStandard: best effort; FIFO per message groupVisibility timeout shorter than work, then delete
Laravel database/Redis queueJob retried after timeout or worker crash (retry_after)None across workerstries exceeded goes to failed_jobs

Product behaviour is covered in Broker Comparison, RabbitMQ, Kafka and Redis Streams & Pub/Sub; the table only names where each failure comes from.

Helland's model: entities, activities, messages Must-know ​

In plain words: Think of the system as many small things (entities), each owning its data and living on one machine. They never change each other's data. They send messages, and they remember who they talked to and what they already processed (activities).

Common misunderstanding: "Exactly-once delivery is a feature I can switch on." Helland's starting assumption is the opposite: most applications use at-least-once messaging, and the recipient "must be prepared in its durable state to be assailed with redundant messages that must be ignored."

Definition: Helland's paper has four parts you need: an entity is a unique key plus its data on one machine, and it is "the scope of serializability"; "Atomic Transactions Cannot Span Entities"; messages are addressed to entities; and an activity is the per-partner state an entity keeps to manage the conversation, including remembering processed messages. About idempotence he writes: "the recipient entity is typically designed to remember that the message has been processed." Mapped to DDD: entity = aggregate instance, activity = the inbox (and a saga for longer conversations).

text
     Order #7 (Sales)                         Stock #mug (Fulfilment)
1    state: pending, v1
2    --- ReserveStock(msg 41) --------------->
3                                              activity[Sales]: seen {} -> apply, seen {41}
4    <-- StockReserved(msg 90) ----------------
5    --- ReserveStock(msg 41) (resent) ------>
6                                              activity[Sales]: 41 seen -> reply again, no effect

At-most-once, at-least-once, "exactly-once":

ClaimWhat it really meansCostWhere it is true
At-most-onceSend once, never retry; a lost message is goneSilent lossFire-and-forget logging, metrics
At-least-onceRetry until acknowledged; duplicates possibleConsumer must dedupMost brokers by default
Exactly-once deliveryImpossible to guarantee over an unreliable link when the sender cannot tell "lost" from "processed, ack lost" (the two generals problem)n/aNowhere on a real network
Effectively-once processingAt-least-once delivery plus an idempotent effectAn inbox or natural idempotencyYour context, by design
Kafka exactly-once semanticsAtomic read-process-write between Kafka topics inside Kafka transactionsProducer ids, transactional commitsInside Kafka; not your SQL database

The two generals argument is the reason the first column of the taxonomy has "lost" and "duplicate" as two sides of one uncertainty: the sender who does not see an acknowledgement cannot know which happened, so it must resend and the receiver must tolerate it. See Delivery Guarantees for the broker side.

Real scenarios: the same card charged twice after a gateway timeout; two shipments for one order after a consumer rebalance; a coupon redeemed twice because the HTTP response was lost; a welcome email sent twice after a worker restart.

Fix: make every effect either naturally idempotent (set status to confirmed; "reserve stock for order 7" keyed by the order id) or guarded by a dedup record (inbox, idempotency key). Code in Reliable consuming.

Aggregates as consistency islands Must-know ​

In plain words: Inside one aggregate the database keeps everything true at every commit. Between aggregates, and above all between contexts, nothing is true at the same moment; things become true one after another through messages.

Common misunderstanding: "I can update the Order and the Stock in one transaction because they are in the same database." In a modular monolith you technically can, and you then lose the option of ever separating them, and you lock two aggregates for one request. The boundary is a design choice, not a deployment fact (Aggregates & Factories).

Definition: The unit of work of this chapter is: one aggregate + one outbox row (or one inbox row + effect) per local transaction. Everything else is a message. Evans: "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously." (Evans, DDD Reference, quoted in Aggregates & Factories).

text
     Request: place order                          What commits together
1    BEGIN
2    INSERT orders (id=o-1, status=pending, version=1)      aggregate
3    INSERT outbox (type=OrderPlaced, key=o-1, seq=1)       the promise to tell others
4    COMMIT
5    -- later, elsewhere, other transactions:
6    relay publishes; saga starts (own tx); Fulfilment reserves (own tx)
Consistency scopeMechanismGuaranteeExample
Inside one aggregateLocal transaction, version columnInvariants at every commitOrder total equals the sum of its lines
Aggregate and its outgoing messageOutbox in the same transaction"State changed" iff "message will be sent"OrderPlaced
Message and its effect in the consumerInbox in the same transaction"Processed" iff "effect applied"Stock reserved once
Across aggregates in one contextMessage or saga, sometimes one tx by exceptionEventualOrder status follows saga outcome
Across contextsSaga + compensationEventual, with deadlinesOrder, stock, payment, shipment

Four reasons to break the one-aggregate-per-transaction rule exist (Vernon, summarised in Aggregates & Factories); none of them is "it is easier".

Fix: code in Go and Laravel: PlaceOrder is one transaction with one aggregate and one outbox row.

Reliable publishing: the transactional outbox Must-know ​

In plain words: Do not talk to the broker inside the business transaction. Write the message to a table in the same transaction, and let another process send it. If the process dies after sending but before ticking the row, it sends again.

Common misunderstanding: "I commit first, then publish; that is almost atomic." It is not: a crash between the two lines loses the event, and publishing before commit sends events for orders that roll back. Microservices.io states the problem: "How to atomically update the database and send messages to a message broker?" and the answer: "store the message in the database as part of the transaction that updates the business entities. A separate process then sends the messages to the message broker."

Definition: The pattern has a sender (the service), an outbox table in the service's own database, and a message relay. Benefits, per the pattern page: "2PC is not used"; messages are sent "if and only if the database transaction commits"; messages go out "in the order they were sent by the application". Its stated issue: "The Message relay might publish a message more than once", so "a message consumer must be idempotent".

text
     Producer tx            Outbox table                Relay                 Broker
1    BEGIN
2    UPDATE order
3    INSERT outbox  ------> row #812 sent_at=NULL
4    COMMIT
5                                                       SELECT unsent ORDER BY id
6                                                       publish #812 ----------> stored
7                                                       CRASH before UPDATE
8                           row #812 still unsent
9                                                       (restart) publish #812 -> stored again (duplicate)
10                          UPDATE sent_at=now()
Producer txOrder aggregate rowoutbox row (new)Relaypoll or tail the logBrokerat-least-onceConsumer txinbox (consumer, id) uniquebusiness effectparking lot (DLQ)poison / exhaustedthen mark sentpublish, THEN mark sentcrash in between: same id published twicethe inbox unique key turns "twice" into "once"One tx on each side; the broker call is never inside a database transaction.

The picture shows both sides: the producer transaction with the outbox row, the relay that publishes and then marks, the broker, the consumer transaction with the inbox row, and the parking lot.

Relay styles:

StyleHowOrderLatencyCosts and risksProducts
Polling publisherSELECT ... WHERE sent_at IS NULL ORDER BY id LIMIT n on a timerPer table order if one relay; ties to id gaps under concurrent transactionsPoll intervalLoad on the database; "Tricky to publish events in order"; works with any SQL databaseAny SQL database; Laravel command or Go loop; Watermill's SQL publisher and Forwarder (documented as "the outbox pattern")
Transaction log tailingRead the database's WAL/binlog and publish rows inserted in the outbox tableLog orderMilliseconds"Relatively obscure although becoming increasing common"; "Requires database specific solutions"; "Tricky to avoid duplicate publishing"Debezium (PostgreSQL logical decoding, MySQL binlog), see Change Data Capture

(The "Tricky..." quotes are the drawbacks listed on the Polling Publisher and Transaction Log Tailing pattern pages.)

Per-aggregate order. Order matters per aggregate, not globally. Keep it by (1) one relay per outbox (or one per partition of the outbox) so rows are published in id order, (2) holding back later rows of a key whose earlier row failed, (3) using the aggregate id as the broker's partition key (Kafka), routing key or message group (SQS FIFO), and (4) putting the aggregate version in the message so consumers can check (Ordering). In PostgreSQL, ids of a sequence are assigned at insert time, not commit time, so a long transaction can commit a lower id after the relay passed it: poll with a safety window, or track by xmin/commit position, or use log tailing.

Real scenarios: order placed event after commit; stock-level changes for the search index; invoice issued; user email changed (Identity) so Sales updates its copy.

What provides it:

PlatformOutbox support
PostgreSQL / MySQLPlain table in the same transaction; log tailing via logical replication or binlog
MongoDBMulti-document transactions on a replica set, or change streams on the outbox collection
DynamoDBTransactional writes plus DynamoDB Streams
LaravelDB::transaction + a table + a command; afterCommit on dispatch is NOT an outbox (the job can be lost between commit and push)
Godatabase/sql BeginTx + INSERT; a relay goroutine or separate binary

Fix: Go outbox.Add and Relay.RunOnce; Laravel Outbox::record and outbox:relay. The full pattern page is Transactional Outbox.

Reliable consuming: the inbox, dedup keys and commutative handlers Must-know ​

In plain words: The consumer writes down "I processed message 41" in the same transaction as the effect. If message 41 comes again, the write fails on the unique key and the effect is skipped.

Common misunderstanding: "Check whether I processed it, then process it, then record it." That is three steps with two gaps; two concurrent copies both pass the check. The record and the effect must be one transaction, and the record must be a unique key.

Definition: An idempotent consumer "record[s] the IDs of processed messages in the database" (microservices.io: "Make a consumer idempotent by having it record the IDs of processed messages in the database"), either in a separate PROCESSED_MESSAGES table (the inbox) or in the business entity itself. Three techniques cover almost every handler:

TechniqueHowGood forLimit
Inbox table (processed ids)INSERT inbox (consumer, message_id) unique; skip on conflict; same tx as the effectAny handler, any effect in your own databaseOne row per message; needs retention
Natural idempotencyThe effect is a set, not an increment: status = confirmed, upsert by business keyState-setting handlersNot for "add 1"
Versioned stateApply only if message.version > stored.version; ignore olderRead models, replicated copiesNeeds a per-key version in the message
Idempotency key at a providerSend your own key with the call (card gateway)Effects outside your databaseProvider must support it
Commutative handlerOrder of arrival does not change the final state (tombstones)Compensations, reorderingNeeds design per handler
text
     Consumer tx (message 41)                             Second delivery of 41
1    BEGIN                                                BEGIN
2    INSERT inbox(consumer='billing', id=41)  ok          INSERT inbox(...,41)  -> unique violation
3    charge card, INSERT payment                          (skip: ack and stop)
4    INSERT outbox PaymentCharged                         ROLLBACK / COMMIT of nothing
5    COMMIT

Dedup key choice:

KeyStable across redelivery?Use
Broker offset / delivery tagNo (changes on redelivery or replay)Never as a dedup key
Message id assigned by the producer at outbox insertYesThe default
Business key (order_id + step)YesWhen the message may be re-created by a retried command
Aggregate id + versionYesFor event streams of one aggregate
Payload hashYes, but collides when two real messages are identicalLast resort

Retention. The inbox grows forever unless pruned. Keep rows at least as long as the broker's maximum redelivery and replay window (Kafka retention.ms, SQS message retention up to 14 days, a replay you plan to run), then delete in batches. Document the window: a replay older than the window will be processed twice.

What provides it:

PlatformHow
PostgreSQLINSERT ... ON CONFLICT DO NOTHING, check rows affected
MySQL / InnoDBINSERT IGNORE or catch error 1062
MongoDBUnique index plus insertOne, catch E11000
RedisSET key NX EX ttl is a cheap pre-filter; it is not atomic with a database effect, so it is not the correctness mechanism
LaravelDB::table(...)->insertOrIgnore(); ShouldBeUnique only stops duplicate queue entries, not duplicate processing

Fix: Go inbox.Once; Laravel Inbox::once. The full pattern page is Idempotent Consumers & the Inbox.

Ordering: per key, versions and tolerance Important ​

In plain words: Only messages about the same aggregate need to be in order, and even then you should be able to survive them arriving in the wrong order.

Common misunderstanding: "Use timestamps to order events." Two machines' clocks disagree (clock skew), and a retry keeps the old timestamp. Order by something the owner controls: the aggregate's version.

Definition: Per-key ordering means all messages of one aggregate go through one partition (Kafka), one queue consumer (RabbitMQ single active consumer or consistent-hash exchange), or one message group (SQS FIFO), see Ordering & Partitioning. Even so, retries and redelivery break strict order, so handlers add a check.

text
     Fulfilment read model "order status"               messages arrive in this order
1    v3 ParcelDispatched  arrives first                 apply: status=dispatched, version=3
2    v2 OrderPaid         arrives late                  2 < 3: ignore (stale)
3    v5 OrderCancelled    arrives (v4 missing)          5 > 3+1: GAP -> park for later, ask for v4
4    v4 OrderRefunded     arrives                       4 = 3+1: apply; then replay v5
Tolerance techniqueRuleUse when
Drop staleif msg.version <= stored.version: ignoreLatest state wins (read models)
Detect gapif msg.version > stored.version + 1: retry laterEvery event matters (ledgers)
Commutative effectThe final state is the same in any orderCompensations: release-before-reserve leaves a tombstone
Re-fetchOn gap, query the owner's API for the current stateSnapshots acceptable
Single writer per keyRoute by key so one consumer handles itThroughput per key is low

Wall-clock timestamps are fine for display and for deadlines evaluated on one machine (the saga's own clock). They are not fine for deciding which of two events is "newer".

Fix: projection.Apply (a version-checked read model that answers Applied, Stale or Gap) in Go; the fulfilment handler (release before reserve, cancel before create) and OrderSaga.Handle (late replies) in Go.

Retries, backoff and poison messages Must-know ​

In plain words: When a handler fails, try again after a growing, randomised pause, a limited number of times. If the message can never succeed, put it aside with the reason and tell a human; do not block the queue and do not throw it away.

Common misunderstanding: "More retries means more reliable." AWS: "Retries are 'selfish.' In other words, when a client retries, it spends more of the server's time to get a higher chance of success." When the failure is overload, retries make it worse; Google's SRE chapter on cascading failures says to use "randomized exponential backoff" and "Limit retries per request", and to consider "a server-wide retry budget".

Definition: The consumer-side policy has four parts: classify the error (transient, permanent, business "no"), a capped exponential backoff with full jitter, a maximum number of attempts, and a destination for what is left (DLQ or parking lot). The resilience patterns at the caller side (timeouts, circuit breaker) are in Error Handling & Fault Tolerance and Timeouts, Retries & Jitter; retry mechanics per broker are in Retry, Backoff & Delayed Delivery.

Error classExampleRetry?Action
Transient technicalTimeout, 503, deadlock (SQLSTATE 40P01), serialization failure (40001)Yes, with backoff and jitterRelease back to the queue
Dependency downCard gateway unavailable for minutesYes, but slow down for everyoneThrottle exceptions or open a breaker; retry window
Permanent technicalUndecodable payload, unknown message type, schema violationNoPark immediately with the reason
Business "no"Out of stock, card declinedNo, it is an answerReply with a rejection message; the saga handles it
Ordering gapVersion 5 arrived, 4 missingYes, laterRelease with a longer delay, then park
Bug in the handlerTypeError for every messageNo (retrying cannot help)Stop the consumer, alert, fix, redrive

Full jitter: wait a random time between 0 and min(cap, base × 2^attempt). It spreads clients that failed at the same moment; AWS notes that without jitter "retries that increase load can make matters significantly worse" when "all clients retry at the same time", and recommends jitter for "all timers, periodic jobs, and other delayed work".

text
     attempt   ceiling = min(2s, 100ms*2^n)    wait (full jitter, random in [0, ceiling))
1    0         100 ms                           e.g. 37 ms
2    1         200 ms                           e.g. 154 ms
3    2         400 ms                           e.g. 12 ms
4    3         800 ms                           e.g. 611 ms   -> attempts exhausted: park with reason

Poison messages. A poison message is one that always fails. If the consumer retries it forever, it blocks everything behind it (with ordered partitions and queues); if it drops it, a business event vanishes. Park it: store the message, the reason, the attempt count, a timestamp and the consumer name in a DLQ, a RabbitMQ dead-letter exchange, a Kafka dead-letter topic, an SQS dead-letter queue with maxReceiveCount, or a Laravel failed_jobs row. Then alert on depth, inspect, fix, and redrive (re-publish after the fix). See Dead-Letter Queue.

ProductRetry primitivePoison destinationRedrive
RabbitMQNack with requeue, or TTL retry queues via dead-letter exchange; quorum queues delivery-limitDead-letter exchange (x-dead-letter-exchange)Shovel or manual republish
Apache KafkaRetry topics (orders.retry.5s) or in-process; no per-message nackDead-letter topicReplay from the dead-letter topic
Redis StreamsPending entries list, XAUTOCLAIM after idle time; count deliveries via XPENDINGMove to a dead stream after N deliveriesXADD back
Amazon SQSVisibility timeout and maxReceiveCountRedrive policy to a dead-letter queue"Start DLQ redrive"
Laravel queue#[Tries], #[Backoff], #[MaxExceptions], release(), retryUntil()failed_jobs table (make:queue-failed-table), failed() methodqueue:retry
Go (Watermill)Router middleware; docs list "Requeuing After Error"A poison queue publisherRe-publish

Fix: Go retry.Process and dlq.Queue; Laravel ConsumeMessage with attributes and middleware, dontRetry(PermanentFailure::class) and failed().

Sagas: the cross-context process Must-know ​

In plain words: A saga is a checklist that spans contexts. Each step is a local transaction in one context. If a later step fails, the saga runs "undo" steps for the earlier ones, as ordinary business operations.

Common misunderstanding: "A saga is a distributed rollback." A rollback erases; a compensation is a new, visible business action. The customer did see "stock reserved" and may see "payment refunded". Some steps cannot be undone at all (an email sent, a parcel dispatched), and the compensation is then an apology or a return process.

Definition: "A saga is a reliably coordinated sequence of local transactions. The coordination mechanism, which often uses asynchronous messaging, ensures that the saga finishes: either all steps complete successfully or, if a local transaction fails because it violates a business rule, the changes made by the completed steps are undone by compensating transactions." (microservices.io). Two coordination styles exist: "Choreography - each local transaction publishes domain events that trigger local transactions in other services" and "Orchestration - an orchestrator (object) tells the participants what local transactions to execute."

AspectChoreographyOrchestration
Who knows the whole flowNobody; it emerges from event subscriptionsThe orchestrator (a saga/process manager)
CouplingServices subscribe to each other's events (cyclic dependencies appear)Participants know commands and replies; the orchestrator knows participants
VisibilityHard: the flow is spread over many servicesEasy: one place shows state per order
Timeouts and deadlinesEach service must implement its ownOne timer per saga
Compensation orderingImplicitExplicit
TestingNeeds the whole systemThe saga is a pure state machine
FitsTwo or three steps, stable flow, same teamFour or more steps, branching, compensations, several teams

Our flow has four steps, three failure branches and two teams, so we orchestrate: the saga lives in Sales and drives Fulfilment and Billing with commands.

Order placedSales: pendingReserve stockFulfilmentCharge paymentBilling, idempotency keyCreate shipmentFulfilmentConfirmedSales: confirmedRelease stockon decline / timeoutRefund paymenton ship fail / timeoutCancel shipmenttimeout / late createCompensatingwaits for every ack; late replies undoneCancelledterminal, Order cancelledout of stock:nothing to undotimer: a deadline onevery step

The picture shows the happy path along the top, a failure arrow down from each step, the compensating commands, the state Compensating (which waits for every acknowledgement), and the terminal Cancelled; a timer on every step feeds the same compensation path.

Compensations are domain operations. Name them in the ubiquitous language (Ubiquitous Language): ReleaseStock, RefundPayment, CancelShipment, not "rollback step 2". Each compensation must itself be idempotent and commutative with its forward step, because the compensation can arrive before the thing it undoes (the forward message was delayed):

Forward stepCompensationIf compensation arrives firstIf forward step arrives late
ReserveStockReleaseStockLeave a tombstone releasedRefuse: StockRejected("already released")
ChargePaymentRefundPaymentLeave a tombstone cancelledDecline: PaymentDeclined("order already cancelled")
CreateShipmentCancelShipment (before pickup) or a return processTombstoneRefuse
SendConfirmationEmailNone possiblen/aSend the apology email as a new forward step

Timeouts and deadlines. A saga step that gets no reply must not wait forever. The saga stores a deadline on every step; a timer asks "which sagas are past their deadline?" and moves them to Compensating with the commands that are safe whatever the neighbour did (release and refund are idempotent and tombstone-safe). A reply that arrives after the cancel is a late reply and must be undone again, not applied (the saga answers a late StockReserved with another ReleaseStock). The deadline is evaluated on the saga's own clock, so clock skew between machines does not matter.

text
     Saga (Sales)                 Billing (down)               Fulfilment
1    ReserveStock ---------------------------------------->   held
2    <-- StockReserved ----------------------------------
3    state=Charging, deadline=t+30s
4    ChargePayment ----> queued (Billing is down)
5    ... 30 s pass ...
6    TIMER: deadline passed -> state=Compensating, outstanding {Refund, Release}
7    RefundPayment ---> queued behind the charge
8    ReleaseStock -------------------------------------------> released
9    <-- StockReleased ----------------------------------
10   Billing returns: ChargePayment executes (money taken), then RefundPayment (money returned)
11   <-- PaymentCharged (late): refund already outstanding, ignore
12   <-- PaymentRefunded: outstanding empty -> state=Cancelled, emit OrderCancelled

What provides orchestration:

PlatformSupport
Hand-written saga aggregateFull control; what this chapter builds in Go and Laravel
Temporal, Cadence, Zeebe/Camunda, AWS Step FunctionsDurable workflow engines: timers, retries and history are built in (Durable Workflows & Jobs)
LaravelBus::chain is a linear job chain with a catch; Bus::batch runs jobs in parallel with then/catch/finally callbacks. Neither stores a compensation plan or a deadline, so a business saga needs its own state table
MassTransit / NServiceBus (.NET), Axon (JVM)Saga state machines in the framework

Fix: Go OrderSaga.Handle and Expire; Laravel OrderSaga and OrderSagaService. The full pattern page is Saga Pattern.

The saga as an aggregate Important ​

In plain words: The saga's own state (which step, which deadline, which compensations are still open) is data with rules, so model it like any aggregate: one row, a version, behaviour methods, one transaction per change.

Common misunderstanding: "The saga is a workflow script that keeps its state in memory or in a cache." If the process dies, the order is lost half-done. The state must be as durable as the orders.

Definition: The saga is an aggregate in Sales identified by the order id (a process manager in older DDD writing). Its invariants: state transitions are legal (no move out of a terminal state); Cancelled is reached only when every outstanding compensation is acknowledged; every state with a pending reply has a deadline. It follows the same unit of work: handling one incoming message is one transaction containing the inbox row, the new saga state and the outgoing commands in the outbox.

FieldMeaningWhy it exists
order_idIdentity (same as the order's)One saga per order; duplicates of OrderPlaced are ignored
statereserving_stock, charging, shipping, completed, compensating, cancelledThe explicit state machine
deadlineWhen the current step times outTimers query by it (indexed)
outstandingCompensations sent and not yet acknowledged"Cancelled" only when empty
reasonWhy compensation startedShown to support and the customer
versionIncremented on every changeUsed as seq in outgoing messages; optimistic concurrency

Two things the saga must not do: block waiting for a reply (it only reacts to messages and timers), and call neighbours directly inside its transaction (it writes commands to the outbox).

Fix: Go saga.Service.Handle and Tick; Laravel OrderSagaService::handle and tick.

Eventual consistency as a product decision Must-know ​

In plain words: While the saga runs, the order is neither confirmed nor failed. The screen must say so, and the business must say what happens when it does not finish.

Common misunderstanding: "Eventual consistency is an engineering detail the UI hides." The user sees it: an order that says "confirmed" and then cancels is a broken promise; an order that says "pending" is honest. Fowler and Lewis: "Often businesses handle a degree of inconsistency in order to respond quickly to demand, while having some kind of reversal process to deal with mistakes. The trade-off is worth it as long as the cost of fixing mistakes is less than the cost of lost business under greater consistency."

Definition: A status model is the set of customer-visible states of an aggregate that the saga moves through, together with the words and actions the product offers in each state.

Order status (Sales)Saga stateWhat the customer seesAllowed actionsNotification
pendingreserving, charging, shipping"We received your order and are checking stock and payment"View, cancel requestEmail "order received"
confirmedcompleted"Your order is confirmed"View, return laterEmail "confirmed"
cancelled (reason: out of stock)cancelled"Sorry, an item is no longer available"ReorderEmail with reason
cancelled (reason: payment declined)cancelled"Your payment was declined"Retry with another cardEmail with link
cancelled (reason: timeout)cancelled"We could not complete your order in time; you were not charged"ReorderEmail; refund notice if money moved

The business owns three numbers: the time-out of each step (how long "pending" may last), the maximum acceptable inconsistency window (seconds to minutes), and what a cancellation costs (the apology voucher). These are decided with the domain experts, not guessed (Event Storming is where the failure branches first appear as sticky notes).

Real scenarios: airline seat held for 15 minutes; hotel booking "pending confirmation"; marketplace order "payment processing"; bank transfer "in progress".

Fix: the status field is part of the aggregate; the saga outcome changes it through a message handled in its own transaction (sales.OnOutcome in Go, OutcomeHandler in Laravel); the API returns 202 Accepted with the pending status (API edge).

Degraded modes: staying useful when a neighbour is down Important ​

In plain words: Decide in advance what each context does when a dependency is gone: keep accepting work, serve slightly old data, switch a feature off, or refuse politely. Never invent an answer.

Common misunderstanding: "Add a fallback and it keeps working." AWS: "Distributed fallback strategies are harder to test," and the failure modes (overload) "are hard to replicate in a test". A fallback that has never run in production is a second, untested system that kicks in during the worst hour. A fallback that returns made-up data (price 0, stock 999) is a bug with a polite face.

Definition: A degraded mode is a designed, tested, visible reduction of function:

Dependency downDegraded modeHonest?Cost / risk
Billing (charge)Sales accepts the order as pending; the saga charges when Billing is back; the order times out after N minutesYes: status says pendingOrders for customers with bad cards fail later
Catalog (price)Use the price snapshot already stored in Sales' own read model, flagged as of 09:02Yes if flaggedPrice may be stale; business sets a maximum age
Catalog (images, reviews)Feature flag hides the sectionYesNone for the core flow
Identity (login)Existing sessions and tokens keep working; new logins failYesCannot onboard
Fulfilment (stock)Backorder mode: accept, promise later dateNeeds a business ruleOversell risk accepted explicitly
Broker downThe outbox keeps growing; the relay catches up on returnYes (no loss)Outbox backlog alarm, disk
Payment provider slowBreaker open: fail fast, show "try again", keep cartYesLost conversions

Rules: (1) degrade only what the business agreed to; (2) say it in the response (Stale, AsOf, status pending); (3) exercise it regularly (game days, Chaos Engineering); (4) prefer waiting with a saga over guessing for anything involving money or stock; (5) AWS names three alternatives to a hidden fallback: "Let the caller handle errors" (retry, surface the failure), "Push data proactively" (keep the data locally so no fallback is needed, which is exactly a read model fed by events), and "Convert fallback into failover" (run the fallback path continuously so it is exercised). Its warning: "One of the worst things about fallback is that it isn't exercised regularly and is likely to fail or increase the scope of impact when it triggers during an outage." See Bulkheads & Graceful Degradation and Cascading Failures.

Read models serving stale data are the safest degraded mode, because a read model is meant to be eventually consistent (Data Patterns): Sales keeps its own copy of product prices fed by Catalog events, so a Catalog outage only freezes the copy.

Fix: Go edge.WithStaleFallback (returns the last value flagged stale, never invents one).

The context edge: timeouts, budgets and breakers Important ​

In plain words: Every call that leaves your context gets a time limit that fits inside the time the caller gave you, and a place where failures are counted and reacted to. These live in the application layer and the adapter, not in the domain model.

Common misunderstanding: "Put a retry annotation on the domain method." The domain model must not know the network exists; timeouts and breakers belong to the adapter or the application service (Domain, Application & Infrastructure Services).

Definition: At the edge you apply: a per-call timeout; deadline propagation ("a deadline is set high in the stack... The tree of RPCs emanating from an initial request will all have the same absolute deadline", Google SRE); a retry budget (SRE: "only allow 60 retries per minute in a process"); a circuit breaker ("the circuit breaker trips, and all further calls to the circuit breaker return with an error, without the protected call being made at all", Fowler); and a bulkhead (a separate pool per dependency). Code-level treatment is in Error Handling & Fault Tolerance; the architecture choice of sync versus async is in Service Communication; service meshes can enforce some of this (API Gateway, BFF & Service Mesh).

MechanismWhere it livesProtectsPointer
Per-call timeout and deadlineHTTP/gRPC client adapter, context in Go, Http::timeout() in LaravelThreads and connectionsTimeouts, Retries & Jitter
Circuit breakerAdapter around a dependencyThe caller from a failing calleeCircuit Breaker
BulkheadSeparate worker pools or queues per dependencyOne dependency from starving othersBulkheads
Rate limit / load sheddingIngress of the contextThe context from overloadLoad Shedding
Saga deadlineSaga aggregateThe business processSagas

Fix: Go edge.CallWithin computes min(perCall, remaining − reserve) and refuses when the budget is spent.

Idempotent commands at the API edge Must-know ​

In plain words: The client sends a unique Idempotency-Key with POST /orders. If the response is lost and the client retries, the server recognises the key and returns the first answer instead of creating a second order.

Common misunderstanding: "POST is not idempotent, so clients must never retry." They will retry; mobile networks force it. The server makes POST safe to retry with a key.

Definition: The key is stored with the result in a table with a unique constraint; the first request wins; later requests with the same key return the stored response, or 409 if the first is still running. The full pattern (scope, expiry, request fingerprint, storage) is in API Idempotency; the contract belongs in the API design (API Realization).

text
     Client                         Sales API                          DB
1    POST /orders  Key: k-91 --->   INSERT idempotency_keys(k-91)  --> ok (first)
2                                   place order + outbox, store 202 {pending}
3    <-- (response lost) ---------
4    POST /orders  Key: k-91 --->   INSERT idempotency_keys(k-91)  --> conflict
5    <-- 202 {pending} (stored) --- return saved response, no second order
LayerMechanismScope
Client to SalesIdempotency-Key headerOne user action
Sales to brokerOutbox message_idOne event
Broker to Fulfilment/BillingInbox (consumer, message_id)One delivery
Billing to card providerProvider idempotency key (charge-<order>)One charge

The keys at each layer are different on purpose; the chain only works if every hop dedups.

Fix: Laravel PlaceOrderController with insertOrIgnore; in Go the same shape is inbox.Once applied to the HTTP request id.

Testing failure Important ​

In plain words: Do not wait for production to duplicate a message. Make the broker duplicate, delay, drop and reorder in your tests, crash the relay at the worst moment, and check the business outcome.

Common misunderstanding: "We have unit tests for each handler." Each handler can be right and the system wrong; the bugs live in the interactions (duplicate plus reorder plus crash).

Definition: Four test levels: (1) pure state machines (the saga), (2) a failure-injecting integration harness (the in-memory broker with Duplicate, Reverse, DropFirst, relay crash hook, a neighbour switched off), (3) consumer contract tests on message schemas (Context Maps & Integration Patterns), (4) chaos in a pre-production environment (Chaos Engineering); broker-level testing tips are in Testing Messaging Systems.

TestInjectsAssertsIn this chapter
Duplicates and reorderingEvery message twice, newest firstOne charge, stock reserved once, order confirmedTestHappyPathSurvivesDuplicatesAndReordering
CompensationCard declinedStock released, order cancelled, no money takenTestPaymentDeclinedCompensatesStock
Late repliesBilling down, timeout, Billing returnsOrder cancelled, stock back, no second refundTestBillingDownTimeoutThenLateReplies
Relay crashCrash after publish, before markingOutbox drained, one chargeTestRelayCrashAfterPublishIsHarmless
Lost publishesFirst 3 publishes failOrder still confirmedTestLostPublishesAreRetriedByTheRelay
Stuck shipmentCreateShipment held past the deadlineOrder cancelled, the late create refused by the tombstone, no parcelTestShippingStallsThenLateCreateIsRefused
PoisonBogus type, bad JSONParked with 1 attempt, queue not blockedTestPoisonMessageIsParkedNotSwallowed
AtomicityInvalid orderNo order row and no outbox rowTestPlaceOrderIsAtomicWithItsOutboxRow
ReplayRe-deliver the whole historySame final stateRe-run Pump with Duplicate; with a real inbox, a replay older than retention is the exception
ContractSchema of OrderPlaced.v1Consumers still decode itContext Maps

Fix: Go and Laravel.

Observability across a saga Important ​

In plain words: Put two ids on every message: one that says "this belongs to order 7's saga" (correlation) and one that says "this was caused by that message" (causation). Then measure lag, outbox backlog and parked messages.

Common misunderstanding: "Distributed tracing covers it." Traces follow a request; a saga lives for minutes or days across many requests and timers. Business ids in logs and a saga table you can query are what support teams use.

Definition: The envelope carries id, correlation, causation, key, seq, type, at. The saga table is the dashboard of in-flight business. Metrics and alerts:

SignalMeaningAlert when
Outbox backlog (unsent rows) and oldest unsent ageThe relay is behind or stuckAge above the accepted inconsistency window
Consumer lag (queue depth, Kafka consumer lag)The consumer cannot keep upGrowing for N minutes
DLQ / parked depthPoison messages existAny, then page
Saga age by state (charging older than 2× step timeout)Timers or neighbours brokenCount above zero
Compensations per hourBusiness failure rateSpike
Inbox duplicate rateRedelivery frequencySudden jump (broker or relay trouble)
Retry rate and backoff timeDependency healthSustained

Log lines carry order_id, correlation, message_id, attempt. Details of the stack in Observability and Messaging Observability; the Go demo prints the causal chain.

Anti-patterns Must-know ​

Anti-patternWhy it failsInstead
Two-phase commit across servicesLocks across the network; a dead coordinator leaves in-doubt transactions; many brokers and providers do not support itLocal transactions + outbox + saga
Dual write (commit, then publish)A crash between the two loses the event; the opposite order publishes rolled-back factsOutbox
Synchronous chains (A calls B calls C calls D)Availability multiplies down; latency adds; one slow service cascadesAsync messages, or one call with a deadline and a degraded mode
Retrying non-idempotent operationsDouble charge after a lost responseIdempotency key, inbox
Silent fallbacksA made-up value hides the failure and corrupts dataExplicit degraded mode with a flag, or fail loudly
Swallowing poison messages (catch, log, ack)Business events vanishPark with reason, alert, redrive
Infinite immediate retriesRetry storm; blocks the queueCapped backoff with jitter, attempt limit
Ordering by timestampClock skewAggregate version, sequence
Saga state in memory or Redis onlyLost on restartDurable aggregate row
Compensation without idempotency or tombstonesDouble refund; late forward step undoes the cancelIdempotent, commutative compensations
"Exactly-once" as the only defenceIt stops at the boundary of one systemInbox at every consumer
Sharing the database to avoid messagingOne schema, no failure isolation, hidden couplingDatabase per service
Event as a remote procedure call (DoReserveStock published as an event, then waiting for the reply)Coupling and hidden synchronyCommands to a named recipient, events as facts

Mechanics ​

The tables ​

The same three tables exist in every context that sends or receives messages (PostgreSQL syntax; the Laravel migration has the same shape).

sql
-- Producer side: written in the SAME transaction as the aggregate.
CREATE TABLE outbox_messages (
  id             bigserial PRIMARY KEY,            -- relay order
  message_id     uuid        NOT NULL UNIQUE,      -- consumers' dedup key
  type           text        NOT NULL,             -- sales.order.placed.v1
  key            text        NOT NULL,             -- aggregate id: the ordering unit
  seq            bigint      NOT NULL,             -- aggregate version at emission
  correlation_id text        NOT NULL,
  causation_id   text,
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  sent_at        timestamptz
);
CREATE INDEX outbox_unsent ON outbox_messages (id) WHERE sent_at IS NULL;   -- partial index: stays tiny

-- Consumer side: the unique key IS the idempotency.
CREATE TABLE inbox_messages (
  consumer     text        NOT NULL,
  message_id   uuid        NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (consumer, message_id)
);

-- The saga is an aggregate: one row per order, a version, a deadline.
CREATE TABLE order_sagas (
  order_id    text PRIMARY KEY,
  state       text        NOT NULL,
  version     bigint      NOT NULL,
  deadline_at timestamptz,
  outstanding jsonb       NOT NULL DEFAULT '{}',
  reason      text
);
CREATE INDEX saga_due ON order_sagas (deadline_at) WHERE state IN ('reserving_stock','charging','shipping');

The three queries that run all day:

sql
-- 1. The consumer (inside the business transaction): 1 row = first time, 0 rows = duplicate.
INSERT INTO inbox_messages (consumer, message_id) VALUES ($1, $2) ON CONFLICT DO NOTHING;

-- 2. The relay (one relay per outbox keeps per-key order): oldest unsent first.
SELECT id, message_id, type, key, seq, payload FROM outbox_messages
WHERE sent_at IS NULL ORDER BY id LIMIT 100;

-- 3. The saga timer: which sagas are past their deadline? (lock so two timers do not both act)
SELECT order_id FROM order_sagas
WHERE state IN ('reserving_stock','charging','shipping') AND deadline_at <= now()
FOR UPDATE SKIP LOCKED;

Maintenance (run in batches, off peak): DELETE FROM outbox_messages WHERE sent_at < now() - interval '7 days' and DELETE FROM inbox_messages WHERE processed_at < now() - interval '14 days', with the retention longer than the broker's replay window. At high volume partition both tables by day and drop partitions (Partitioning & Sharding).

Knobs that decide delivery ​

ProductSettingEffect on this chapter
RabbitMQPublisher confirmsThe relay marks a row sent only after the broker confirms; without confirms a message can be lost after "publish" returns
RabbitMQManual consumer ack, prefetch_countAck after the inbox transaction commits; auto-ack loses messages on crash
RabbitMQDurable queues, persistent messages, quorum queuesSurvive broker restart
Apache Kafkaacks=all, enable.idempotence=true, min.insync.replicasNo loss on leader change; producer retries do not duplicate within a session
Apache Kafkaenable.auto.commit=false, commit after the handler's transactionAt-least-once; a crash re-delivers
Apache KafkaPartition key = aggregate idPer-aggregate order
Redis StreamsXACK after the transaction; XAUTOCLAIM min-idle-timeCrashed consumers' entries are re-delivered
Amazon SQSVisibility timeout greater than the handler's worst caseOtherwise a second copy is delivered while the first is running
Laravel queueretry_after in config/queue.php larger than the job timeoutOtherwise a second worker picks up a running job
Laravel queueafter_commit, afterCommit()Do not dispatch a job for a transaction that has not committed (not a substitute for the outbox)
Laravel queue#[Tries], #[MaxExceptions], #[Backoff], retryUntil()Bounded, spaced retries
PostgreSQLsynchronous_commit, replica lagOutbox rows read from a lagging replica are stale: read the relay's batch from the primary

Error codes and what to do ​

CodeMeaningHandler action
PostgreSQL 23505 unique_violationInbox or idempotency key already existsDuplicate: skip, acknowledge
MySQL error 1062Duplicate entrySame
MongoDB E11000Duplicate keySame
PostgreSQL 40001 serialization_failureConcurrent transaction conflictRetry the whole transaction
PostgreSQL 40P01 deadlock_detected / MySQL 1213Deadlock victimRetry with jitter (Deadlocks)
Optimistic version mismatch (0 rows updated)Another writer changed the aggregateReload and retry, or park if stale
HTTP 409 ConflictRequest with the same idempotency key still runningClient waits and retries
HTTP 422Validation failedPermanent; do not retry
HTTP 429 / 503 / 504Overload, down, gateway timeoutRetry with backoff, honour Retry-After
AMQP 406 PRECONDITION_FAILEDChannel closed (for example ack of an unknown delivery tag after a redelivery)Reopen, continue; the inbox makes redelivery safe
Kafka NotLeaderForPartition, RebalanceInProgressLeader moved or group rebalancingClient retries; expect duplicates

Go ​

One Go module (academy/designing-for-failure-reliable-messaging), standard library only, go vet and go test -race clean. Each of Sales, Fulfilment and Billing has its own in-memory database (store.DB) with real transaction semantics (all writes of one Tx commit or none), its own outbox, relay and inbox. The in-memory broker injects duplicates, reordering and lost publishes.

The envelope and the published language ​

Every message carries a stable ID (the dedup key), a Key and Seq (ordering), Correlation and Causation (tracing).

go
// Package msg is the envelope every context sends: identity for dedup,
// a key and sequence for ordering, correlation and causation for tracing.
package msg

import (
	"encoding/json"
	"time"
)

type Message struct {
	ID          string          `json:"id"`          // unique, stable across redelivery: the dedup key
	Type        string          `json:"type"`        // e.g. sales.order.placed.v1
	Key         string          `json:"key"`         // aggregate id: the ordering unit
	Seq         int64           `json:"seq"`         // aggregate version at emission: per-key order
	Correlation string          `json:"correlation"` // the whole business flow (the saga)
	Causation   string          `json:"causation"`   // the message that caused this one
	At          time.Time       `json:"at"`
	Payload     json.RawMessage `json:"payload"`
}

func New[T any](typ, key string, seq int64, p T) (Message, error) {
	raw, err := json.Marshal(p)
	if err != nil {
		return Message{}, err
	}
	return Message{Type: typ, Key: key, Seq: seq, Payload: raw}, nil
}

func Decode[T any](m Message) (T, error) {
	var v T
	err := json.Unmarshal(m.Payload, &v)
	return v, err
}

The published language between the three contexts (message types and payloads, versioned by suffix):

go
// Package contracts holds the published language between Sales, Fulfilment
// and Billing: the message types and their payloads.
package contracts

const (
	OrderPlaced       = "sales.order.placed.v1"
	OrderConfirmed    = "sales.order.confirmed.v1"
	OrderCancelled    = "sales.order.cancelled.v1"
	StockReserved     = "fulfilment.stock.reserved.v1"
	StockRejected     = "fulfilment.stock.rejected.v1"
	StockReleased     = "fulfilment.stock.released.v1"
	ShipmentCreated   = "fulfilment.shipment.created.v1"
	ShipmentFailed    = "fulfilment.shipment.failed.v1"
	ShipmentCancelled = "fulfilment.shipment.cancelled.v1"
	PaymentCharged    = "billing.payment.charged.v1"
	PaymentDeclined   = "billing.payment.declined.v1"
	PaymentRefunded   = "billing.payment.refunded.v1"

	CmdReserveStock   = "cmd.fulfilment.ReserveStock.v1"
	CmdReleaseStock   = "cmd.fulfilment.ReleaseStock.v1"
	CmdCreateShipment = "cmd.fulfilment.CreateShipment.v1"
	CmdCancelShipment = "cmd.fulfilment.CancelShipment.v1"
	CmdChargePayment  = "cmd.billing.ChargePayment.v1"
	CmdRefundPayment  = "cmd.billing.RefundPayment.v1"
)

type Line struct {
	SKU string `json:"sku"`
	Qty int    `json:"qty"`
}

type OrderPlacedV1 struct {
	OrderID    string `json:"order_id"`
	CustomerID string `json:"customer_id"`
	Total      int64  `json:"total_cents"`
	Lines      []Line `json:"lines"`
}

// OrderRef is the payload of every message that only needs the order id.
type OrderRef struct {
	OrderID string `json:"order_id"`
	Reason  string `json:"reason,omitempty"`
}

type ChargePayment struct {
	OrderID        string `json:"order_id"`
	Amount         int64  `json:"amount_cents"`
	IdempotencyKey string `json:"idempotency_key"`
}

type OrderLines struct {
	OrderID string `json:"order_id"`
	Lines   []Line `json:"lines"`
}

Reliable publishing: one aggregate, one outbox row ​

PlaceOrder is the unit of work. It never calls the broker.

go
package sales

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/store"
)

const table = "orders"

// PlaceOrder is one unit of work: ONE aggregate + ONE outbox row in ONE
// local transaction. No broker call happens here.
func PlaceOrder(db *store.DB, id, customerID string, total int64, lines []contracts.Line) error {
	return db.Tx(func(tx *store.Tx) error {
		o, err := Place(id, customerID, total, lines)
		if err != nil {
			return err
		}
		if err := store.Save(tx, table, o.ID, o); err != nil {
			return err
		}
		m, err := msg.New(contracts.OrderPlaced, o.ID, o.Version, contracts.OrderPlacedV1{
			OrderID: o.ID, CustomerID: o.CustomerID, Total: o.Total, Lines: o.Lines,
		})
		if err != nil {
			return err
		}
		_, err = outbox.Add(tx, m, "", "")
		return err
	})
}

// Load reads an order (used by tests and read models).
func Load(db *store.DB, id string) (o Order, ok bool) {
	db.View(func(tx *store.Tx) { o, ok, _ = store.Load[Order](tx, table, id) })
	return o, ok
}

// OnOutcome applies the saga's verdict to the Order aggregate. It is a
// separate transaction from the saga's own: one aggregate per transaction.
func OnOutcome(tx *store.Tx, m msg.Message) error {
	ref, err := msg.Decode[contracts.OrderRef](m)
	if err != nil {
		return fmt.Errorf("decode: %w", err)
	}
	o, ok, err := store.Load[Order](tx, table, ref.OrderID)
	if err != nil || !ok {
		return fmt.Errorf("order %s not found: %v", ref.OrderID, err)
	}
	switch m.Type {
	case contracts.OrderConfirmed:
		_, err = o.Confirm()
	case contracts.OrderCancelled:
		_, err = o.Cancel(ref.Reason)
	default:
		return nil
	}
	if err != nil {
		return err
	}
	return store.Save(tx, table, o.ID, o)
}

The outbox and the relay. The relay publishes first and marks afterwards; the CrashAfterPublish hook exists only so tests can kill it at the worst moment.

go
// Package outbox implements the transactional outbox and a polling relay.
// Add runs inside the business transaction; the relay publishes later.
// Delivery is at-least-once: a crash between publish and mark re-publishes.
package outbox

import (
	"context"
	"errors"
	"fmt"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

const Table = "outbox"

type Entry struct {
	Message msg.Message `json:"message"`
	Sent    bool        `json:"sent"`
}

// Add stores the message in the SAME transaction as the state change.
// It assigns the stable message id (database name + sequence).
func Add(tx *store.Tx, m msg.Message, correlation, causation string) (msg.Message, error) {
	n := tx.NextSeq()
	m.ID = fmt.Sprintf("%s-%06d", tx.DBName(), n)
	m.Correlation, m.Causation = correlation, causation
	if m.Correlation == "" {
		m.Correlation = m.ID
	}
	err := store.Save(tx, Table, fmt.Sprintf("%012d", n), Entry{Message: m})
	return m, err
}

type Publisher interface {
	Publish(ctx context.Context, m msg.Message) error
}

// ErrCrash simulates the relay process dying between publish and mark.
var ErrCrash = errors.New("outbox: relay crashed")

type Relay struct {
	DB  *store.DB
	Pub Publisher
	// CrashAfterPublish is a failure-injection hook used by tests.
	CrashAfterPublish func(m msg.Message) bool
}

// RunOnce publishes unsent entries in outbox order. If a publish fails, later
// messages of the SAME key are held back so per-aggregate order is kept;
// other keys continue.
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
	var pending []Entry
	var keys []string
	r.DB.View(func(tx *store.Tx) {
		for _, k := range tx.Keys(Table) {
			e, _, _ := store.Load[Entry](tx, Table, k)
			if !e.Sent {
				pending = append(pending, e)
				keys = append(keys, k)
			}
		}
	})
	blocked := map[string]bool{}
	published := 0
	for i, e := range pending {
		if blocked[e.Message.Key] {
			continue
		}
		if err := r.Pub.Publish(ctx, e.Message); err != nil {
			blocked[e.Message.Key] = true
			continue
		}
		if r.CrashAfterPublish != nil && r.CrashAfterPublish(e.Message) {
			return published, ErrCrash // published, NOT marked: duplicate on restart
		}
		err := r.DB.Tx(func(tx *store.Tx) error {
			e.Sent = true
			return store.Save(tx, Table, keys[i], e)
		})
		if err != nil {
			return published, err
		}
		published++
	}
	return published, nil
}

// Backlog is the number of unsent entries: the first outbox metric to alert on.
func Backlog(db *store.DB) int {
	n := 0
	db.View(func(tx *store.Tx) {
		for _, k := range tx.Keys(Table) {
			if e, _, _ := store.Load[Entry](tx, Table, k); !e.Sent {
				n++
			}
		}
	})
	return n
}

The aggregate whose status the saga's verdict changes. Confirm and Cancel are idempotent and a terminal order never flips:

go
// Package sales holds the Order aggregate: the consistency island that owns
// the order's status. Other contexts never write it; they send messages.
package sales

import (
	"errors"
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
)

type Status string

const (
	Pending   Status = "pending"
	Confirmed Status = "confirmed"
	Cancelled Status = "cancelled"
)

var ErrEmptyOrder = errors.New("sales: an order needs at least one line")

type Order struct {
	ID         string           `json:"id"`
	CustomerID string           `json:"customer_id"`
	Lines      []contracts.Line `json:"lines"`
	Total      int64            `json:"total_cents"`
	Status     Status           `json:"status"`
	Reason     string           `json:"reason,omitempty"`
	Version    int64            `json:"version"`
}

func Place(id, customerID string, total int64, lines []contracts.Line) (*Order, error) {
	if len(lines) == 0 {
		return nil, ErrEmptyOrder
	}
	return &Order{ID: id, CustomerID: customerID, Lines: lines, Total: total, Status: Pending, Version: 1}, nil
}

// Confirm and Cancel are idempotent: repeating the same outcome is a no-op,
// and a terminal order never flips to the opposite outcome.
func (o *Order) Confirm() (changed bool, err error) {
	switch o.Status {
	case Confirmed:
		return false, nil
	case Cancelled:
		return false, fmt.Errorf("sales: order %s is cancelled, cannot confirm", o.ID)
	}
	o.Status, o.Version = Confirmed, o.Version+1
	return true, nil
}

func (o *Order) Cancel(reason string) (changed bool, err error) {
	switch o.Status {
	case Cancelled:
		return false, nil
	case Confirmed:
		return false, fmt.Errorf("sales: order %s is confirmed, cannot cancel", o.ID)
	}
	o.Status, o.Reason, o.Version = Cancelled, reason, o.Version+1
	return true, nil
}

Reliable consuming: the inbox ​

go
// Package inbox makes a consumer idempotent: the dedup record and the
// business effect commit in ONE local transaction, so "processed" and
// "recorded as processed" cannot disagree.
package inbox

import (
	"errors"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

const Table = "inbox"

// Once runs fn at most once per (consumer, message id). It returns false when
// the message was already processed (a duplicate), without calling fn.
func Once(db *store.DB, consumer string, m msg.Message, fn func(tx *store.Tx) error) (bool, error) {
	processed := false
	err := db.Tx(func(tx *store.Tx) error {
		if err := tx.Insert(Table, consumer+"|"+m.ID, m.Type); err != nil {
			if errors.Is(err, store.ErrDuplicate) {
				return nil // already done: ack and move on
			}
			return err
		}
		if err := fn(tx); err != nil {
			return err // rolls back the inbox row too: the retry starts clean
		}
		processed = true
		return nil
	})
	return processed, err
}

Fulfilment's handlers are idempotent (same order id), commutative (release before reserve leaves a tombstone) and answer through their own outbox:

go
// Package fulfilment is the Fulfilment context's side of the conversation:
// idempotent, commutative handlers over its own database.
package fulfilment

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Reservation struct {
	OrderID string           `json:"order_id"`
	Status  string           `json:"status"` // held | released
	Lines   []contracts.Line `json:"lines"`
}

type Service struct {
	DB *store.DB
	// FailShipmentFor lets a test make the carrier reject an order.
	FailShipmentFor map[string]bool
}

func (s *Service) Stock(sku string) (n int) {
	s.DB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("stock", sku)
		fmt.Sscan(raw, &n)
	})
	return n
}

func (s *Service) Seed(sku string, qty int) {
	_ = s.DB.Tx(func(tx *store.Tx) error { tx.Put("stock", sku, fmt.Sprint(qty)); return nil })
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "fulfilment", m, func(tx *store.Tx) error {
		in, err := msg.Decode[contracts.OrderLines](m)
		if err != nil || in.OrderID == "" {
			return retry.Permanent{Err: fmt.Errorf("undecodable %s", m.Type)}
		}
		switch m.Type {
		case contracts.CmdReserveStock:
			return s.reserve(tx, in, m)
		case contracts.CmdReleaseStock:
			return s.release(tx, in.OrderID, m)
		case contracts.CmdCreateShipment:
			return s.ship(tx, in, m)
		case contracts.CmdCancelShipment:
			return s.cancelShipment(tx, in.OrderID, m)
		}
		return retry.Permanent{Err: fmt.Errorf("unknown command %s", m.Type)}
	})
	return err
}

func (s *Service) reply(tx *store.Tx, typ, orderID, reason string, cause msg.Message) error {
	out, err := msg.New(typ, orderID, 0, contracts.OrderRef{OrderID: orderID, Reason: reason})
	if err != nil {
		return err
	}
	_, err = outbox.Add(tx, out, cause.Correlation, cause.ID)
	return err
}

func (s *Service) reserve(tx *store.Tx, in contracts.OrderLines, cause msg.Message) error {
	if r, ok, _ := store.Load[Reservation](tx, "reservations", in.OrderID); ok {
		if r.Status == "released" { // Release arrived first (reordering): stay released
			return s.reply(tx, contracts.StockRejected, in.OrderID, "already released", cause)
		}
		return s.reply(tx, contracts.StockReserved, in.OrderID, "", cause) // same command again
	}
	for _, l := range in.Lines {
		var have int
		raw, _ := tx.Get("stock", l.SKU)
		fmt.Sscan(raw, &have)
		if have < l.Qty {
			return s.reply(tx, contracts.StockRejected, in.OrderID, "insufficient "+l.SKU, cause)
		}
	}
	for _, l := range in.Lines {
		var have int
		raw, _ := tx.Get("stock", l.SKU)
		fmt.Sscan(raw, &have)
		tx.Put("stock", l.SKU, fmt.Sprint(have-l.Qty))
	}
	if err := store.Save(tx, "reservations", in.OrderID, Reservation{OrderID: in.OrderID, Status: "held", Lines: in.Lines}); err != nil {
		return err
	}
	return s.reply(tx, contracts.StockReserved, in.OrderID, "", cause)
}

// release is a compensation. It is idempotent and commutative with reserve:
// releasing something never reserved leaves a tombstone, so a late reserve is refused.
func (s *Service) release(tx *store.Tx, orderID string, cause msg.Message) error {
	r, ok, _ := store.Load[Reservation](tx, "reservations", orderID)
	if ok && r.Status == "held" {
		for _, l := range r.Lines {
			var have int
			raw, _ := tx.Get("stock", l.SKU)
			fmt.Sscan(raw, &have)
			tx.Put("stock", l.SKU, fmt.Sprint(have+l.Qty))
		}
	}
	r.OrderID, r.Status = orderID, "released"
	if err := store.Save(tx, "reservations", orderID, r); err != nil {
		return err
	}
	return s.reply(tx, contracts.StockReleased, orderID, "", cause)
}

func (s *Service) ship(tx *store.Tx, in contracts.OrderLines, cause msg.Message) error {
	switch status, _ := tx.Get("shipments", in.OrderID); status {
	case "cancelled": // CancelShipment arrived first: refuse the late create
		return s.reply(tx, contracts.ShipmentFailed, in.OrderID, "already cancelled", cause)
	case "created": // same command again
		return s.reply(tx, contracts.ShipmentCreated, in.OrderID, "", cause)
	}
	if s.FailShipmentFor[in.OrderID] {
		return s.reply(tx, contracts.ShipmentFailed, in.OrderID, "carrier rejected address", cause)
	}
	tx.Put("shipments", in.OrderID, "created")
	return s.reply(tx, contracts.ShipmentCreated, in.OrderID, "", cause)
}

// cancelShipment is a compensation: idempotent, and commutative with ship
// (a cancel before the create leaves a tombstone that refuses the create).
func (s *Service) cancelShipment(tx *store.Tx, orderID string, cause msg.Message) error {
	tx.Put("shipments", orderID, "cancelled")
	return s.reply(tx, contracts.ShipmentCancelled, orderID, "", cause)
}

// Shipment returns "", "created" or "cancelled".
func (s *Service) Shipment(orderID string) (status string) {
	s.DB.View(func(tx *store.Tx) { status, _ = tx.Get("shipments", orderID) })
	return status
}

Billing adds the business-level idempotency key and the refund tombstone:

go
// Package billing charges and refunds idempotently, keyed by the caller's
// idempotency key. A refund for an unknown charge leaves a tombstone so a
// late charge for the same order is declined (commutative handlers).
package billing

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Payment struct {
	OrderID string `json:"order_id"`
	Amount  int64  `json:"amount_cents"`
	Status  string `json:"status"` // charged | refunded | cancelled (tombstone)
}

type Service struct {
	DB *store.DB
	// DeclineFor lets a test make the card issuer decline an order.
	DeclineFor map[string]bool
}

// Charges counts money actually taken: the number that must never exceed one.
func (s *Service) Charges(orderID string) (n int) {
	s.DB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("charge_count", orderID)
		fmt.Sscan(raw, &n)
	})
	return n
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "billing", m, func(tx *store.Tx) error {
		switch m.Type {
		case contracts.CmdChargePayment:
			c, err := msg.Decode[contracts.ChargePayment](m)
			if err != nil || c.IdempotencyKey == "" {
				return retry.Permanent{Err: fmt.Errorf("undecodable charge")}
			}
			return s.charge(tx, c, m)
		case contracts.CmdRefundPayment:
			r, err := msg.Decode[contracts.OrderRef](m)
			if err != nil || r.OrderID == "" {
				return retry.Permanent{Err: fmt.Errorf("undecodable refund")}
			}
			return s.refund(tx, r.OrderID, m)
		}
		return retry.Permanent{Err: fmt.Errorf("unknown command %s", m.Type)}
	})
	return err
}

func (s *Service) reply(tx *store.Tx, typ, orderID, reason string, cause msg.Message) error {
	out, err := msg.New(typ, orderID, 0, contracts.OrderRef{OrderID: orderID, Reason: reason})
	if err != nil {
		return err
	}
	_, err = outbox.Add(tx, out, cause.Correlation, cause.ID)
	return err
}

func (s *Service) charge(tx *store.Tx, c contracts.ChargePayment, cause msg.Message) error {
	// Natural idempotency: the second command with the same key is answered, not re-executed.
	if p, ok, _ := store.Load[Payment](tx, "payments", c.IdempotencyKey); ok {
		return s.reply(tx, contracts.PaymentCharged, c.OrderID, "replayed "+p.Status, cause)
	}
	if t, ok, _ := store.Load[Payment](tx, "payments", "order-"+c.OrderID); ok && t.Status == "cancelled" {
		return s.reply(tx, contracts.PaymentDeclined, c.OrderID, "order already cancelled", cause)
	}
	if s.DeclineFor[c.OrderID] {
		return s.reply(tx, contracts.PaymentDeclined, c.OrderID, "card declined", cause)
	}
	p := Payment{OrderID: c.OrderID, Amount: c.Amount, Status: "charged"}
	if err := store.Save(tx, "payments", c.IdempotencyKey, p); err != nil {
		return err
	}
	if err := store.Save(tx, "payments", "order-"+c.OrderID, p); err != nil {
		return err
	}
	var n int
	raw, _ := tx.Get("charge_count", c.OrderID)
	fmt.Sscan(raw, &n)
	tx.Put("charge_count", c.OrderID, fmt.Sprint(n+1))
	return s.reply(tx, contracts.PaymentCharged, c.OrderID, "", cause)
}

func (s *Service) refund(tx *store.Tx, orderID string, cause msg.Message) error {
	p, ok, _ := store.Load[Payment](tx, "payments", "order-"+orderID)
	if ok && p.Status == "charged" {
		p.Status = "refunded"
	} else if !ok {
		p = Payment{OrderID: orderID, Status: "cancelled"} // tombstone
	}
	if err := store.Save(tx, "payments", "order-"+orderID, p); err != nil {
		return err
	}
	return s.reply(tx, contracts.PaymentRefunded, orderID, "", cause)
}

Retries, backoff and the parking lot ​

go
// Package retry is the consumer-side retry loop: capped exponential backoff
// with full jitter, a hard limit, and a way to say "this will never work".
package retry

import (
	"errors"
	"time"

	"academy/designing-for-failure-reliable-messaging/msg"
)

// Permanent marks an error that no retry can fix (bad payload, unknown type).
type Permanent struct{ Err error }

func (e Permanent) Error() string { return "permanent: " + e.Err.Error() }
func (e Permanent) Unwrap() error { return e.Err }

type Parker interface {
	Park(m msg.Message, reason string, attempts int) error
}

type Policy struct {
	MaxAttempts int
	Base, Cap   time.Duration
	Rand        func() float64 // injectable so tests are deterministic
}

// Delay is "full jitter": a random wait in [0, min(cap, base*2^attempt)).
func (p Policy) Delay(attempt int) time.Duration {
	if attempt > 30 {
		attempt = 30
	}
	ceiling := min(p.Cap, p.Base<<attempt)
	return time.Duration(p.Rand() * float64(ceiling))
}

// Process handles m. Transient errors are retried after a backoff; permanent
// errors and exhausted attempts go to the parking lot. It never drops silently:
// the result is either "handled" or "parked with a reason".
func Process(p Policy, sleep func(time.Duration), m msg.Message, handle func(msg.Message) error, parker Parker) (parked bool, err error) {
	var last error
	for attempt := 0; attempt < p.MaxAttempts; attempt++ {
		last = handle(m)
		if last == nil {
			return false, nil
		}
		if errors.As(last, new(Permanent)) {
			return true, parker.Park(m, last.Error(), attempt+1)
		}
		sleep(p.Delay(attempt))
	}
	return true, parker.Park(m, "attempts exhausted: "+last.Error(), p.MaxAttempts)
}
go
// Package dlq is the parking lot for poison messages: kept with the reason
// and the attempt count so a human (or a repair job) can decide.
package dlq

import (
	"fmt"
	"sync"

	"academy/designing-for-failure-reliable-messaging/msg"
)

type Parked struct {
	Message  msg.Message
	Reason   string
	Attempts int
}

type Queue struct {
	mu    sync.Mutex
	items []Parked
}

func (q *Queue) Park(m msg.Message, reason string, attempts int) error {
	q.mu.Lock()
	defer q.mu.Unlock()
	q.items = append(q.items, Parked{Message: m, Reason: reason, Attempts: attempts})
	return nil
}

// Depth is the second metric to alert on: anything above zero needs a human.
func (q *Queue) Depth() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return len(q.items)
}

func (q *Queue) Items() []Parked {
	q.mu.Lock()
	defer q.mu.Unlock()
	return append([]Parked(nil), q.items...)
}

func (p Parked) String() string {
	return fmt.Sprintf("%s (%s) after %d attempts: %s", p.Message.ID, p.Message.Type, p.Attempts, p.Reason)
}

The saga as an aggregate, with timeouts and compensations ​

The state machine is pure: a message and a clock go in, a new state and outgoing messages come out. Late replies, duplicates and terminal states are all handled here.

go
// Package saga is the Order -> Reserve stock -> Charge -> Ship process as an
// aggregate. Handle is a pure state machine: message in, state change and
// outgoing messages out. Persistence, dedup and the outbox live in service.go.
package saga

import (
	"time"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
)

type State string

const (
	ReservingStock State = "reserving_stock"
	Charging       State = "charging"
	Shipping       State = "shipping"
	Completed      State = "completed" // terminal
	Compensating   State = "compensating"
	Cancelled      State = "cancelled" // terminal
)

type OrderSaga struct {
	OrderID     string           `json:"order_id"`
	State       State            `json:"state"`
	Lines       []contracts.Line `json:"lines"`
	Total       int64            `json:"total_cents"`
	Deadline    time.Time        `json:"deadline"`
	Outstanding map[string]bool  `json:"outstanding"` // compensations not yet acknowledged
	Reason      string           `json:"reason,omitempty"`
	Version     int64            `json:"version"`
}

// Out is a message the saga wants to send (a command or an outcome event).
type Out struct {
	Type    string
	Payload any
}

func (s *OrderSaga) terminal() bool { return s.State == Completed || s.State == Cancelled }

func Start(placed contracts.OrderPlacedV1, now time.Time, stepTimeout time.Duration) (*OrderSaga, []Out) {
	s := &OrderSaga{OrderID: placed.OrderID, State: ReservingStock, Lines: placed.Lines, Total: placed.Total,
		Deadline: now.Add(stepTimeout), Outstanding: map[string]bool{}, Version: 1}
	return s, []Out{{contracts.CmdReserveStock, contracts.OrderLines{OrderID: s.OrderID, Lines: s.Lines}}}
}

// Handle applies one reply. Replies that make no sense in the current state
// (late, duplicated, reordered) are ignored or answered with a compensation:
// the saga never panics and never moves backwards from a terminal state.
func (s *OrderSaga) Handle(m msg.Message, now time.Time, stepTimeout time.Duration) []Out {
	if s.terminal() && s.State == Completed {
		return nil
	}
	ref := contracts.OrderRef{OrderID: s.OrderID}
	var outs []Out
	switch m.Type {
	case contracts.StockReserved:
		switch s.State {
		case ReservingStock:
			s.advance(Charging, now, stepTimeout)
			outs = append(outs, Out{contracts.CmdChargePayment, contracts.ChargePayment{
				OrderID: s.OrderID, Amount: s.Total, IdempotencyKey: "charge-" + s.OrderID}})
		case Compensating, Cancelled: // late reply after a timeout: undo it again
			outs = append(outs, Out{contracts.CmdReleaseStock, ref})
		}
	case contracts.StockRejected:
		if s.State == ReservingStock {
			outs = s.cancel("out of stock", nil)
		}
	case contracts.PaymentCharged:
		switch s.State {
		case Charging:
			s.advance(Shipping, now, stepTimeout)
			outs = append(outs, Out{contracts.CmdCreateShipment, contracts.OrderLines{OrderID: s.OrderID, Lines: s.Lines}})
		case Compensating, Cancelled:
			if !s.Outstanding[contracts.CmdRefundPayment] { // not already being undone
				outs = append(outs, Out{contracts.CmdRefundPayment, ref})
				s.Outstanding[contracts.CmdRefundPayment] = true
			}
		}
	case contracts.PaymentDeclined:
		if s.State == Charging {
			outs = s.compensate("payment declined", contracts.CmdReleaseStock)
		}
	case contracts.ShipmentCreated:
		switch s.State {
		case Shipping:
			s.State, s.Version = Completed, s.Version+1
			outs = append(outs, Out{contracts.OrderConfirmed, ref})
		case Compensating, Cancelled: // late reply: a parcel exists for a cancelled order
			if !s.Outstanding[contracts.CmdCancelShipment] {
				s.Outstanding[contracts.CmdCancelShipment] = true
				outs = append(outs, Out{contracts.CmdCancelShipment, ref})
			}
		}
	case contracts.ShipmentFailed:
		if s.State == Shipping {
			outs = s.compensate("shipment failed", contracts.CmdRefundPayment, contracts.CmdReleaseStock)
		}
	case contracts.StockReleased:
		outs = s.acknowledge(contracts.CmdReleaseStock)
	case contracts.PaymentRefunded:
		outs = s.acknowledge(contracts.CmdRefundPayment)
	case contracts.ShipmentCancelled:
		outs = s.acknowledge(contracts.CmdCancelShipment)
	}
	return outs
}

// Expire is called by a timer. A silent neighbour is not an answer: we move to
// compensation with the commands that are safe whatever the neighbour did.
func (s *OrderSaga) Expire(now time.Time) []Out {
	if s.terminal() || s.State == Compensating || now.Before(s.Deadline) {
		return nil
	}
	switch s.State {
	case ReservingStock:
		return s.compensate("timeout reserving stock", contracts.CmdReleaseStock)
	case Charging:
		return s.compensate("timeout charging payment", contracts.CmdRefundPayment, contracts.CmdReleaseStock)
	default: // Shipping: the shipment may or may not exist, so cancel it too (tombstone-safe)
		return s.compensate("timeout shipping", contracts.CmdCancelShipment, contracts.CmdRefundPayment, contracts.CmdReleaseStock)
	}
}

func (s *OrderSaga) advance(next State, now time.Time, timeout time.Duration) {
	s.State, s.Deadline, s.Version = next, now.Add(timeout), s.Version+1
}

func (s *OrderSaga) compensate(reason string, cmds ...string) []Out {
	s.State, s.Reason, s.Version = Compensating, reason, s.Version+1
	var outs []Out
	for _, c := range cmds {
		s.Outstanding[c] = true
		outs = append(outs, Out{c, contracts.OrderRef{OrderID: s.OrderID}})
	}
	return outs
}

func (s *OrderSaga) acknowledge(cmd string) []Out {
	if s.State != Compensating {
		return nil
	}
	delete(s.Outstanding, cmd)
	if len(s.Outstanding) == 0 {
		return s.cancel(s.Reason, nil)
	}
	return nil
}

func (s *OrderSaga) cancel(reason string, _ []Out) []Out {
	s.State, s.Reason, s.Version = Cancelled, reason, s.Version+1
	return []Out{{contracts.OrderCancelled, contracts.OrderRef{OrderID: s.OrderID, Reason: reason}}}
}

The service wraps it with persistence: inbox row, saga row and outgoing commands in one transaction; Tick finds expired sagas, one per transaction.

go
package saga

import (
	"fmt"
	"time"

	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/store"
)

const table = "sagas"

// Service persists the saga aggregate. Every handled message is ONE
// transaction: inbox row + saga state + outgoing commands in the outbox.
type Service struct {
	DB          *store.DB
	Now         func() time.Time
	StepTimeout time.Duration
}

func (s *Service) Handle(m msg.Message) error {
	_, err := inbox.Once(s.DB, "saga", m, func(tx *store.Tx) error {
		if m.Type == contracts.OrderPlaced {
			placed, err := msg.Decode[contracts.OrderPlacedV1](m)
			if err != nil {
				return Permanent(err)
			}
			if _, exists, _ := store.Load[OrderSaga](tx, table, placed.OrderID); exists {
				return nil // a second OrderPlaced for the same order
			}
			sg, outs := Start(placed, s.Now(), s.StepTimeout)
			return s.persist(tx, sg, outs, m)
		}
		ref, err := msg.Decode[contracts.OrderRef](m)
		if err != nil || ref.OrderID == "" {
			return Permanent(fmt.Errorf("undecodable %s", m.Type))
		}
		sg, ok, err := store.Load[OrderSaga](tx, table, ref.OrderID)
		if err != nil || !ok {
			return fmt.Errorf("saga %s not found yet", ref.OrderID) // transient: OrderPlaced may arrive later
		}
		outs := sg.Handle(m, s.Now(), s.StepTimeout)
		return s.persist(tx, &sg, outs, m)
	})
	return err
}

// Tick is driven by a scheduler. One saga per transaction.
func (s *Service) Tick() error {
	var ids []string
	s.DB.View(func(tx *store.Tx) { ids = tx.Keys(table) })
	for _, id := range ids {
		err := s.DB.Tx(func(tx *store.Tx) error {
			sg, _, err := store.Load[OrderSaga](tx, table, id)
			if err != nil {
				return err
			}
			outs := sg.Expire(s.Now())
			if len(outs) == 0 {
				return nil
			}
			return s.persist(tx, &sg, outs, msg.Message{ID: "timer", Correlation: id})
		})
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *Service) persist(tx *store.Tx, sg *OrderSaga, outs []Out, cause msg.Message) error {
	if err := store.Save(tx, table, sg.OrderID, sg); err != nil {
		return err
	}
	for _, o := range outs {
		m, err := msg.New(o.Type, sg.OrderID, sg.Version, o.Payload)
		if err != nil {
			return err
		}
		corr := cause.Correlation
		if corr == "" {
			corr = cause.ID
		}
		if _, err := outbox.Add(tx, m, corr, cause.ID); err != nil {
			return err
		}
	}
	return nil
}

// Get is a read helper for tests and dashboards.
func (s *Service) Get(orderID string) (sg OrderSaga, ok bool) {
	s.DB.View(func(tx *store.Tx) { sg, ok, _ = store.Load[OrderSaga](tx, table, orderID) })
	return sg, ok
}

A version-checked read model ​

The Seq field is what this package reads: a message applies only if it is exactly the next version; older ones are ignored, a jump is a gap to retry later.

go
// Package projection is a version-checked read model: it applies messages of
// one key in version order, ignores stale ones and refuses to jump over a gap.
// This is what the Seq field of the envelope is for.
package projection

import (
	"fmt"

	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Result string

const (
	Applied Result = "applied"
	Stale   Result = "stale" // seq <= stored: already reflected, ignore and ack
	Gap     Result = "gap"   // seq > stored+1: something is missing, retry later
)

// Apply writes value for the key if m.Seq is exactly the next version.
// Gap is returned as a result, not an error: the caller maps it to a delayed
// retry (transient), then to parking after a limit.
func Apply(tx *store.Tx, table string, m msg.Message, value string) Result {
	var stored int64
	raw, _ := tx.Get(table+"_version", m.Key)
	fmt.Sscan(raw, &stored)
	switch {
	case m.Seq <= stored:
		return Stale
	case m.Seq > stored+1:
		return Gap
	}
	tx.Put(table, m.Key, value)
	tx.Put(table+"_version", m.Key, fmt.Sprint(m.Seq))
	return Applied
}

// Get returns the stored value and version.
func Get(tx *store.Tx, table, key string) (value string, version int64) {
	value, _ = tx.Get(table, key)
	raw, _ := tx.Get(table+"_version", key)
	fmt.Sscan(raw, &version)
	return value, version
}

The edge: budgets and honest degradation ​

go
// Package edge shows where timeouts, budgets and degraded answers live: in the
// application layer at the context's edge, never inside the domain model.
// Circuit breakers and bulkheads are covered in design/error-handling-fault-tolerance.
package edge

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

var ErrBudgetSpent = errors.New("edge: not enough time left for another call")

// CallWithin runs fn with a timeout of min(perCall, what is left of the
// caller's deadline minus a reserve for our own work). Deadline propagation:
// the whole request tree shares one absolute deadline.
func CallWithin[T any](ctx context.Context, perCall, reserve time.Duration, fn func(context.Context) (T, error)) (T, error) {
	var zero T
	timeout := perCall
	if dl, ok := ctx.Deadline(); ok {
		left := time.Until(dl) - reserve
		if left <= 0 {
			return zero, ErrBudgetSpent
		}
		timeout = min(timeout, left)
	}
	cctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	return fn(cctx)
}

// Answer says how fresh a degraded read is, so the UI can show "as of 09:02".
type Answer[T any] struct {
	Value    T
	Stale    bool
	AsOf     time.Time
	Fallback string // why we degraded; empty when fresh
}

// WithStaleFallback returns the live value, or the last known value flagged as
// stale. It never invents a value: no cache entry means the error is returned.
func WithStaleFallback[T any](ctx context.Context, live func(context.Context) (T, error), last func() (T, time.Time, bool)) (Answer[T], error) {
	v, err := live(ctx)
	if err == nil {
		return Answer[T]{Value: v, AsOf: time.Now()}, nil
	}
	if cached, at, ok := last(); ok {
		return Answer[T]{Value: cached, Stale: true, AsOf: at, Fallback: err.Error()}, nil
	}
	return Answer[T]{}, err
}

The hostile broker and the tests ​

go
// Package broker is an in-memory at-least-once broker with failure injection:
// duplicates, reordering and drops. It has one queue per consumer group.
package broker

import (
	"context"
	"strings"
	"sync"

	"academy/designing-for-failure-reliable-messaging/msg"
)

type Faults struct {
	Duplicate bool // deliver every message twice
	Reverse   bool // newest first: worst-case reordering
	DropFirst int  // lose the first N publishes (publisher sees an error)
}

type Memory struct {
	mu     sync.Mutex
	Faults Faults
	subs   map[string][]string // consumer -> type prefixes
	queues map[string][]msg.Message
	drops  int
}

func New() *Memory {
	return &Memory{subs: map[string][]string{}, queues: map[string][]msg.Message{}}
}

func (b *Memory) Subscribe(consumer string, prefixes ...string) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.subs[consumer] = prefixes
}

type ErrLost struct{}

func (ErrLost) Error() string { return "broker: publish not acknowledged" }

func (b *Memory) Publish(_ context.Context, m msg.Message) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.drops < b.Faults.DropFirst {
		b.drops++
		return ErrLost{}
	}
	for consumer, prefixes := range b.subs {
		for _, p := range prefixes {
			if !strings.HasPrefix(m.Type, p) {
				continue
			}
			copies := 1
			if b.Faults.Duplicate {
				copies = 2
			}
			for i := 0; i < copies; i++ {
				if b.Faults.Reverse {
					b.queues[consumer] = append([]msg.Message{m}, b.queues[consumer]...)
				} else {
					b.queues[consumer] = append(b.queues[consumer], m)
				}
			}
			break
		}
	}
	return nil
}

// Receive pops the next message for a consumer group.
func (b *Memory) Receive(consumer string) (msg.Message, bool) {
	b.mu.Lock()
	defer b.mu.Unlock()
	q := b.queues[consumer]
	if len(q) == 0 {
		return msg.Message{}, false
	}
	b.queues[consumer] = q[1:]
	return q[0], true
}

// Lag is the queue depth of a consumer group: a metric to alert on.
func (b *Memory) Lag(consumer string) int {
	b.mu.Lock()
	defer b.mu.Unlock()
	return len(b.queues[consumer])
}

// Push puts a message straight back on one consumer's queue (used by tests to
// release messages that were held back).
func (b *Memory) Push(consumer string, m msg.Message) {
	b.mu.Lock()
	defer b.mu.Unlock()
	b.queues[consumer] = append(b.queues[consumer], m)
}

The world wires three contexts to one broker, with a switch for "Billing is down":

go
// Package sim wires three contexts, each with its own database, outbox relay
// and inbox, to one at-least-once broker. It is the integration edge the
// tests attack with duplicates, reordering, lost publishes, crashes and a
// neighbour that is down.
package sim

import (
	"context"
	"fmt"
	"math/rand/v2"
	"time"

	"academy/designing-for-failure-reliable-messaging/billing"
	"academy/designing-for-failure-reliable-messaging/broker"
	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/dlq"
	"academy/designing-for-failure-reliable-messaging/fulfilment"
	"academy/designing-for-failure-reliable-messaging/inbox"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/retry"
	"academy/designing-for-failure-reliable-messaging/saga"
	"academy/designing-for-failure-reliable-messaging/sales"
	"academy/designing-for-failure-reliable-messaging/store"
)

type Clock struct{ T time.Time }

func (c *Clock) Now() time.Time          { return c.T }
func (c *Clock) Advance(d time.Duration) { c.T = c.T.Add(d) }

type heldMessage struct {
	consumer string
	m        msg.Message
}

type World struct {
	Clock  *Clock
	Broker *broker.Memory
	DLQ    *dlq.Queue

	SalesDB, FulfilDB, BillDB *store.DB
	Saga                      *saga.Service
	Fulfil                    *fulfilment.Service
	Bill                      *billing.Service
	Relays                    []*outbox.Relay

	BillingDown bool // the neighbour is down: its queue fills, nobody answers
	Policy      retry.Policy
	Sleeps      []time.Duration // recorded backoff waits
	Handled     map[string]int  // consumer -> messages that reached the handler
	Trace       func(consumer string, m msg.Message)
	// Hold lets a test delay chosen messages: a slow neighbour or a stuck partition.
	Hold func(consumer string, m msg.Message) bool
	held []heldMessage
}

func NewWorld() *World {
	w := &World{
		Clock:   &Clock{T: time.Date(2026, 11, 25, 9, 0, 0, 0, time.UTC)},
		Broker:  broker.New(),
		DLQ:     &dlq.Queue{},
		Handled: map[string]int{},
	}
	w.SalesDB, w.FulfilDB, w.BillDB = store.New("sales"), store.New("fulfilment"), store.New("billing")
	w.Saga = &saga.Service{DB: w.SalesDB, Now: w.Clock.Now, StepTimeout: 30 * time.Second}
	w.Fulfil = &fulfilment.Service{DB: w.FulfilDB, FailShipmentFor: map[string]bool{}}
	w.Bill = &billing.Service{DB: w.BillDB, DeclineFor: map[string]bool{}}
	for _, db := range []*store.DB{w.SalesDB, w.FulfilDB, w.BillDB} {
		w.Relays = append(w.Relays, &outbox.Relay{DB: db, Pub: w.Broker})
	}
	w.Broker.Subscribe("saga", "sales.order.placed", "fulfilment.", "billing.")
	w.Broker.Subscribe("sales-order", "sales.order.confirmed", "sales.order.cancelled")
	w.Broker.Subscribe("notify", "sales.order.confirmed", "sales.order.cancelled")
	w.Broker.Subscribe("fulfilment", "cmd.fulfilment.")
	w.Broker.Subscribe("billing", "cmd.billing.")
	rng := rand.New(rand.NewPCG(1, 2))
	w.Policy = retry.Policy{MaxAttempts: 4, Base: 100 * time.Millisecond, Cap: 2 * time.Second, Rand: rng.Float64}
	return w
}

func (w *World) handlers() map[string]func(msg.Message) error {
	return map[string]func(msg.Message) error{
		"saga":        w.Saga.Handle,
		"fulfilment":  w.Fulfil.Handle,
		"billing":     w.Bill.Handle,
		"sales-order": w.salesOrder,
		"notify":      w.notify,
	}
}

func (w *World) salesOrder(m msg.Message) error {
	_, err := inbox.Once(w.SalesDB, "sales-order", m, func(tx *store.Tx) error {
		if err := sales.OnOutcome(tx, m); err != nil {
			return retry.Permanent{Err: err}
		}
		return nil
	})
	return err
}

// notify sends the customer an e-mail. "Add one e-mail" is NOT naturally
// idempotent: without the inbox a duplicate message means a duplicate e-mail.
func (w *World) notify(m msg.Message) error {
	_, err := inbox.Once(w.SalesDB, "notify", m, func(tx *store.Tx) error {
		ref, err := msg.Decode[contracts.OrderRef](m)
		if err != nil {
			return retry.Permanent{Err: err}
		}
		var n int
		raw, _ := tx.Get("emails", ref.OrderID)
		fmt.Sscan(raw, &n)
		tx.Put("emails", ref.OrderID, fmt.Sprint(n+1))
		return nil
	})
	return err
}

// Emails is the number of e-mails sent for an order.
func (w *World) Emails(orderID string) (n int) {
	w.SalesDB.View(func(tx *store.Tx) {
		raw, _ := tx.Get("emails", orderID)
		fmt.Sscan(raw, &n)
	})
	return n
}

// Pump runs relays and consumers until nothing moves. It returns the number
// of rounds it needed. A relay crash stops that round; the next one resumes.
func (w *World) Pump() int {
	ctx := context.Background()
	handlers := w.handlers()
	for round := 1; round <= 200; round++ {
		moved := false
		for _, r := range w.Relays {
			if n, _ := r.RunOnce(ctx); n > 0 {
				moved = true
			}
		}
		for _, name := range []string{"saga", "sales-order", "notify", "fulfilment", "billing"} {
			if name == "billing" && w.BillingDown {
				continue
			}
			for {
				m, ok := w.Broker.Receive(name)
				if !ok {
					break
				}
				moved = true
				if w.Hold != nil && w.Hold(name, m) {
					w.held = append(w.held, heldMessage{name, m})
					continue
				}
				w.Handled[name]++
				if w.Trace != nil {
					w.Trace(name, m)
				}
				h := handlers[name]
				_, _ = retry.Process(w.Policy, func(d time.Duration) { w.Sleeps = append(w.Sleeps, d) }, m, h, w.DLQ)
			}
		}
		// A relay that failed to publish is not "idle": it polls again next round.
		backlog := outbox.Backlog(w.SalesDB) + outbox.Backlog(w.FulfilDB) + outbox.Backlog(w.BillDB)
		if !moved && backlog == 0 {
			return round
		}
	}
	return 200
}

// ReleaseHeld delivers the delayed messages now (late replies and late commands).
func (w *World) ReleaseHeld() {
	for _, h := range w.held {
		w.Broker.Push(h.consumer, h.m)
	}
	w.held = nil
}

// Order places an order for one SKU and returns its id.
func (w *World) Order(id, sku string, qty int, total int64) error {
	return sales.PlaceOrder(w.SalesDB, id, "cust-1", total, []contracts.Line{{SKU: sku, Qty: qty}})
}

The tests inject the failures from the taxonomy and assert business outcomes:

go
package sim

import (
	"context"
	"errors"
	"testing"
	"time"

	"academy/designing-for-failure-reliable-messaging/broker"
	"academy/designing-for-failure-reliable-messaging/contracts"
	"academy/designing-for-failure-reliable-messaging/msg"
	"academy/designing-for-failure-reliable-messaging/outbox"
	"academy/designing-for-failure-reliable-messaging/saga"
	"academy/designing-for-failure-reliable-messaging/sales"
)

func newWorld(t *testing.T) *World {
	t.Helper()
	w := NewWorld()
	w.Fulfil.Seed("sku-mug", 5)
	return w
}

func mustOrder(t *testing.T, w *World, id string) {
	t.Helper()
	if err := w.Order(id, "sku-mug", 2, 3000); err != nil {
		t.Fatal(err)
	}
}

func assertOrder(t *testing.T, w *World, id string, want sales.Status) {
	t.Helper()
	o, ok := sales.Load(w.SalesDB, id)
	if !ok || o.Status != want {
		t.Fatalf("order %s: got %+v ok=%v, want status %s", id, o, ok, want)
	}
}

func TestHappyPathSurvivesDuplicatesAndReordering(t *testing.T) {
	w := newWorld(t)
	w.Broker.Faults = broker.Faults{Duplicate: true, Reverse: true}
	mustOrder(t, w, "o-1")
	w.Pump()

	assertOrder(t, w, "o-1", sales.Confirmed)
	if n := w.Bill.Charges("o-1"); n != 1 {
		t.Fatalf("charged %d times, want exactly 1", n)
	}
	if got := w.Fulfil.Stock("sku-mug"); got != 3 {
		t.Fatalf("stock = %d, want 3 (reserved once)", got)
	}
	if w.Emails("o-1") != 1 {
		t.Fatalf("e-mails sent = %d, want 1: an additive effect needs the inbox", w.Emails("o-1"))
	}
	if w.DLQ.Depth() != 0 {
		t.Fatalf("unexpected parked messages: %v", w.DLQ.Items())
	}
	if sg, _ := w.Saga.Get("o-1"); sg.State != saga.Completed {
		t.Fatalf("saga state = %s", sg.State)
	}
}

func TestPaymentDeclinedCompensatesStock(t *testing.T) {
	w := newWorld(t)
	w.Bill.DeclineFor["o-2"] = true
	mustOrder(t, w, "o-2")
	w.Pump()

	assertOrder(t, w, "o-2", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5 (reservation released)", got)
	}
	if w.Bill.Charges("o-2") != 0 {
		t.Fatal("money was taken for a declined order")
	}
}

func TestOutOfStockCancelsWithoutCompensation(t *testing.T) {
	w := NewWorld()
	w.Fulfil.Seed("sku-mug", 1)
	mustOrder(t, w, "o-3")
	w.Pump()
	assertOrder(t, w, "o-3", sales.Cancelled)
	if w.Bill.Charges("o-3") != 0 {
		t.Fatal("charged an order that never got stock")
	}
}

func TestShipmentFailureRefundsAndReleases(t *testing.T) {
	w := newWorld(t)
	w.Fulfil.FailShipmentFor["o-4"] = true
	mustOrder(t, w, "o-4")
	w.Pump()

	assertOrder(t, w, "o-4", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	if sg, _ := w.Saga.Get("o-4"); sg.State != saga.Cancelled || sg.Reason != "shipment failed" {
		t.Fatalf("saga = %+v", sg)
	}
}

// Billing is down. Sales keeps accepting orders; the saga times out and
// compensates; when Billing returns it replays the old charge and then the
// refund, and everything converges to "cancelled, refunded, stock back".
func TestBillingDownTimeoutThenLateReplies(t *testing.T) {
	w := newWorld(t)
	w.BillingDown = true
	mustOrder(t, w, "o-5")
	w.Pump()
	assertOrder(t, w, "o-5", sales.Pending) // the customer sees "pending", not an error

	w.Clock.Advance(31 * time.Second)
	if err := w.Saga.Tick(); err != nil {
		t.Fatal(err)
	}
	w.Pump()
	if sg, _ := w.Saga.Get("o-5"); sg.State != saga.Compensating {
		t.Fatalf("saga = %s, want compensating while the refund is outstanding", sg.State)
	}

	w.BillingDown = false
	w.Pump()
	assertOrder(t, w, "o-5", sales.Cancelled)
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	if sg, _ := w.Saga.Get("o-5"); sg.State != saga.Cancelled {
		t.Fatalf("saga = %s", sg.State)
	}
}

func TestRelayCrashAfterPublishIsHarmless(t *testing.T) {
	w := newWorld(t)
	crashed := false
	w.Relays[0].CrashAfterPublish = func(msg.Message) bool {
		if crashed {
			return false
		}
		crashed = true
		return true
	}
	mustOrder(t, w, "o-6")
	w.Pump()

	assertOrder(t, w, "o-6", sales.Confirmed)
	if w.Bill.Charges("o-6") != 1 {
		t.Fatal("duplicate publish caused a double charge")
	}
	if !crashed {
		t.Fatal("crash hook never fired")
	}
	if outbox.Backlog(w.SalesDB) != 0 {
		t.Fatal("outbox not drained after restart")
	}
}

func TestLostPublishesAreRetriedByTheRelay(t *testing.T) {
	w := newWorld(t)
	w.Broker.Faults.DropFirst = 3
	mustOrder(t, w, "o-7")
	w.Pump()
	assertOrder(t, w, "o-7", sales.Confirmed)
}

func TestPoisonMessageIsParkedNotSwallowed(t *testing.T) {
	w := newWorld(t)
	_ = w.Broker.Publish(context.Background(), msg.Message{ID: "x-1", Type: "cmd.fulfilment.Bogus.v1", Key: "o-8", Payload: []byte(`{"order_id":"o-8"}`)})
	_ = w.Broker.Publish(context.Background(), msg.Message{ID: "x-2", Type: contracts.CmdReserveStock, Key: "o-9", Payload: []byte(`not json`)})
	mustOrder(t, w, "o-10")
	w.Pump()

	if w.DLQ.Depth() != 2 {
		t.Fatalf("parked = %d, want 2: %v", w.DLQ.Depth(), w.DLQ.Items())
	}
	for _, p := range w.DLQ.Items() {
		if p.Attempts != 1 {
			t.Fatalf("permanent errors must not be retried: %s", p)
		}
	}
	assertOrder(t, w, "o-10", sales.Confirmed) // the poison did not block the queue
}

func TestPlaceOrderIsAtomicWithItsOutboxRow(t *testing.T) {
	w := newWorld(t)
	if err := sales.PlaceOrder(w.SalesDB, "o-11", "c", 1, nil); !errors.Is(err, sales.ErrEmptyOrder) {
		t.Fatalf("err = %v", err)
	}
	if _, ok := sales.Load(w.SalesDB, "o-11"); ok || outbox.Backlog(w.SalesDB) != 0 {
		t.Fatal("a rolled-back order left an order row or an outbox row")
	}
}

// A stuck partition delays CreateShipment past the saga's deadline. The saga
// cancels everything; the late command is then refused by the tombstone.
func TestShippingStallsThenLateCreateIsRefused(t *testing.T) {
	w := newWorld(t)
	w.Hold = func(consumer string, m msg.Message) bool { return m.Type == contracts.CmdCreateShipment }
	mustOrder(t, w, "o-12")
	w.Pump()
	assertOrder(t, w, "o-12", sales.Pending)

	w.Clock.Advance(31 * time.Second)
	if err := w.Saga.Tick(); err != nil {
		t.Fatal(err)
	}
	w.Hold = nil
	w.Pump()
	assertOrder(t, w, "o-12", sales.Cancelled)

	w.ReleaseHeld() // the stuck CreateShipment is finally delivered
	w.Pump()
	if got := w.Fulfil.Shipment("o-12"); got != "cancelled" {
		t.Fatalf("shipment = %q: a parcel exists for a cancelled, refunded order", got)
	}
	if got := w.Fulfil.Stock("sku-mug"); got != 5 {
		t.Fatalf("stock = %d, want 5", got)
	}
	assertOrder(t, w, "o-12", sales.Cancelled)
}

The retry policy, the pure saga, the inbox, Fulfilment's handlers, the projection and the edge helpers have their own focused tests (retry/retry_test.go, saga/saga_test.go, inbox/inbox_test.go, fulfilment/service_test.go, projection/projection_test.go, edge/edge_test.go). The runnable demo is cmd/demo/main.go.

What not to write ​

The anti-patterns as code, so they can be recognised in a review:

go
// Package wrong collects the anti-patterns this chapter warns about. It
// compiles and it "works" on a good day. Do not copy it.
package wrong

import (
	"context"
	"database/sql"
	"net/http"
)

type Publisher interface {
	Publish(ctx context.Context, topic string, body []byte) error
}

// DualWrite commits the database, then calls the broker. A crash (or a broker
// error) between the two lines loses the event forever: the order exists and
// nobody was told. Swapping the lines gives the opposite bug: an event for an
// order that was rolled back.
func DualWrite(ctx context.Context, db *sql.DB, pub Publisher, id string) error {
	if _, err := db.ExecContext(ctx, `INSERT INTO orders (id, status) VALUES ($1, 'pending')`, id); err != nil {
		return err
	}
	return pub.Publish(ctx, "order.placed", []byte(id)) // not atomic with the INSERT
}

// ChargeWithBlindRetry retries a non-idempotent call. If the first attempt
// succeeded but the response was lost, the customer is charged twice.
func ChargeWithBlindRetry(client *http.Client, url string) error {
	var err error
	for i := 0; i < 3; i++ {
		var resp *http.Response
		resp, err = client.Post(url, "application/json", nil) // no Idempotency-Key header
		if err == nil {
			resp.Body.Close()
			return nil
		}
	}
	return err
}

// SwallowEverything acknowledges a message whatever happened. A bug in the
// handler turns into silently lost business events and an empty dashboard.
func SwallowEverything(handle func([]byte) error, body []byte) {
	_ = handle(body) // error ignored, message acked, no log, no DLQ
}

// SilentFallback hides a dead neighbour behind a made-up answer. The order is
// "confirmed" with a price of zero, and nobody is alerted.
func SilentFallback(get func() (int64, error)) int64 {
	price, err := get()
	if err != nil {
		return 0
	}
	return price
}

The Go angle ​

  • database/sql: db.BeginTx(ctx, nil) for the producer transaction, tx.ExecContext for the aggregate and outbox inserts; check the unique violation of the inbox with the driver's error type (pgx: *pgconn.PgError with code 23505). Always defer tx.Rollback() and commit explicitly.
  • context: carry the deadline from the request to every outgoing call (context.WithTimeout); a handler that ignores ctx.Done() keeps working after the caller left.
  • golang.org/x/sync/errgroup: fan-out calls with a shared cancel (errgroup.WithContext); use it for parallel reads, not for writes that must be atomic.
  • Watermill documents a "Forwarder (the outbox pattern)", an SQL Pub/Sub for PostgreSQL and MySQL, router middleware and "Requeuing After Error"; it is the library to look at before writing a relay of your own (Watermill docs). The snippets here use no dependency so every line is visible.
  • Goroutines make the relay trivial and the restart the hard part: design the relay to be killed at any line (the CrashAfterPublish test).

Run the whole module: cd docs/snippets/ddd/designing-for-failure-reliable-messaging/go && go vet ./... && go test -race ./....

Laravel ​

Laravel 13 on PHP 8.4. Reviewed with php -l and by reading, not run here (no Laravel application in the repository); the failure behaviour of the same design is proven by the Go module. The queue features used are those of the Laravel 13 Queues documentation: the Tries, Backoff, MaxExceptions, Timeout and UniqueFor attributes, ShouldBeUnique, WithoutOverlapping, ThrottlesExceptions, retryUntil, failed_jobs, dontRetry and batches. RabbitMQ and Kafka are not built-in drivers; the relay below publishes through a Publisher interface you implement with the package you choose (Laravel Queue Internals).

The tables ​

php
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Written in the SAME transaction as the aggregate; read by the relay.
        Schema::create('outbox_messages', function (Blueprint $t) {
            $t->id();                                   // relay order
            $t->uuid('message_id')->unique();           // the consumers' dedup key
            $t->string('type');
            $t->string('key');                          // aggregate id: the ordering unit
            $t->unsignedBigInteger('seq');              // aggregate version at emission
            $t->string('correlation_id');
            $t->string('causation_id')->nullable();
            $t->json('payload');
            $t->timestamp('sent_at')->nullable();
            $t->timestamp('created_at')->useCurrent();
            $t->index(['sent_at', 'id']);
        });

        // One row per (consumer, message): the unique index IS the idempotency.
        Schema::create('inbox_messages', function (Blueprint $t) {
            $t->string('consumer');
            $t->uuid('message_id');
            $t->timestamp('processed_at')->useCurrent();
            $t->primary(['consumer', 'message_id']);
        });

        // The saga is an aggregate: its own row, its own version.
        Schema::create('order_sagas', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('state');
            $t->unsignedBigInteger('version');
            $t->timestamp('deadline_at')->nullable();
            $t->json('lines');
            $t->unsignedBigInteger('total_cents');
            $t->json('outstanding');                    // compensations not yet acknowledged
            $t->string('reason')->nullable();
            $t->index(['state', 'deadline_at']);
        });

        // The parking lot for poison messages (a table, so humans can query it).
        Schema::create('parked_messages', function (Blueprint $t) {
            $t->id();
            $t->string('consumer');
            $t->uuid('message_id');
            $t->string('type');
            $t->json('payload');
            $t->text('reason');
            $t->unsignedSmallInteger('attempts');
            $t->timestamp('parked_at')->useCurrent();
        });

        // Idempotency keys for the HTTP edge of Sales.
        Schema::create('idempotency_keys', function (Blueprint $t) {
            $t->string('key')->primary();
            $t->unsignedSmallInteger('status')->nullable();
            $t->json('response')->nullable();
            $t->timestamp('created_at')->useCurrent();
        });

        Schema::create('orders', function (Blueprint $t) {
            $t->string('id')->primary();
            $t->string('customer_id');
            $t->unsignedBigInteger('total_cents');
            $t->json('lines');
            $t->string('status');
            $t->string('reason')->nullable();
            $t->unsignedBigInteger('version')->default(1);
            $t->timestamps();
        });

        // Fulfilment: stock, reservations (with tombstones) and shipments (with tombstones).
        Schema::create('stock', function (Blueprint $t) {
            $t->string('sku')->primary();
            $t->unsignedInteger('qty');
        });
        Schema::create('reservations', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('status');                       // held | released (tombstone)
            $t->json('lines');
        });
        Schema::create('shipments', function (Blueprint $t) {
            $t->string('order_id')->primary();
            $t->string('status');                       // created | cancelled (tombstone)
        });

        Schema::create('payments', function (Blueprint $t) {
            $t->string('idempotency_key')->primary();   // the provider call is keyed by it too
            $t->string('order_id')->index();
            $t->unsignedBigInteger('amount_cents');
            $t->string('status');                       // charged | refunded | cancelled (tombstone)
            $t->timestamps();
        });
    }

    public function down(): void
    {
        foreach (['shipments', 'reservations', 'stock', 'payments', 'orders', 'idempotency_keys', 'parked_messages', 'order_sagas', 'inbox_messages', 'outbox_messages'] as $table) {
            Schema::dropIfExists($table);
        }
    }
};

Reliable publishing: aggregate, outbox row, relay command ​

php
<?php

namespace App\Sales\Domain;

use Illuminate\Database\Eloquent\Model;

/**
 * The Order aggregate: the consistency island that owns the order status.
 * Other contexts never write it; they send messages.
 */
final class Order extends Model
{
    public $incrementing = false;
    protected $keyType = 'string';
    protected $table = 'orders';
    protected $guarded = [];
    protected $casts = ['lines' => 'array'];

    /** @param list<array{sku: string, qty: int}> $lines */
    public static function place(string $id, string $customerId, int $totalCents, array $lines): self
    {
        if ($lines === []) {
            throw new \DomainException('An order needs at least one line');
        }

        return new self([
            'id' => $id, 'customer_id' => $customerId, 'total_cents' => $totalCents,
            'lines' => $lines, 'status' => 'pending', 'version' => 1,
        ]);
    }

    /** Idempotent: repeating the outcome is a no-op; a terminal order never flips. */
    public function confirm(): bool
    {
        if ($this->status === 'confirmed') {
            return false;
        }
        if ($this->status === 'cancelled') {
            throw new \DomainException("Order {$this->id} is cancelled, cannot confirm");
        }
        $this->status = 'confirmed';
        $this->version++;

        return true;
    }

    public function cancel(string $reason): bool
    {
        if ($this->status === 'cancelled') {
            return false;
        }
        if ($this->status === 'confirmed') {
            throw new \DomainException("Order {$this->id} is confirmed, cannot cancel");
        }
        $this->status = 'cancelled';
        $this->reason = $reason;
        $this->version++;

        return true;
    }
}
php
<?php

namespace App\Sales\Application;

use App\Messaging\Outbox;
use App\Sales\Domain\Order;
use Illuminate\Support\Facades\DB;

final class PlaceOrder
{
    /**
     * One unit of work: ONE aggregate + ONE outbox row in ONE local
     * transaction. No broker call here; the relay publishes later.
     *
     * @param list<array{sku: string, qty: int}> $lines
     */
    public function __invoke(string $orderId, string $customerId, int $totalCents, array $lines): Order
    {
        return DB::transaction(function () use ($orderId, $customerId, $totalCents, $lines): Order {
            $order = Order::place($orderId, $customerId, $totalCents, $lines);
            $order->save();

            Outbox::record('sales.order.placed.v1', $order->id, $order->version, [
                'order_id' => $order->id, 'customer_id' => $customerId,
                'total_cents' => $totalCents, 'lines' => $lines,
            ]);

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

namespace App\Messaging;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

final class Outbox
{
    /**
     * Must be called INSIDE the transaction that changes the aggregate.
     * Throws if there is no open transaction: a forgotten wrapper is a bug,
     * not a silent dual write.
     *
     * @param array<string, mixed> $payload
     */
    public static function record(
        string $type,
        string $key,
        int $seq,
        array $payload,
        ?string $correlationId = null,
        ?string $causationId = null,
    ): string {
        if (DB::transactionLevel() === 0) {
            throw new \LogicException('Outbox::record() outside a transaction');
        }

        $id = (string) Str::uuid();

        DB::table('outbox_messages')->insert([
            'message_id' => $id,
            'type' => $type,
            'key' => $key,
            'seq' => $seq,
            'correlation_id' => $correlationId ?? $id,
            'causation_id' => $causationId,
            'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
        ]);

        return $id;
    }
}

The relay is a long-running Artisan command under Supervisor (php artisan outbox:relay), guarded by Cache::lock so only one runs; it blocks later rows of a key whose earlier row failed:

php
<?php

namespace App\Console;

use App\Messaging\Publisher;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * Polling publisher. Publish first, mark after: a crash in between means a
 * duplicate, never a loss. Consumers dedup with the inbox.
 *
 * Ordering per aggregate: one relay at a time (Cache::lock), rows in id order,
 * and a failed key blocks only its own later rows.
 */
final class RelayOutbox extends Command
{
    protected $signature = 'outbox:relay {--once : Run one batch and exit} {--batch=100}';
    protected $description = 'Publish unsent outbox rows to the broker';

    public function handle(Publisher $publisher): int
    {
        do {
            $published = Cache::lock('outbox-relay', 30)->get(fn () => $this->runBatch($publisher, (int) $this->option('batch')));

            if ($this->option('once')) {
                return self::SUCCESS;
            }

            if (! $published) {
                usleep(200_000); // idle: poll again in 200 ms
            }
        } while (true);
    }

    private function runBatch(Publisher $publisher, int $batch): int
    {
        $rows = DB::table('outbox_messages')->whereNull('sent_at')->orderBy('id')->limit($batch)->get();
        $blocked = [];
        $published = 0;

        foreach ($rows as $row) {
            if (isset($blocked[$row->key])) {
                continue; // keep per-aggregate order
            }

            try {
                $publisher->publish([
                    'id' => $row->message_id, 'type' => $row->type, 'key' => $row->key, 'seq' => $row->seq,
                    'correlation' => $row->correlation_id, 'causation' => $row->causation_id,
                    'payload' => json_decode($row->payload, true, flags: JSON_THROW_ON_ERROR),
                ]);
            } catch (\Throwable $e) {
                report($e);
                $blocked[$row->key] = true;

                continue;
            }

            DB::table('outbox_messages')->where('id', $row->id)->update(['sent_at' => now()]);
            $published++;
        }

        return $published;
    }
}
php
<?php

namespace App\Messaging;

interface Publisher
{
    /** Throw on any failure; the relay will retry the same message later. */
    public function publish(array $message): void;
}

Reliable consuming: the inbox ​

php
<?php

namespace App\Messaging;

use Closure;
use Illuminate\Support\Facades\DB;

final class Inbox
{
    /**
     * Run $effect at most once per (consumer, message id). The dedup row and
     * the business effect commit together; if $effect throws, the dedup row
     * rolls back and the redelivery is processed normally.
     *
     * @param Closure(): void $effect
     * @return bool false when the message was a duplicate
     */
    public static function once(string $consumer, string $messageId, Closure $effect): bool
    {
        return DB::transaction(function () use ($consumer, $messageId, $effect): bool {
            // INSERT ... ON CONFLICT DO NOTHING (PostgreSQL) / INSERT IGNORE (MySQL)
            $inserted = DB::table('inbox_messages')->insertOrIgnore([
                'consumer' => $consumer,
                'message_id' => $messageId,
            ]);

            if ($inserted === 0) {
                return false; // already processed: acknowledge and move on
            }

            $effect();

            return true;
        });
    }
}

Billing is idempotent twice over, by message id and by business key, and leaves a tombstone for a refund that arrives before its charge:

php
<?php

namespace App\Billing;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\Outbox;
use App\Messaging\PermanentFailure;
use Illuminate\Support\Facades\DB;

/**
 * Idempotent twice over: the inbox dedups the message, and the payments table
 * dedups the business command by its idempotency key. A refund for an unknown
 * charge leaves a tombstone so a late charge for that order is declined.
 */
final class ChargeHandler implements MessageHandler
{
    public function __construct(private readonly PaymentProvider $provider) {}

    public function handle(array $message): void
    {
        Inbox::once('billing', $message['id'], function () use ($message): void {
            $p = $message['payload'];
            $orderId = $p['order_id'] ?? throw new PermanentFailure('order_id missing');

            match ($message['type']) {
                'cmd.billing.ChargePayment.v1' => $this->charge($message, $p),
                'cmd.billing.RefundPayment.v1' => $this->refund($message, $orderId),
                default => throw new PermanentFailure("Unknown command {$message['type']}"),
            };
        });
    }

    /** @param array<string, mixed> $p */
    private function charge(array $message, array $p): void
    {
        $key = $p['idempotency_key'] ?? throw new PermanentFailure('idempotency_key missing');

        if (DB::table('payments')->where('idempotency_key', $key)->exists()) {
            $this->reply($message, 'billing.payment.charged.v1', $p['order_id']); // same key: answer, do not charge again

            return;
        }
        $tombstone = DB::table('payments')->where('order_id', $p['order_id'])->where('status', 'cancelled')->exists();
        if ($tombstone || ! $this->provider->charge($key, $p['amount_cents'])) { // the provider call carries the same key
            $this->reply($message, 'billing.payment.declined.v1', $p['order_id']);

            return;
        }

        DB::table('payments')->insert([
            'idempotency_key' => $key, 'order_id' => $p['order_id'], 'amount_cents' => $p['amount_cents'],
            'status' => 'charged', 'created_at' => now(), 'updated_at' => now(),
        ]);
        $this->reply($message, 'billing.payment.charged.v1', $p['order_id']);
    }

    private function refund(array $message, string $orderId): void
    {
        $charged = DB::table('payments')->where('order_id', $orderId)->where('status', 'charged')->first();
        if ($charged !== null) {
            $this->provider->refund("refund-{$orderId}", $charged->amount_cents);
            DB::table('payments')->where('idempotency_key', $charged->idempotency_key)->update(['status' => 'refunded']);
        } elseif (! DB::table('payments')->where('order_id', $orderId)->exists()) {
            DB::table('payments')->insert([ // tombstone
                'idempotency_key' => "cancelled-{$orderId}", 'order_id' => $orderId, 'amount_cents' => 0,
                'status' => 'cancelled', 'created_at' => now(), 'updated_at' => now(),
            ]);
        }
        $this->reply($message, 'billing.payment.refunded.v1', $orderId);
    }

    private function reply(array $cause, string $type, string $orderId): void
    {
        Outbox::record($type, $orderId, 0, ['order_id' => $orderId], $cause['correlation'] ?? $cause['id'], $cause['id']);
    }
}

Fulfilment's handler (reserve, release, create and cancel shipment) uses a conditional decrement (no read-then-write race), a nested DB::transaction as a savepoint so a refused line undoes the earlier lines, and tombstones:

php
<?php

namespace App\Fulfilment;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\Outbox;
use App\Messaging\PermanentFailure;
use Illuminate\Support\Facades\DB;

/**
 * Reserve/Release are commutative: Release before Reserve leaves a tombstone,
 * so the late Reserve is refused and the final state is the same either way.
 */
final class StockHandler implements MessageHandler
{
    public function handle(array $message): void
    {
        Inbox::once('fulfilment', $message['id'], function () use ($message): void {
            $orderId = $message['payload']['order_id'] ?? throw new PermanentFailure('order_id missing');

            match ($message['type']) {
                'cmd.fulfilment.ReserveStock.v1' => $this->reserve($message, $orderId),
                'cmd.fulfilment.ReleaseStock.v1' => $this->release($message, $orderId),
                'cmd.fulfilment.CreateShipment.v1' => $this->ship($message, $orderId),
                'cmd.fulfilment.CancelShipment.v1' => $this->cancelShipment($message, $orderId),
                default => throw new PermanentFailure("Unknown command {$message['type']}"),
            };
        });
    }

    private function reserve(array $message, string $orderId): void
    {
        $existing = DB::table('reservations')->where('order_id', $orderId)->first();
        if ($existing !== null) {
            $this->reply($message, $existing->status === 'held' ? 'fulfilment.stock.reserved.v1' : 'fulfilment.stock.rejected.v1', $orderId);

            return;
        }

        try {
            // Nested DB::transaction() is a savepoint: a refused line undoes the lines before it.
            DB::transaction(function () use ($message, $orderId): void {
                foreach ($message['payload']['lines'] as $line) {
                    // Atomic conditional update: no read-then-write race (see optimistic-pessimistic-locking).
                    $ok = DB::table('stock')->where('sku', $line['sku'])->where('qty', '>=', $line['qty'])->decrement('qty', $line['qty']);
                    if ($ok === 0) {
                        throw new StockRejected($orderId, $line['sku']);
                    }
                }
            });
        } catch (StockRejected) {
            // A business "no" is an answer, not a failure: reply, do not retry.
            $this->reply($message, 'fulfilment.stock.rejected.v1', $orderId);

            return;
        }
        DB::table('reservations')->insert(['order_id' => $orderId, 'status' => 'held', 'lines' => json_encode($message['payload']['lines'])]);
        $this->reply($message, 'fulfilment.stock.reserved.v1', $orderId);
    }

    private function release(array $message, string $orderId): void
    {
        $r = DB::table('reservations')->where('order_id', $orderId)->first();
        if ($r !== null && $r->status === 'held') {
            foreach (json_decode($r->lines, true) as $line) {
                DB::table('stock')->where('sku', $line['sku'])->increment('qty', $line['qty']);
            }
            DB::table('reservations')->where('order_id', $orderId)->update(['status' => 'released']);
        } elseif ($r === null) {
            DB::table('reservations')->insert(['order_id' => $orderId, 'status' => 'released', 'lines' => '[]']); // tombstone
        }
        $this->reply($message, 'fulfilment.stock.released.v1', $orderId);
    }

    private function ship(array $message, string $orderId): void
    {
        $status = DB::table('shipments')->where('order_id', $orderId)->value('status');

        if ($status === 'cancelled') { // CancelShipment arrived first: refuse the late create
            $this->reply($message, 'fulfilment.shipment.failed.v1', $orderId);
        } else {
            if ($status === null) {
                DB::table('shipments')->insert(['order_id' => $orderId, 'status' => 'created']);
            }
            $this->reply($message, 'fulfilment.shipment.created.v1', $orderId);
        }
    }

    /** Compensation: idempotent, and commutative with ship() through the tombstone. */
    private function cancelShipment(array $message, string $orderId): void
    {
        DB::table('shipments')->upsert([['order_id' => $orderId, 'status' => 'cancelled']], ['order_id'], ['status']);
        $this->reply($message, 'fulfilment.shipment.cancelled.v1', $orderId);
    }

    private function reply(array $cause, string $type, string $orderId): void
    {
        Outbox::record($type, $orderId, 0, ['order_id' => $orderId], $cause['correlation'] ?? $cause['id'], $cause['id']);
    }
}
php
<?php

namespace App\Fulfilment;

/** A business "no", not a technical failure: the handler turns it into a StockRejected event, no retry. */
final class StockRejected extends \DomainException
{
    public function __construct(public readonly string $orderId, public readonly string $sku)
    {
        parent::__construct("Insufficient stock for {$sku}");
    }
}

Retries, middleware and failed jobs ​

One broker message becomes one queued job. The job is transport; the guarantee comes from Inbox::once(). ShouldBeUnique is a cheap first filter against enqueuing the same message twice, not the correctness mechanism.

php
<?php

namespace App\Messaging;

use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\MaxExceptions;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Queue\Attributes\UniqueFor;
use Illuminate\Queue\Middleware\ThrottlesExceptions;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Support\Facades\DB;

/**
 * One broker message = one queued job. The job is only the transport; the
 * guarantee comes from Inbox::once() inside the handler.
 *
 *  - ShouldBeUnique + UniqueFor: do not enqueue the same message twice in a row
 *    (cheap first filter; NOT the correctness mechanism, the inbox is).
 *  - WithoutOverlapping(key): one message per aggregate at a time, so a
 *    version-checked handler never races with itself.
 *  - ThrottlesExceptions: if the neighbour keeps failing, stop hammering it.
 *  - Tries/Backoff/MaxExceptions/Timeout: bounded, spaced retries.
 */
#[Tries(6)]
#[MaxExceptions(5)]
#[Backoff([2, 10, 30, 120, 600])]
#[Timeout(30)]
#[UniqueFor(3600)]
final class ConsumeMessage implements ShouldQueue, ShouldBeUnique
{
    use InteractsWithQueue;
    use Queueable;

    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function __construct(
        public readonly string $consumer,
        public readonly array $message,
    ) {}

    public function uniqueId(): string
    {
        return $this->consumer . ':' . $this->message['id'];
    }

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            new WithoutOverlapping($this->consumer . ':' . $this->message['key']),
            new ThrottlesExceptions(10, 5 * 60),
        ];
    }

    public function retryUntil(): \DateTimeInterface
    {
        return now()->plus(minutes: 30);
    }

    public function handle(HandlerRegistry $handlers): void
    {
        $handlers->for($this->consumer)->handle($this->message);
    }

    /**
     * Called once, after the last attempt (or after a dontRetry exception).
     * Park the message with the reason: never swallow it.
     */
    public function failed(?\Throwable $e): void
    {
        DB::table('parked_messages')->insert([
            'consumer' => $this->consumer,
            'message_id' => $this->message['id'],
            'type' => $this->message['type'],
            'payload' => json_encode($this->message['payload']),
            'reason' => $e?->getMessage() ?? 'unknown',
            'attempts' => $this->attempts(),
        ]);
    }
}
php
<?php

namespace App\Messaging;

interface MessageHandler
{
    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function handle(array $message): void;
}
php
<?php

namespace App\Messaging;

final class HandlerRegistry
{
    /** @param array<string, MessageHandler> $handlers consumer name => handler */
    public function __construct(private readonly array $handlers) {}

    public function for(string $consumer): MessageHandler
    {
        return $this->handlers[$consumer]
            ?? throw new PermanentFailure("No handler for consumer {$consumer}");
    }
}
php
<?php

namespace App\Messaging;

/** Retrying cannot fix this (bad payload, unknown type). Registered with dontRetry(). */
final class PermanentFailure extends \RuntimeException {}

Poison messages are declared once in bootstrap/app.php with dontRetry, so they skip the retries and land in failed() and the parked_messages table:

php
<?php

use App\Messaging\PermanentFailure;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__ . '/../routes/web.php', commands: __DIR__ . '/../routes/console.php')
    ->withProviders([\App\Providers\MessagingServiceProvider::class])
    ->withCommands([\App\Console\RelayOutbox::class])
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Poison messages: no retry, straight to failed() and the parking table.
        $exceptions->dontRetry([PermanentFailure::class]);
    })
    ->create();

Operations: php artisan queue:work --tries=6 --backoff=... is overridden by the attributes; php artisan queue:failed lists failed jobs and php artisan queue:retry all re-queues them after the fix (the redrive); php artisan queue:prune-failed and queue:prune-batches keep tables small. Bus::batch([...])->allowFailures() fits fan-out of independent jobs (for example sending 500 notifications); it is not a saga.

Sagas ​

The state machine is plain PHP with no framework dependency, so it is unit-tested without a database:

php
<?php

namespace App\Sales\Saga;

enum SagaState: string
{
    case ReservingStock = 'reserving_stock';
    case Charging = 'charging';
    case Shipping = 'shipping';
    case Completed = 'completed';       // terminal
    case Compensating = 'compensating';
    case Cancelled = 'cancelled';       // terminal

    public function isTerminal(): bool
    {
        return $this === self::Completed || $this === self::Cancelled;
    }
}
php
<?php

namespace App\Sales\Saga;

/** A message the saga wants to send: a command to a neighbour or an outcome event. */
final readonly class Out
{
    /** @param array<string, mixed> $payload */
    public function __construct(public string $type, public array $payload) {}
}
php
<?php

namespace App\Sales\Saga;

use DateTimeImmutable;

/**
 * Order -> Reserve stock -> Charge -> Ship, as an aggregate.
 * handle() is a pure state machine: message in, state change + outgoing
 * messages out. Persistence, inbox and outbox live in OrderSagaService.
 */
final class OrderSaga
{
    /**
     * @param list<array{sku: string, qty: int}> $lines
     * @param array<string, bool> $outstanding compensations not yet acknowledged
     */
    public function __construct(
        public readonly string $orderId,
        public SagaState $state,
        public array $lines,
        public int $totalCents,
        public DateTimeImmutable $deadline,
        public array $outstanding = [],
        public ?string $reason = null,
        public int $version = 1,
    ) {}

    /** @return array{0: self, 1: list<Out>} */
    public static function start(string $orderId, array $lines, int $totalCents, DateTimeImmutable $now, int $stepSeconds): array
    {
        $saga = new self($orderId, SagaState::ReservingStock, $lines, $totalCents, $now->modify("+{$stepSeconds} seconds"));

        return [$saga, [new Out('cmd.fulfilment.ReserveStock.v1', ['order_id' => $orderId, 'lines' => $lines])]];
    }

    /** @return list<Out> */
    public function handle(string $type, DateTimeImmutable $now, int $stepSeconds): array
    {
        if ($this->state === SagaState::Completed) {
            return [];
        }
        $ref = ['order_id' => $this->orderId];

        return match ($type) {
            'fulfilment.stock.reserved.v1' => match ($this->state) {
                SagaState::ReservingStock => $this->advance(SagaState::Charging, $now, $stepSeconds, [
                    new Out('cmd.billing.ChargePayment.v1', $ref + [
                        'amount_cents' => $this->totalCents, 'idempotency_key' => "charge-{$this->orderId}",
                    ]),
                ]),
                SagaState::Compensating, SagaState::Cancelled => [new Out('cmd.fulfilment.ReleaseStock.v1', $ref)], // late reply
                default => [],
            },
            'fulfilment.stock.rejected.v1' => $this->state === SagaState::ReservingStock ? $this->cancel('out of stock') : [],
            'billing.payment.charged.v1' => match ($this->state) {
                SagaState::Charging => $this->advance(SagaState::Shipping, $now, $stepSeconds, [
                    new Out('cmd.fulfilment.CreateShipment.v1', ['order_id' => $this->orderId, 'lines' => $this->lines]),
                ]),
                SagaState::Compensating, SagaState::Cancelled => $this->undoLateCharge($ref),
                default => [],
            },
            'billing.payment.declined.v1' => $this->state === SagaState::Charging
                ? $this->compensate('payment declined', ['cmd.fulfilment.ReleaseStock.v1']) : [],
            'fulfilment.shipment.created.v1' => match ($this->state) {
                SagaState::Shipping => $this->complete(),
                SagaState::Compensating, SagaState::Cancelled => $this->undoLateShipment($ref), // a parcel exists for a cancelled order
                default => [],
            },
            'fulfilment.shipment.failed.v1' => $this->state === SagaState::Shipping
                ? $this->compensate('shipment failed', ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1']) : [],
            'fulfilment.stock.released.v1' => $this->acknowledge('cmd.fulfilment.ReleaseStock.v1'),
            'billing.payment.refunded.v1' => $this->acknowledge('cmd.billing.RefundPayment.v1'),
            'fulfilment.shipment.cancelled.v1' => $this->acknowledge('cmd.fulfilment.CancelShipment.v1'),
            default => [],
        };
    }

    /** A silent neighbour is not an answer: compensate with commands that are safe whatever it did. @return list<Out> */
    public function expire(DateTimeImmutable $now): array
    {
        if ($this->state->isTerminal() || $this->state === SagaState::Compensating || $now < $this->deadline) {
            return [];
        }

        return match ($this->state) {
            SagaState::ReservingStock => $this->compensate('timeout reserving stock', ['cmd.fulfilment.ReleaseStock.v1']),
            // The shipment may or may not exist: cancel it too (tombstone-safe).
            SagaState::Shipping => $this->compensate('timeout in shipping', [
                'cmd.fulfilment.CancelShipment.v1', 'cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1',
            ]),
            default => $this->compensate('timeout in ' . $this->state->value, ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1']),
        };
    }

    /** @param list<Out> $outs @return list<Out> */
    private function advance(SagaState $next, DateTimeImmutable $now, int $stepSeconds, array $outs): array
    {
        $this->state = $next;
        $this->deadline = $now->modify("+{$stepSeconds} seconds");
        $this->version++;

        return $outs;
    }

    /** @param list<string> $commands @return list<Out> */
    private function compensate(string $reason, array $commands): array
    {
        $this->state = SagaState::Compensating;
        $this->reason = $reason;
        $this->version++;
        $outs = [];
        foreach ($commands as $command) {
            $this->outstanding[$command] = true;
            $outs[] = new Out($command, ['order_id' => $this->orderId]);
        }

        return $outs;
    }

    /** @return list<Out> */
    private function acknowledge(string $command): array
    {
        if ($this->state !== SagaState::Compensating) {
            return [];
        }
        unset($this->outstanding[$command]);

        return $this->outstanding === [] ? $this->cancel($this->reason ?? 'cancelled') : [];
    }

    /** @return list<Out> */
    private function cancel(string $reason): array
    {
        $this->state = SagaState::Cancelled;
        $this->reason = $reason;
        $this->version++;

        return [new Out('sales.order.cancelled.v1', ['order_id' => $this->orderId, 'reason' => $reason])];
    }

    /** @return list<Out> */
    private function complete(): array
    {
        $this->state = SagaState::Completed;
        $this->version++;

        return [new Out('sales.order.confirmed.v1', ['order_id' => $this->orderId])];
    }

    /** @param array<string, string> $ref @return list<Out> */
    private function undoLateCharge(array $ref): array
    {
        if (isset($this->outstanding['cmd.billing.RefundPayment.v1'])) {
            return []; // a refund is already on its way
        }
        $this->outstanding['cmd.billing.RefundPayment.v1'] = true;

        return [new Out('cmd.billing.RefundPayment.v1', $ref)];
    }

    /** @param array<string, string> $ref @return list<Out> */
    private function undoLateShipment(array $ref): array
    {
        if (isset($this->outstanding['cmd.fulfilment.CancelShipment.v1'])) {
            return [];
        }
        $this->outstanding['cmd.fulfilment.CancelShipment.v1'] = true;

        return [new Out('cmd.fulfilment.CancelShipment.v1', $ref)];
    }
}

The service stores it, one transaction per message and one per expired saga, with lockForUpdate:

php
<?php

namespace App\Sales\Saga;

use App\Messaging\Inbox;
use App\Messaging\Outbox;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;

/**
 * Persists the saga aggregate. Each handled message is ONE transaction:
 * inbox row + saga state + outgoing commands in the outbox.
 */
final class OrderSagaService
{
    public function __construct(private readonly int $stepSeconds = 30) {}

    /** @param array{id: string, type: string, payload: array<string, mixed>} $message */
    public function handle(array $message, ?DateTimeImmutable $now = null): bool
    {
        $now ??= new DateTimeImmutable();

        return Inbox::once('saga', $message['id'], function () use ($message, $now): void {
            $orderId = $message['payload']['order_id'];

            if ($message['type'] === 'sales.order.placed.v1') {
                if ($this->find($orderId) !== null) {
                    return; // second OrderPlaced for the same order
                }
                [$saga, $outs] = OrderSaga::start($orderId, $message['payload']['lines'], $message['payload']['total_cents'], $now, $this->stepSeconds);
                $this->persist($saga, $outs, $message, insert: true);

                return;
            }

            $saga = $this->find($orderId)
                ?? throw new \RuntimeException("Saga {$orderId} not found yet"); // transient: retry later

            $outs = $saga->handle($message['type'], $now, $this->stepSeconds);
            $this->persist($saga, $outs, $message);
        });
    }

    /** Called by the scheduler: expire sagas whose deadline passed, one saga per transaction. */
    public function tick(?DateTimeImmutable $now = null): int
    {
        $now ??= new DateTimeImmutable();
        $expired = DB::table('order_sagas')
            ->whereNotIn('state', ['completed', 'cancelled', 'compensating'])
            ->where('deadline_at', '<=', $now->format('Y-m-d H:i:s'))
            ->pluck('order_id');

        foreach ($expired as $orderId) {
            DB::transaction(function () use ($orderId, $now): void {
                $row = DB::table('order_sagas')->where('order_id', $orderId)->lockForUpdate()->first();
                $saga = $row ? $this->hydrate($row) : null;
                $outs = $saga?->expire($now) ?? [];
                if ($saga !== null && $outs !== []) {
                    $this->persist($saga, $outs, ['id' => 'timer-' . $orderId, 'correlation' => $orderId]);
                }
            });
        }

        return $expired->count();
    }

    private function find(string $orderId): ?OrderSaga
    {
        $row = DB::table('order_sagas')->where('order_id', $orderId)->lockForUpdate()->first();

        return $row ? $this->hydrate($row) : null;
    }

    private function hydrate(object $row): OrderSaga
    {
        return new OrderSaga(
            $row->order_id, SagaState::from($row->state), json_decode($row->lines, true), (int) $row->total_cents,
            new DateTimeImmutable($row->deadline_at), json_decode($row->outstanding, true), $row->reason, (int) $row->version,
        );
    }

    /** @param list<Out> $outs @param array<string, mixed> $cause */
    private function persist(OrderSaga $saga, array $outs, array $cause, bool $insert = false): void
    {
        $values = [
            'state' => $saga->state->value, 'version' => $saga->version,
            'deadline_at' => $saga->deadline->format('Y-m-d H:i:s'),
            'lines' => json_encode($saga->lines), 'total_cents' => $saga->totalCents,
            'outstanding' => json_encode((object) $saga->outstanding), 'reason' => $saga->reason,
        ];
        $insert
            ? DB::table('order_sagas')->insert(['order_id' => $saga->orderId] + $values)
            : DB::table('order_sagas')->where('order_id', $saga->orderId)->update($values);

        foreach ($outs as $out) {
            Outbox::record($out->type, $saga->orderId, $saga->version, $out->payload, $cause['correlation'] ?? $cause['id'], $cause['id']);
        }
    }
}

The saga's verdict reaches the Order aggregate through its own handler and transaction:

php
<?php

namespace App\Sales;

use App\Messaging\Inbox;
use App\Messaging\MessageHandler;
use App\Messaging\PermanentFailure;
use App\Sales\Domain\Order;
use Illuminate\Support\Facades\DB;

/** Applies the saga's verdict to the Order aggregate: a separate transaction from the saga's own. */
final class OutcomeHandler implements MessageHandler
{
    public function handle(array $message): void
    {
        Inbox::once('sales-order', $message['id'], function () use ($message): void {
            $order = Order::query()->lockForUpdate()->find($message['payload']['order_id'])
                ?? throw new \RuntimeException('Order not found yet'); // transient

            try {
                match ($message['type']) {
                    'sales.order.confirmed.v1' => $order->confirm(),
                    'sales.order.cancelled.v1' => $order->cancel($message['payload']['reason'] ?? 'cancelled'),
                    default => throw new PermanentFailure("Unexpected {$message['type']}"),
                };
            } catch (\DomainException $e) {
                throw new PermanentFailure($e->getMessage(), previous: $e);
            }

            $order->save();
        });
    }
}

The timer is a scheduled command (Schedule::command('saga:tick')->everyMinute()->withoutOverlapping()):

php
<?php

use App\Sales\Saga\OrderSagaService;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;

// The relay runs as a long-lived process under Supervisor: `php artisan outbox:relay`.
// The saga timer runs every minute; withoutOverlapping() keeps ticks from piling up.
Artisan::command('saga:tick', function (OrderSagaService $sagas): void {
    $this->info('expired sagas handled: ' . $sagas->tick());
})->purpose('Compensate sagas whose step deadline passed');

Schedule::command('saga:tick')->everyMinute()->withoutOverlapping();

// Alert inputs (pointer): outbox backlog, parked messages, saga age. See the observability section.
Artisan::command('outbox:backlog', function (): void {
    $this->line((string) \Illuminate\Support\Facades\DB::table('outbox_messages')->whereNull('sent_at')->count());
})->purpose('Number of unsent outbox rows');

Wiring: who consumes what ​

A service provider binds the handler registry, the router (consumers subscribe by type prefix, like the Go broker), and the two adapters you replace in production: the broker publisher and the payment gateway. LogPublisher and FakePaymentProvider are development stand-ins so the relay and the handlers can be tried without infrastructure.

php
<?php

namespace App\Providers;

use App\Billing\ChargeHandler;
use App\Billing\FakePaymentProvider;
use App\Billing\PaymentProvider;
use App\Fulfilment\StockHandler;
use App\Messaging\HandlerRegistry;
use App\Messaging\LogPublisher;
use App\Messaging\MessageRouter;
use App\Messaging\Publisher;
use App\Sales\OutcomeHandler;
use App\Sales\Saga\OrderSagaService;
use App\Sales\Saga\SagaHandler;
use Illuminate\Support\ServiceProvider;

/** Wiring: who consumes what, and which adapters are in use. Register it in bootstrap/providers.php. */
final class MessagingServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(OrderSagaService::class, fn () => new OrderSagaService(stepSeconds: 30));
        $this->app->singleton(PaymentProvider::class, FakePaymentProvider::class); // swap for the real gateway adapter
        $this->app->singleton(Publisher::class, LogPublisher::class);              // swap for the broker adapter

        $this->app->singleton(MessageRouter::class, fn () => new MessageRouter([
            'saga' => ['sales.order.placed', 'fulfilment.', 'billing.'],
            'sales-order' => ['sales.order.confirmed', 'sales.order.cancelled'],
            'fulfilment' => ['cmd.fulfilment.'],
            'billing' => ['cmd.billing.'],
        ]));

        $this->app->singleton(HandlerRegistry::class, fn ($app) => new HandlerRegistry([
            'saga' => $app->make(SagaHandler::class),
            'sales-order' => $app->make(OutcomeHandler::class),
            'fulfilment' => $app->make(StockHandler::class),
            'billing' => $app->make(ChargeHandler::class),
        ]));
    }
}
php
<?php

namespace App\Messaging;

/**
 * The broker transport (a RabbitMQ or Kafka package, or the relay itself in a
 * modular monolith) calls route() for every message it receives. Each consumer
 * subscribes by type prefix, exactly like the Go broker.
 */
final class MessageRouter
{
    /** @param array<string, list<string>> $subscriptions consumer => type prefixes */
    public function __construct(private readonly array $subscriptions) {}

    /** @param array{id: string, type: string, key: string, payload: array<string, mixed>} $message */
    public function route(array $message): void
    {
        foreach ($this->subscriptions as $consumer => $prefixes) {
            foreach ($prefixes as $prefix) {
                if (str_starts_with($message['type'], $prefix)) {
                    ConsumeMessage::dispatch($consumer, $message); // one job per consumer
                    break;
                }
            }
        }
    }
}
php
<?php

namespace App\Sales\Saga;

use App\Messaging\MessageHandler;

/** Adapter: lets the saga service be the handler of the `saga` consumer. */
final class SagaHandler implements MessageHandler
{
    public function __construct(private readonly OrderSagaService $sagas) {}

    public function handle(array $message): void
    {
        $this->sagas->handle($message);
    }
}
php
<?php

namespace App\Messaging;

use Illuminate\Support\Facades\Log;

/**
 * Development stand-in for the broker adapter: writes to the log and hands the
 * message to the router in-process, so the relay can be tried without a broker.
 * Replace it with your RabbitMQ or Kafka publisher in production.
 */
final class LogPublisher implements Publisher
{
    public function __construct(private readonly MessageRouter $router) {}

    public function publish(array $message): void
    {
        Log::info('publish', ['id' => $message['id'], 'type' => $message['type'], 'key' => $message['key']]);
        $this->router->route($message);
    }
}
php
<?php

namespace App\Billing;

/** Development stand-in for the card gateway: approves everything. Replace in production. */
final class FakePaymentProvider implements PaymentProvider
{
    /** @var array<string, bool> */
    private array $seen = [];

    public function charge(string $idempotencyKey, int $amountCents): bool
    {
        $this->seen[$idempotencyKey] = true; // a real provider returns the first result for a repeated key

        return true;
    }

    public function refund(string $idempotencyKey, int $amountCents): void
    {
        $this->seen[$idempotencyKey] = true;
    }
}

The API edge ​

php
<?php

namespace App\Sales\Http;

use App\Sales\Application\PlaceOrder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Idempotent command at the API edge: the client sends an Idempotency-Key and
 * may retry the POST after a timeout without creating a second order.
 * (The full pattern, including key scope and expiry, is in api-idempotency.)
 */
final class PlaceOrderController
{
    public function __invoke(Request $request, PlaceOrder $placeOrder): JsonResponse
    {
        $key = $request->header('Idempotency-Key')
            ?? abort(422, 'Idempotency-Key header is required');
        $data = $request->validate([
            'order_id' => 'required|string', 'customer_id' => 'required|string', 'total_cents' => 'required|integer|min:1',
            'lines' => 'required|array|min:1', 'lines.*.sku' => 'required|string', 'lines.*.qty' => 'required|integer|min:1',
        ]);

        return DB::transaction(function () use ($key, $data, $placeOrder): JsonResponse {
            // The unique key makes "first writer wins" a database fact, not an if-statement.
            $first = DB::table('idempotency_keys')->insertOrIgnore(['key' => $key]) === 1;

            if (! $first) {
                $saved = DB::table('idempotency_keys')->where('key', $key)->lockForUpdate()->first();

                return response()->json(json_decode($saved->response ?? '{"status":"in_progress"}', true), $saved->status ?? 409);
            }

            $order = $placeOrder($data['order_id'], $data['customer_id'], $data['total_cents'], $data['lines']);
            $body = ['order_id' => $order->id, 'status' => $order->status]; // "pending": the saga is still running
            DB::table('idempotency_keys')->where('key', $key)->update(['status' => 202, 'response' => json_encode($body)]);

            return response()->json($body, 202);
        });
    }
}
php
<?php

use App\Sales\Http\PlaceOrderController;
use Illuminate\Support\Facades\Route;

// 202 Accepted: the order exists as "pending"; confirmation arrives asynchronously.
Route::post('/orders', PlaceOrderController::class);
php
<?php

namespace App\Billing;

interface PaymentProvider
{
    /** Idempotent at the provider too: the same key never charges twice. */
    public function charge(string $idempotencyKey, int $amountCents): bool;

    public function refund(string $idempotencyKey, int $amountCents): void;
}

Outgoing HTTP calls get explicit limits (Http::timeout(3)->connectTimeout(1)->retry(...) only for idempotent calls or calls carrying an idempotency key); a circuit breaker around a payment gateway is covered in Error Handling & Fault Tolerance.

Tests ​

php
<?php

namespace Tests\Unit;

use App\Sales\Saga\OrderSaga;
use App\Sales\Saga\SagaState;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;

final class OrderSagaTest extends TestCase
{
    private function started(): OrderSaga
    {
        [$saga] = OrderSaga::start('o-1', [['sku' => 'mug', 'qty' => 2]], 3000, new DateTimeImmutable('2026-11-25 09:00:00'), 30);

        return $saga;
    }

    public function test_duplicate_reply_does_not_advance_twice(): void
    {
        $saga = $this->started();
        $now = new DateTimeImmutable('2026-11-25 09:00:05');

        $first = $saga->handle('fulfilment.stock.reserved.v1', $now, 30);
        $second = $saga->handle('fulfilment.stock.reserved.v1', $now, 30);

        $this->assertCount(1, $first);
        $this->assertSame('cmd.billing.ChargePayment.v1', $first[0]->type);
        $this->assertSame('charge-o-1', $first[0]->payload['idempotency_key']);
        $this->assertSame([], $second);
        $this->assertSame(SagaState::Charging, $saga->state);
    }

    public function test_timeout_in_charging_compensates_with_safe_commands(): void
    {
        $saga = $this->started();
        $saga->handle('fulfilment.stock.reserved.v1', new DateTimeImmutable('2026-11-25 09:00:05'), 30);

        $outs = $saga->expire(new DateTimeImmutable('2026-11-25 09:01:00'));

        $this->assertSame(SagaState::Compensating, $saga->state);
        $this->assertEqualsCanonicalizing(
            ['cmd.billing.RefundPayment.v1', 'cmd.fulfilment.ReleaseStock.v1'],
            array_map(fn ($o) => $o->type, $outs),
        );
    }

    public function test_late_payment_after_timeout_does_not_send_a_second_refund(): void
    {
        $saga = $this->started();
        $saga->handle('fulfilment.stock.reserved.v1', new DateTimeImmutable('2026-11-25 09:00:05'), 30);
        $saga->expire(new DateTimeImmutable('2026-11-25 09:01:00'));

        $outs = $saga->handle('billing.payment.charged.v1', new DateTimeImmutable('2026-11-25 09:02:00'), 30);

        $this->assertSame([], $outs); // a refund is already outstanding
    }

    public function test_cancelled_only_after_every_compensation_is_acknowledged(): void
    {
        $saga = $this->started();
        $now = new DateTimeImmutable('2026-11-25 09:00:05');
        $saga->handle('fulfilment.stock.reserved.v1', $now, 30);
        $saga->handle('billing.payment.charged.v1', $now, 30);
        $saga->handle('fulfilment.shipment.failed.v1', $now, 30);

        $saga->handle('billing.payment.refunded.v1', $now, 30);
        $this->assertSame(SagaState::Compensating, $saga->state);

        $outs = $saga->handle('fulfilment.stock.released.v1', $now, 30);
        $this->assertSame(SagaState::Cancelled, $saga->state);
        $this->assertSame('sales.order.cancelled.v1', $outs[0]->type);
    }

    public function test_shipping_timeout_cancels_the_shipment_and_a_late_create_is_undone_once(): void
    {
        $saga = $this->started();
        $t = new DateTimeImmutable('2026-11-25 09:00:05');
        $saga->handle('fulfilment.stock.reserved.v1', $t, 30);
        $saga->handle('billing.payment.charged.v1', $t, 30); // shipping

        $outs = $saga->expire(new DateTimeImmutable('2026-11-25 09:05:00'));
        $this->assertContains('cmd.fulfilment.CancelShipment.v1', array_map(fn ($o) => $o->type, $outs));

        foreach (['fulfilment.shipment.cancelled.v1', 'billing.payment.refunded.v1', 'fulfilment.stock.released.v1'] as $type) {
            $saga->handle($type, $t, 30);
        }
        $this->assertSame(SagaState::Cancelled, $saga->state);

        $late = $saga->handle('fulfilment.shipment.created.v1', $t, 30);
        $this->assertSame('cmd.fulfilment.CancelShipment.v1', $late[0]->type);
        $this->assertSame([], $saga->handle('fulfilment.shipment.created.v1', $t, 30));
    }
}
php
<?php

namespace Tests\Feature;

use App\Sales\Application\PlaceOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class OutboxAtomicityTest extends TestCase
{
    use RefreshDatabase;

    public function test_order_and_outbox_row_commit_together(): void
    {
        (new PlaceOrder())('o-1', 'c-1', 3000, [['sku' => 'mug', 'qty' => 2]]);

        $this->assertDatabaseHas('orders', ['id' => 'o-1', 'status' => 'pending']);
        $this->assertDatabaseHas('outbox_messages', ['type' => 'sales.order.placed.v1', 'key' => 'o-1', 'sent_at' => null]);
    }

    public function test_a_rolled_back_order_leaves_no_event(): void
    {
        try {
            (new PlaceOrder())('o-2', 'c-1', 3000, []); // domain rule: at least one line
        } catch (\DomainException) {
        }

        $this->assertDatabaseMissing('orders', ['id' => 'o-2']);
        $this->assertDatabaseCount('outbox_messages', 0);
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\Inbox;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class InboxTest extends TestCase
{
    use RefreshDatabase;

    public function test_second_delivery_is_skipped(): void
    {
        $effects = 0;
        $id = '8f4e1c9a-0000-4000-8000-000000000001';

        $this->assertTrue(Inbox::once('billing', $id, function () use (&$effects): void { $effects++; }));
        $this->assertFalse(Inbox::once('billing', $id, function () use (&$effects): void { $effects++; }));
        $this->assertSame(1, $effects);
        $this->assertTrue(Inbox::once('saga', $id, function () use (&$effects): void { $effects++; })); // other consumer: own record
    }

    public function test_a_failing_effect_leaves_no_dedup_row(): void
    {
        $id = '8f4e1c9a-0000-4000-8000-000000000002';

        try {
            Inbox::once('billing', $id, function (): void { throw new \RuntimeException('provider down'); });
        } catch (\RuntimeException) {
        }

        $this->assertDatabaseMissing('inbox_messages', ['message_id' => $id]);
        $this->assertTrue(Inbox::once('billing', $id, fn () => null)); // the redelivery is processed
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\Outbox;
use App\Messaging\Publisher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

final class RelayOutboxTest extends TestCase
{
    use RefreshDatabase;

    public function test_failed_publish_is_retried_and_order_per_key_is_kept(): void
    {
        DB::transaction(function (): void {
            Outbox::record('evt.a', 'o-1', 1, ['n' => 1]);
            Outbox::record('evt.b', 'o-1', 2, ['n' => 2]);
            Outbox::record('evt.c', 'o-2', 1, ['n' => 3]);
        });

        $log = new \ArrayObject();
        $this->app->instance(Publisher::class, new class($log) implements Publisher {
            private int $calls = 0;

            public function __construct(private \ArrayObject $log) {}

            public function publish(array $message): void
            {
                if (++$this->calls === 1) {
                    throw new \RuntimeException('broker timeout'); // first publish of o-1 fails
                }
                $this->log[] = $message['type'];
            }
        });

        $this->artisan('outbox:relay --once')->assertSuccessful();
        // o-1 is blocked (evt.b must not overtake evt.a); o-2 went through
        $this->assertSame(['evt.c'], $log->getArrayCopy());

        $this->artisan('outbox:relay --once')->assertSuccessful();
        $this->assertSame(['evt.c', 'evt.a', 'evt.b'], $log->getArrayCopy());
        $this->assertDatabaseCount('outbox_messages', 3);
        $this->assertSame(0, DB::table('outbox_messages')->whereNull('sent_at')->count());
    }
}
php
<?php

namespace Tests\Feature;

use App\Billing\ChargeHandler;
use App\Billing\PaymentProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

final class BillingIdempotencyTest extends TestCase
{
    use RefreshDatabase;

    private function provider(): PaymentProvider
    {
        return new class implements PaymentProvider {
            public int $charges = 0;

            public function charge(string $idempotencyKey, int $amountCents): bool
            {
                $this->charges++;

                return true;
            }

            public function refund(string $idempotencyKey, int $amountCents): void {}
        };
    }

    private function charge(string $messageId): array
    {
        return ['id' => $messageId, 'type' => 'cmd.billing.ChargePayment.v1', 'key' => 'o-1', 'payload' => [
            'order_id' => 'o-1', 'amount_cents' => 3000, 'idempotency_key' => 'charge-o-1',
        ]];
    }

    public function test_same_message_and_same_business_key_charge_once(): void
    {
        $provider = $this->provider();
        $handler = new ChargeHandler($provider);

        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000a'));
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000a')); // duplicate delivery: the inbox
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000b')); // new message, same key: the payments table

        $this->assertSame(1, $provider->charges);
        $this->assertSame(1, DB::table('payments')->where('order_id', 'o-1')->count());
    }

    public function test_refund_before_charge_leaves_a_tombstone_that_declines_the_late_charge(): void
    {
        $provider = $this->provider();
        $handler = new ChargeHandler($provider);

        $handler->handle(['id' => '8f4e1c9a-0000-4000-8000-00000000000c', 'type' => 'cmd.billing.RefundPayment.v1', 'key' => 'o-1', 'payload' => ['order_id' => 'o-1']]);
        $handler->handle($this->charge('8f4e1c9a-0000-4000-8000-00000000000d'));

        $this->assertSame(0, $provider->charges);
        $this->assertDatabaseHas('outbox_messages', ['type' => 'billing.payment.declined.v1', 'key' => 'o-1']);
    }
}
php
<?php

namespace Tests\Feature;

use App\Messaging\ConsumeMessage;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

final class ParkPoisonTest extends TestCase
{
    use RefreshDatabase;

    public function test_failed_job_is_parked_with_its_reason_not_swallowed(): void
    {
        $job = new ConsumeMessage('fulfilment', [
            'id' => '8f4e1c9a-0000-4000-8000-0000000000aa', 'type' => 'cmd.fulfilment.Bogus.v1', 'key' => 'o-9', 'payload' => ['x' => 1],
        ]);

        $job->failed(new \RuntimeException('Unknown command cmd.fulfilment.Bogus.v1'));

        $this->assertDatabaseHas('parked_messages', ['consumer' => 'fulfilment', 'type' => 'cmd.fulfilment.Bogus.v1']);
    }

    public function test_unique_id_is_consumer_plus_message_id(): void
    {
        $job = new ConsumeMessage('billing', ['id' => '8f4e1c9a-0000-4000-8000-0000000000bb', 'type' => 't', 'key' => 'o-1', 'payload' => []]);
        $this->assertSame('billing:8f4e1c9a-0000-4000-8000-0000000000bb', $job->uniqueId());
    }
}

The Laravel angle ​

  • DB::transaction(fn) is the unit of work; a nested call is a savepoint. lockForUpdate() serialises a saga row (Locks & Concurrency). DB::table(...)->insertOrIgnore() is the portable idempotent insert.
  • A job dispatched inside a transaction can run before the transaction commits unless after_commit is set or afterCommit() is used; even then the job can be lost between commit and push, so the outbox, not the queue, is the source of truth for events.
  • ShouldBeUnique (with #[UniqueFor] and uniqueId()) and WithoutOverlapping are cache-lock based and best effort; they reduce duplicate work but do not replace the inbox.
  • RateLimited (with RateLimiter::for('payments', ...)) caps how fast jobs hit a provider and ThrottlesExceptions(10, 5 * 60) reacts to failures: the first is a speed limit, the second a pause after trouble. ThrottlesExceptions(10, 5 * 60) pauses a job after 10 consecutive exceptions for 5 minutes, which suits an unstable provider; pair it with retryUntil().
  • Events and listeners (Event::dispatch) are in-process and synchronous by default; they are domain events, not reliable messages (Domain Events vs Integration Events).

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Order saved, event never sentTransactional outboxMessage row in the same transaction; relayNo loss, no 2PCRelay, duplicates, pruning
Customer charged twiceInbox + idempotency keysUnique (consumer, message_id); provider key charge-<order>Safe retries everywhereKey storage, retention
Stock held after a failed paymentSaga compensation + timerReleaseStock on decline; deadline per stepNo manual cleanupSaga state, compensation design
Poison message blocks the queueClassify, park, alert, redrivePermanent error type, DLQ with reasonQueue keeps moving, nothing lostSomeone must triage
Billing down at peakPending status + saga + throttled retryAccept order, charge later, deadlineRevenue continuesLate failures, customer messaging
Cancel arrives before placeVersion gap handling, retry laterseq check; transient error "saga not found yet"Order-independent outcomeNeeds a gap policy and a parking limit
Late reply after cancellationUndo againSaga answers a late StockReserved with ReleaseStockNo leaked reservationsCompensations must be idempotent
Outbox backlog growsIndex, batch, partition, or switch to log tailingPartial index on unsent; relay per partitionLower lagMore moving parts
Inbox table growsRetention + partitionsDelete older than the replay windowBounded sizeA replay older than the window duplicates
Retry storm after recoveryFull jitter, retry budget, throttleretry.Policy, ThrottlesExceptionsRecovery is not killed by its own clientsSlower catch-up
Message with an unknown schemaVersioned types, ACL, contract tests...OrderPlaced.v1Safe evolutionSeveral versions in flight
Two relays publish the same rowOne relay (lock) or accept duplicatesCache::lock, advisory lock, leader electionOrder keptSingle point; failover delay

Choosing ​

SituationRecommendationExtra techniqueReason
One step crosses a context (notify, index)Outbox + event, consumer with inboxNatural idempotency if possibleNo saga needed
Two or three steps, same team, stableChoreographyIdempotent consumers, correlation idSimple, no extra component
Four or more steps, compensations, deadlinesOrchestrated saga as an aggregateTimers, outbox for commandsOne place shows the state
Process lasts hours or days, human stepsA durable workflow engineTemporal, Step FunctionsTimers and history built in
Money movesIdempotency key at every hop, saga, reconciliationLedger, daily reportOne failure costs more than all the machinery
Read-mostly data from another contextEvent-fed read modelVersion check, as of timestampNeighbour outage freezes, not breaks
Need an immediate answer from a neighbourSync call with deadline, breaker, degraded modeCache last good value, flaggedAnswer now, honest about age
Broker cannot do transactionsOutbox + inboxPer-key partitioningWorks with any at-least-once broker
High event rate from one databaseLog tailing (Debezium)Outbox table with CDC filterLow latency, no polling load
Ordering critical per aggregatePartition key = aggregate id + version checkSingle consumer per keyOrder plus a safety net
Business says "never show pending"Reconsider boundaries or accept sync couplingReserve capacity synchronouslyA product decision with a cost, not a free wish

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

Monolith: one process, one database ​

Place the order, reserve the stock and charge the card inside one database transaction; failure means rollback. Even so, write the events through an outbox table: it costs one insert, and the day a module is extracted the events are already there. External calls (the card provider) are the first failure to appear: call them after the transaction with an idempotency key, or as an outbox-driven step, never while holding row locks. Example: a Laravel monolith where PlaceOrder commits orders + outbox_messages, and a queue worker sends the confirmation email from the outbox row. See ACID & Transactions.

Modular monolith: separate modules, separate rules ​

One deployable and often one database, but modules (Sales, Fulfilment, Billing) own their tables and expose only an API (Modular Monolith). Rule: no transaction spans two modules. Modules talk through an in-process bus that is backed by the outbox and inbox tables, so that the saga, the idempotent handlers and the status model already work and the extraction later changes only the transport. Example: the order_sagas table in Sales' schema; Fulfilment's StockHandler consuming from the same database table queue; per-module inbox_messages. The danger is the "easy" cross-module transaction: it removes exactly the failure handling you will need.

Microservices: three databases, one broker ​

The running example end to end (the Go demo prints this trace; every message appears twice because the broker duplicates):

text
     Sales (db sales)              Broker              Fulfilment / Billing
1    tx: order o-1 pending + outbox OrderPlaced
2    relay -> OrderPlaced -------> saga queue
3    saga tx: inbox + saga(reserving) + outbox ReserveStock
4    relay -> ReserveStock ------> fulfilment: inbox + reserve + outbox StockReserved
5    saga tx: charging + outbox ChargePayment (key charge-o-1)
6    relay -> ChargePayment -----> billing: inbox + payment + outbox PaymentCharged
7    saga tx: shipping + outbox CreateShipment
8    relay -> CreateShipment ----> fulfilment: shipment + outbox ShipmentCreated
9    saga tx: completed + outbox OrderConfirmed
10   sales-order tx: order confirmed (version 2)

Contract between the contexts: the message types and payloads in contracts (the published language, Context Maps); commands go to one named recipient, events are facts; each type carries a version suffix (.v1) and consumers ignore unknown fields. Failure paths: step 5 with a declined card sends ReleaseStock; step 8 failing sends RefundPayment and ReleaseStock. Team ownership: Sales owns the saga because it owns the customer promise.

Distributed data: replicas, caches, multi-region ​

  • Replicas. The relay and the saga timer read the outbox and saga tables from the primary; a lagging replica hides unsent rows or fresh deadlines (Replication & Failover). Read models served from replicas are stale by design; show as of.
  • Caches. A cache in front of the Order aggregate may show pending after the saga confirmed; set a short TTL or invalidate from the OrderConfirmed event, and never decide a business rule from a cache.
  • Sharded databases. Use the aggregate id as the shard key so an aggregate, its outbox rows and inbox rows stay on one shard; then the local transaction stays local (Sharding).
  • Multi-region. Message ids must be globally unique; the inbox must be in the region that applies the effect; a region failover can replay messages, so retention windows must cover failover. Cross-region sagas need deadlines longer than inter-region latency plus broker lag. Concepts: Consistency Models, Eventual Consistency in Databases, Distributed SQL & 2PC.

Scaling path: 1×, 10×, 100× ​

ScalePublishingConsumingSagasTypical change
1× (hundreds of orders a day)Outbox + one polling relay (200 ms)Inbox in each serviceHand-written saga rowThe Laravel or Go code of this chapter
10× (tens of orders a second)Partial index, batch size tuning, relay per partitionPruning, per-key partitions, parallel consumers with WithoutOverlapping per keyTimer with SKIP LOCKED, saga indexesKafka or RabbitMQ with quorum queues instead of database queues
100× (thousands a second)Log tailing (Debezium) from the outbox table, partitioned outboxPartitioned inbox tables, idempotent writes in batchesWorkflow engine (Temporal, Step Functions), sagas sharded by order idDedicated platform team, schema registry, automated redrive and replay tooling

Lab: break it on purpose ​

The Go part runs offline on one machine (single process, no containers). The Laravel part is written as commands with expected output and was not run.

Setup (run).

bash
cd docs/snippets/ddd/designing-for-failure-reliable-messaging/go
go vet ./... && go test -count=1 -race ./...
# ok  academy/designing-for-failure-reliable-messaging/edge
# ok  academy/designing-for-failure-reliable-messaging/fulfilment
# ok  academy/designing-for-failure-reliable-messaging/inbox
# ok  academy/designing-for-failure-reliable-messaging/retry
# ok  academy/designing-for-failure-reliable-messaging/saga
# ok  academy/designing-for-failure-reliable-messaging/sim

Step 1: watch a duplicated broker do no harm (run).

bash
go run ./cmd/demo
text
== order o-1
  saga        <- sales.order.placed.v1              id=sales-000001   caused-by=
  saga        <- sales.order.placed.v1              id=sales-000001   caused-by=
  fulfilment  <- cmd.fulfilment.ReserveStock.v1     id=sales-000002   caused-by=sales-000001
  fulfilment  <- cmd.fulfilment.ReserveStock.v1     id=sales-000002   caused-by=sales-000001
  ...
  => order=confirmed saga=completed charges=1 stock=3 rounds=9 parked=0
== order o-2
  ...
  => order=cancelled saga=cancelled charges=0 stock=3 rounds=9 parked=0

Every message is delivered twice; charges=1 and stock=3 prove each effect ran once. Order o-2 had its card declined: stock was released and no money was taken.

Step 2: remove the inbox where it matters (run). In sim/world.go, in notify, replace inbox.Once(w.SalesDB, "notify", m, func(tx *store.Tx) error { by w.SalesDB.Tx(func(tx *store.Tx) error { (and drop the unused return value) and run go test -run TestHappyPath ./sim. Expected (this was run):

text
--- FAIL: TestHappyPathSurvivesDuplicatesAndReordering (0.00s)
    world_test.go:53: e-mails sent = 2, want 1: an additive effect needs the inbox

"Send one more e-mail" is not naturally idempotent, so the duplicate delivery sends two. Now remove the inbox from billing, fulfilment and saga instead: the tests still pass, because those handlers are also protected by the business idempotency key, the reservation record and the saga's state checks. That is defence in depth, and the reason to keep the inbox everywhere: you cannot audit every future handler for natural idempotency. Revert.

Step 3: crash the relay (run). TestRelayCrashAfterPublishIsHarmless kills the relay once, after the first publish and before it marks the row. Make the hook return true every time (delete the if crashed { return false } lines) and run it. Expected (this was run):

text
--- FAIL: TestRelayCrashAfterPublishIsHarmless (0.00s)
    world_test.go:144: order o-6: got {... Status:pending ...}, want status confirmed

A relay that always crashes before marking can never advance past its first row: the order stays pending. The alert for this in production is oldest unsent outbox age. Revert.

Step 4: Billing down, then back (run). TestBillingDownTimeoutThenLateReplies shows: order stays pending; after 31 s of fake time saga.Tick moves the saga to compensating; when Billing returns it executes the queued charge and then the refund; the saga ends cancelled, stock back to 5, no second refund (the late PaymentCharged is ignored because a refund is outstanding).

Step 5: poison (run). TestPoisonMessageIsParkedNotSwallowed publishes an unknown command and a bad payload. Expected: DLQ.Depth() == 2, each with Attempts == 1 (permanent errors are not retried), and the legitimate order o-10 still confirms.

Step 6: Laravel (expected, not run).

bash
php artisan migrate
php artisan test --filter='InboxTest|OutboxAtomicityTest|RelayOutboxTest|BillingIdempotencyTest|OrderSagaTest|ParkPoisonTest'
# PASS  Tests\Unit\OrderSagaTest
# PASS  Tests\Feature\InboxTest
# PASS  Tests\Feature\OutboxAtomicityTest
# PASS  Tests\Feature\RelayOutboxTest
# PASS  Tests\Feature\BillingIdempotencyTest
# PASS  Tests\Feature\ParkPoisonTest
php artisan outbox:relay --once      # publishes unsent rows, exits
php artisan saga:tick                # expired sagas handled: 0
php artisan queue:work --queue=default

Step 7: tune. Change StepTimeout to 5 * time.Second in sim.NewWorld and rerun TestBillingDown... with a 6-second advance. Discuss: what is the cost of a too-short timeout? (Cancelling orders whose charge would have succeeded; the late PaymentCharged then needs a refund.)

Common misconceptions ​

BeliefReality
The broker's exactly-once removes the need for idempotent consumersIt holds inside the broker's boundary; your database write is outside it
Retries make a system more reliableRetries multiply load during an outage; they need backoff, jitter, limits and a budget
A saga is a distributed rollbackA saga runs compensating business actions; they are visible and may be imperfect
Choreography is always simplerIt is simple for two or three steps and opaque beyond that
Timestamps order eventsClocks skew; use the aggregate version or a sequence
afterCommit dispatch is an outboxThe job can be lost between commit and push; the outbox row is durable
Commit then publish is almost atomicA crash between the lines loses the event
ShouldBeUnique makes handlers idempotentIt deduplicates queue entries by a cache lock; processing can still repeat
A DLQ is where messages go to dieIt is a work queue for humans; alert on depth and redrive
A fallback keeps us safeAn untested fallback is a second system that fails during the outage
The UI can hide eventual consistencyPending and failed states are product states the user sees
Two-phase commit is fine inside one companyIt couples availability and locks across services and needs support from every participant

Cheat sheet ​

TopicRemember
Failure modelDown, slow, garbage, duplicate, out of order, lost, partial, clock skew
Unit of workOne aggregate + one outbox row (or inbox row + effect) per local transaction
DeliveryAssume at-least-once; exactly-once is a boundary-local property
OutboxSame transaction; relay publishes then marks; duplicates possible
RelayOne relay per outbox for order; polling is simple, log tailing is fast
InboxUnique (consumer, message_id) in the effect's transaction
Dedup keyProducer-assigned message id, never the broker offset
OrderingPartition by aggregate id; check versions; make handlers commutative
RetriesCapped exponential backoff with full jitter; limit and budget
PoisonPermanent error means park with reason, alert on depth, redrive after the fix
SagaLocal transactions + compensations + deadlines; state is an aggregate
CompensationA domain command; idempotent; commutative with its forward step (tombstones)
Late repliesUndo them again; never move backwards from a terminal state
ProductPending and failed are real states with words, timers and actions
Degraded modeDesigned, flagged, exercised; never invent data
API edgeIdempotency-Key stored with the result; 202 with pending status
TestingInject duplicates, reordering, loss, crashes and a dead neighbour; assert the business outcome
ObservabilityCorrelation and causation ids; outbox age, lag, DLQ depth, saga age

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 — List the eight failures a context must assume and give one defence for each. Important ​

Answer

Answer: Neighbour down (timeout, async messaging), slow (deadline, breaker), garbage (validation, ACL, DLQ), duplicate (inbox, idempotency key), out of order (per-key partition, versions), lost (outbox, deadlines, reconciliation), partial failure (saga with compensations), clock skew (versions instead of timestamps). See the taxonomy.

2 — Why can a crash between COMMIT and broker.Publish not be fixed with a try/catch? Must-know ​

Answer

Answer: After the crash the process is gone; nothing is left to catch. The event exists only in memory. The outbox moves the promise into the same transaction as the state, so a restarted relay can still find it. See Reliable publishing.

3 — The relay published a message and crashed before marking it sent. What happens, and who handles it? Must-know ​

Answer

Answer: On restart the relay publishes the same message id again. The consumer's inbox hits the unique key and skips the second copy. The relay may duplicate; it must never lose. See Reliable consuming.

4 — Why must the inbox row and the business effect share one transaction? Must-know ​

Answer

Answer: Otherwise a crash between them leaves either an effect without a record (a duplicate runs it again) or a record without an effect (the message is skipped forever). One transaction makes "recorded" and "done" the same fact.

5 — Why is the broker offset a bad dedup key? Important ​

Answer

Answer: It changes on redelivery, replay and republish, so a duplicate of the same business message looks new. Use an id assigned by the producer when the outbox row is created.

6 — What is the difference between a compensation and a rollback, and why must compensations be commutative with their forward steps? Good to know ​

Answer

Answer: A rollback erases an uncommitted change; a compensation is a new committed action that semantically undoes an earlier committed one. Because messages can be reordered, the compensation can arrive before the forward step; a tombstone makes the late forward step a no-op so both orders end in the same state.

7 — Billing does not answer. What does the saga do, and what happens if Billing answers after the cancel? Important ​

Answer

Answer: At the deadline the saga moves to Compensating and sends safe, idempotent commands (release stock, refund). A late PaymentCharged finds the saga in Compensating or Cancelled; it does not advance, and it triggers a refund only if none is outstanding. See Sagas.

8 — When is choreography enough, and when do you orchestrate? Must-know ​

Answer

Answer: Choreography fits two or three steps, a stable flow and one team. With four or more steps, branches, compensations, deadlines or several teams, an orchestrator gives one place for state and timers.

9 — A poison message arrives. Name three wrong reactions and the right one. Must-know ​

Answer

Answer: Wrong: retry forever (blocks the queue), catch-log-ack (the event vanishes), crash the consumer repeatedly. Right: classify it as permanent, park it with the reason and attempts, alert on DLQ depth, fix, redrive. See Retries.

10 — Why is "Sales returns an error while Billing is down" a product decision? Important ​

Answer

Answer: The technical option exists (accept as pending, charge later), but it changes what the customer sees and what failures cost later (late cancellations). Only the business can weigh lost orders against late failures. See Eventual consistency as a product decision.

11 — Where do timeouts and circuit breakers live in a DDD context? Must-know ​

Answer

Answer: In the application layer and the infrastructure adapters at the context edge, never in the domain model. The saga's own deadlines are domain state because they express a business promise. See The context edge.

Glossary ​

TermMeaning
Design for failureTreating the failure of any service call as a normal case (Fowler and Lewis)
Failure taxonomyThe list of neighbour behaviours the design must tolerate
Consistency islandAn aggregate (and its database) inside which invariants hold at every commit
Unit of workOne aggregate plus one outbox or inbox row in one local transaction
Helland entityA uniquely keyed set of data living on one machine; the scope of serializability
ActivityPer-partner state an entity keeps, including the ids of processed messages
At-most-onceSend once, no retry; loss possible
At-least-onceRetry until acknowledged; duplicates possible
Effectively-onceAt-least-once delivery plus an idempotent effect
Two generals problemImpossibility of certainty over an unreliable link without further assumptions; why a missing ack is ambiguous
Transactional outboxA message row written in the aggregate's transaction and published later
RelayThe process that moves outbox rows to the broker
Polling publisherA relay that queries the outbox table periodically
Transaction log tailingA relay that reads the database log (CDC, Debezium)
InboxA table of processed message ids with a unique key, written with the effect
Idempotent consumerA consumer whose repeated processing of one message has no extra effect
Idempotency keyA client- or caller-supplied unique key that makes a command safe to retry
Dedup keyThe identifier used to recognise a duplicate
Natural idempotencyAn effect that is a set operation, not an increment
Commutative handlerA handler whose final state does not depend on message order
TombstoneA record that marks something as already undone or cancelled so a late arrival is refused
Version / seqThe aggregate's version carried in the message to order and detect gaps
GapA missing version between the stored one and the incoming one
Poison messageA message that can never be processed successfully
DLQ / parking lotA queue or table for messages set aside with a reason
RedriveRe-publishing parked messages after the fix
BackoffIncreasing wait between retries
Full jitterA random wait in zero to the current backoff ceiling
Retry budgetA cap on the number of retries per time window across a process
Deadline propagationOne absolute deadline shared by the whole call tree
Circuit breakerA guard that fails fast after repeated failures of a dependency
BulkheadIsolating resources per dependency so one cannot starve the rest
SagaA coordinated sequence of local transactions with compensations
ChoreographySaga coordination by events between services
OrchestrationSaga coordination by a central object that sends commands
Process managerThe older DDD name for a stateful orchestrator
Compensating transactionA business action that semantically undoes an earlier committed step
Late replyA response that arrives after the saga gave up on that step
Status modelThe customer-visible states of an aggregate during an asynchronous process
Degraded modeA designed reduction of function during a dependency failure
Read modelA local, event-fed, eventually consistent copy of another context's data
Correlation idAn id shared by all messages of one business flow
Causation idThe id of the message that directly caused this one
Consumer lagHow far a consumer is behind the head of its queue
Consumer contract testA test that a producer's message still satisfies a consumer's expectations
Failure injectionMaking the test environment duplicate, delay, drop or crash on purpose
Dual writeWriting to the database and the broker as two independent steps
Two-phase commit (2PC)An atomic commit protocol across participants with locks held while waiting
ShouldBeUniqueLaravel interface that prevents the same job being queued twice by a cache lock
ThrottlesExceptionsLaravel job middleware that pauses a job after consecutive exceptions
failed_jobsLaravel table for jobs that exhausted their attempts

References ​

Built by Morteza Negahi