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 for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why a context must assume failure | Why it exists |
| Sagas 1987, Helland 2007, Nygard, Fowler, SRE, AWS | Where it comes from |
| The eight failures to assume | The failure taxonomy |
| Entities, activities, messages, "exactly-once is a lie" | Helland's model |
| Aggregate as island, one transaction per aggregate | Consistency islands |
| Outbox, polling vs log tailing, per-aggregate order | Reliable publishing |
| Inbox, dedup keys, versions, commutative handlers | Reliable consuming |
| Partition keys, version checks, gaps | Ordering |
| Backoff, jitter, poison messages, DLQ, parking | Retries and poison messages |
| Choreography vs orchestration, compensations, timeouts | Sagas |
| Saga state as an aggregate | The saga as an aggregate |
| Pending/failed states in the product | Eventual consistency as a product decision |
| Stale reads, flags, accepting orders when Billing is down | Degraded modes |
| Timeouts, budgets, breakers at the edge | The context edge |
Idempotency-Key on commands | Idempotent commands at the API edge |
| Failure injection, replay, contract tests | Testing |
| Correlation, causation, lag, DLQ depth | Observability |
| What not to do | Anti-patterns |
| Full code | Go, Laravel |
| Concrete problems and fixes | Solving the classic problems |
| Which technique for which situation | Choosing |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The eight failures a context must assume (each is a block in the taxonomy):
| Failure | In plain words | What it breaks if ignored | Main defence |
|---|---|---|---|
| Neighbour down | Nobody answers | The caller hangs or crashes | Timeout, async messaging, degraded mode |
| Neighbour slow | Answers after the caller gave up | Threads pile up, cascade | Deadline, budget, breaker, bulkhead |
| Garbage | A reply that violates the contract or the meaning | Corrupted local state | Validation, ACL, contract tests, DLQ |
| Duplicate | The same message twice | Double charge, double reservation | Inbox, idempotency key, natural idempotency |
| Out of order | Message 2 before message 1 | Old state overwrites new | Per-key ordering, versions, commutative handlers |
| Lost | Sent and never arrived | Order stuck forever | Outbox, at-least-once, deadlines, reconciliation |
| Partial failure | Step 2 of 4 done, step 3 failed | Money taken, nothing dispatched | Saga with compensations |
| Clock skew | Two machines disagree about "now" | Wrong ordering and deadlines | Versions and sequences, deadlines on one clock |
The reliable-messaging toolbox:
| Building block | Lives where | Gives you | Cost |
|---|---|---|---|
| Aggregate + version | Inside a context | Immediate consistency of one island | Small aggregates, retries on conflict |
| Transactional outbox | Producer's database | "State changed" and "event will be sent" are one fact | A relay and a table to prune |
| Relay (polling or log tailing) | Producer side | At-least-once publication | Duplicates, lag, one more process |
| Inbox / processed-ids table | Consumer's database | Effectively-once processing | One row per message, retention policy |
| Idempotency key | API edge and provider calls | Safe client retries | A key store |
| Saga | Between contexts | Business-level atomicity by compensation | State, timers, compensations to design |
| DLQ / parking lot | Consumer side | Poison messages stop blocking | Someone must read it |
| Deadlines and timers | Saga and edge | No waiting forever | Timeout choices, late replies |
Delivery guarantees in one table (details in Delivery Guarantees):
| Guarantee | What can go wrong | Who must cope | Typical use |
|---|---|---|---|
| At-most-once | Message lost | The business, by reconciliation | Metrics, best-effort notifications |
| At-least-once | Message duplicated | The consumer, by idempotency | Nearly all business messaging |
| "Exactly-once" | A slogan: at-least-once plus dedup, inside one system's boundary | Whoever claims it, at its boundary | Kafka transactions between Kafka topics; your database is outside |
Saga outcomes of the running example:
| Event | Saga reaction | Compensation |
|---|---|---|
StockRejected | Cancel at once | None: nothing was done |
PaymentDeclined | Compensate | Release stock |
ShipmentFailed | Compensate | Refund payment, release stock |
| Timeout at any step | Compensate with commands that are safe whatever the neighbour did | Release stock, refund (idempotent, tombstones) |
| Late reply after cancel | Undo it again | Release 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 services | Local transactions + messages + compensation |
|---|---|
| Looks like the monolith | Looks different; the business sees "pending" |
| Locks held across the network | Locks 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 all | Each step proceeds or times out on its own |
| Availability of the whole is the product of the parts | Each context stays available for its own work |
| Failure of the coordinator can leave locks in doubt | Failure 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.
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
- "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).
- "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).
- "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.
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 fallbackDates 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.
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"| Failure | How it shows up | Real scenario | Product-level symptom | Defence | Where in this page |
|---|---|---|---|---|---|
| Neighbour down | Connection refused, no consumer on the queue | Billing deploy, database failover | Checkout error or "pending" | Async messaging, deadline, degraded mode | Degraded |
| Neighbour slow | p99 latency grows, then timeouts | Card issuer at 8 s | Thread pool exhaustion, cascade | Per-call timeout, deadline propagation, breaker | Edge |
| Garbage | Schema violation, impossible values, unknown type | Producer ships qty: -1 | Corrupt stock | Validate at the edge, ACL, contract test, DLQ | Retries |
| Duplicate | Same message_id twice | Relay crash after publish, broker redelivery after consumer crash | Charged twice | Inbox, idempotency key | Consuming |
| Out of order | OrderCancelled before OrderPlaced | Two partitions, retries, parallel consumers | Cancelled order shows as confirmed | Per-key partition, versions, tombstones | Ordering |
| Lost | Never arrives | Dual write, crash after commit, acks=0, auto-ack then crash | Order stuck pending | Outbox, deadlines, reconciliation job | Publishing |
| Partial failure | Some steps done, one failed | Stock reserved, card declined | Stock held forever | Saga with compensations and timers | Sagas |
| Clock skew | created_at of B earlier than A though B was caused by A | Two hosts, NTP drift | Wrong "latest wins", premature timeouts | Versions and sequence numbers; deadlines read on the owner's clock | Ordering, Sagas |
What provides the defence, by product:
| Product | Duplicate source | Order guarantee | Loss risk |
|---|---|---|---|
| RabbitMQ | Redelivery after consumer crash or nack with requeue; publisher retry without confirms dedup | Per queue, broken by requeue and multiple consumers | Auto-ack + crash; unconfirmed publish; non-durable queue |
| Apache Kafka | Producer retry without idempotence; consumer reprocess after rebalance | Per partition | acks=0/1 with leader loss; offset committed before processing |
| Redis Streams | Reclaim of pending entries (XAUTOCLAIM) after consumer crash | Per stream | Persistence setting (AOF fsync policy), XACK before work |
| Amazon SQS | Standard queue is at-least-once; FIFO has a dedup window | Standard: best effort; FIFO per message group | Visibility timeout shorter than work, then delete |
| Laravel database/Redis queue | Job retried after timeout or worker crash (retry_after) | None across workers | tries 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).
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 effectAt-most-once, at-least-once, "exactly-once":
| Claim | What it really means | Cost | Where it is true |
|---|---|---|---|
| At-most-once | Send once, never retry; a lost message is gone | Silent loss | Fire-and-forget logging, metrics |
| At-least-once | Retry until acknowledged; duplicates possible | Consumer must dedup | Most brokers by default |
| Exactly-once delivery | Impossible to guarantee over an unreliable link when the sender cannot tell "lost" from "processed, ack lost" (the two generals problem) | n/a | Nowhere on a real network |
| Effectively-once processing | At-least-once delivery plus an idempotent effect | An inbox or natural idempotency | Your context, by design |
| Kafka exactly-once semantics | Atomic read-process-write between Kafka topics inside Kafka transactions | Producer ids, transactional commits | Inside 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).
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 scope | Mechanism | Guarantee | Example |
|---|---|---|---|
| Inside one aggregate | Local transaction, version column | Invariants at every commit | Order total equals the sum of its lines |
| Aggregate and its outgoing message | Outbox in the same transaction | "State changed" iff "message will be sent" | OrderPlaced |
| Message and its effect in the consumer | Inbox in the same transaction | "Processed" iff "effect applied" | Stock reserved once |
| Across aggregates in one context | Message or saga, sometimes one tx by exception | Eventual | Order status follows saga outcome |
| Across contexts | Saga + compensation | Eventual, with deadlines | Order, 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".
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()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:
| Style | How | Order | Latency | Costs and risks | Products |
|---|---|---|---|---|---|
| Polling publisher | SELECT ... WHERE sent_at IS NULL ORDER BY id LIMIT n on a timer | Per table order if one relay; ties to id gaps under concurrent transactions | Poll interval | Load on the database; "Tricky to publish events in order"; works with any SQL database | Any SQL database; Laravel command or Go loop; Watermill's SQL publisher and Forwarder (documented as "the outbox pattern") |
| Transaction log tailing | Read the database's WAL/binlog and publish rows inserted in the outbox table | Log order | Milliseconds | "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:
| Platform | Outbox support |
|---|---|
| PostgreSQL / MySQL | Plain table in the same transaction; log tailing via logical replication or binlog |
| MongoDB | Multi-document transactions on a replica set, or change streams on the outbox collection |
| DynamoDB | Transactional writes plus DynamoDB Streams |
| Laravel | DB::transaction + a table + a command; afterCommit on dispatch is NOT an outbox (the job can be lost between commit and push) |
| Go | database/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:
| Technique | How | Good for | Limit |
|---|---|---|---|
| Inbox table (processed ids) | INSERT inbox (consumer, message_id) unique; skip on conflict; same tx as the effect | Any handler, any effect in your own database | One row per message; needs retention |
| Natural idempotency | The effect is a set, not an increment: status = confirmed, upsert by business key | State-setting handlers | Not for "add 1" |
| Versioned state | Apply only if message.version > stored.version; ignore older | Read models, replicated copies | Needs a per-key version in the message |
| Idempotency key at a provider | Send your own key with the call (card gateway) | Effects outside your database | Provider must support it |
| Commutative handler | Order of arrival does not change the final state (tombstones) | Compensations, reordering | Needs design per handler |
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 COMMITDedup key choice:
| Key | Stable across redelivery? | Use |
|---|---|---|
| Broker offset / delivery tag | No (changes on redelivery or replay) | Never as a dedup key |
| Message id assigned by the producer at outbox insert | Yes | The default |
Business key (order_id + step) | Yes | When the message may be re-created by a retried command |
| Aggregate id + version | Yes | For event streams of one aggregate |
| Payload hash | Yes, but collides when two real messages are identical | Last 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:
| Platform | How |
|---|---|
| PostgreSQL | INSERT ... ON CONFLICT DO NOTHING, check rows affected |
| MySQL / InnoDB | INSERT IGNORE or catch error 1062 |
| MongoDB | Unique index plus insertOne, catch E11000 |
| Redis | SET key NX EX ttl is a cheap pre-filter; it is not atomic with a database effect, so it is not the correctness mechanism |
| Laravel | DB::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.
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 technique | Rule | Use when |
|---|---|---|
| Drop stale | if msg.version <= stored.version: ignore | Latest state wins (read models) |
| Detect gap | if msg.version > stored.version + 1: retry later | Every event matters (ledgers) |
| Commutative effect | The final state is the same in any order | Compensations: release-before-reserve leaves a tombstone |
| Re-fetch | On gap, query the owner's API for the current state | Snapshots acceptable |
| Single writer per key | Route by key so one consumer handles it | Throughput 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 class | Example | Retry? | Action |
|---|---|---|---|
| Transient technical | Timeout, 503, deadlock (SQLSTATE 40P01), serialization failure (40001) | Yes, with backoff and jitter | Release back to the queue |
| Dependency down | Card gateway unavailable for minutes | Yes, but slow down for everyone | Throttle exceptions or open a breaker; retry window |
| Permanent technical | Undecodable payload, unknown message type, schema violation | No | Park immediately with the reason |
| Business "no" | Out of stock, card declined | No, it is an answer | Reply with a rejection message; the saga handles it |
| Ordering gap | Version 5 arrived, 4 missing | Yes, later | Release with a longer delay, then park |
| Bug in the handler | TypeError for every message | No (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".
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 reasonPoison 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.
| Product | Retry primitive | Poison destination | Redrive |
|---|---|---|---|
| RabbitMQ | Nack with requeue, or TTL retry queues via dead-letter exchange; quorum queues delivery-limit | Dead-letter exchange (x-dead-letter-exchange) | Shovel or manual republish |
| Apache Kafka | Retry topics (orders.retry.5s) or in-process; no per-message nack | Dead-letter topic | Replay from the dead-letter topic |
| Redis Streams | Pending entries list, XAUTOCLAIM after idle time; count deliveries via XPENDING | Move to a dead stream after N deliveries | XADD back |
| Amazon SQS | Visibility timeout and maxReceiveCount | Redrive policy to a dead-letter queue | "Start DLQ redrive" |
| Laravel queue | #[Tries], #[Backoff], #[MaxExceptions], release(), retryUntil() | failed_jobs table (make:queue-failed-table), failed() method | queue:retry |
| Go (Watermill) | Router middleware; docs list "Requeuing After Error" | A poison queue publisher | Re-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."
| Aspect | Choreography | Orchestration |
|---|---|---|
| Who knows the whole flow | Nobody; it emerges from event subscriptions | The orchestrator (a saga/process manager) |
| Coupling | Services subscribe to each other's events (cyclic dependencies appear) | Participants know commands and replies; the orchestrator knows participants |
| Visibility | Hard: the flow is spread over many services | Easy: one place shows state per order |
| Timeouts and deadlines | Each service must implement its own | One timer per saga |
| Compensation ordering | Implicit | Explicit |
| Testing | Needs the whole system | The saga is a pure state machine |
| Fits | Two or three steps, stable flow, same team | Four 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.
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 step | Compensation | If compensation arrives first | If forward step arrives late |
|---|---|---|---|
ReserveStock | ReleaseStock | Leave a tombstone released | Refuse: StockRejected("already released") |
ChargePayment | RefundPayment | Leave a tombstone cancelled | Decline: PaymentDeclined("order already cancelled") |
CreateShipment | CancelShipment (before pickup) or a return process | Tombstone | Refuse |
SendConfirmationEmail | None possible | n/a | Send 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.
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 OrderCancelledWhat provides orchestration:
| Platform | Support |
|---|---|
| Hand-written saga aggregate | Full control; what this chapter builds in Go and Laravel |
| Temporal, Cadence, Zeebe/Camunda, AWS Step Functions | Durable workflow engines: timers, retries and history are built in (Durable Workflows & Jobs) |
| Laravel | Bus::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.
| Field | Meaning | Why it exists |
|---|---|---|
order_id | Identity (same as the order's) | One saga per order; duplicates of OrderPlaced are ignored |
state | reserving_stock, charging, shipping, completed, compensating, cancelled | The explicit state machine |
deadline | When the current step times out | Timers query by it (indexed) |
outstanding | Compensations sent and not yet acknowledged | "Cancelled" only when empty |
reason | Why compensation started | Shown to support and the customer |
version | Incremented on every change | Used 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 state | What the customer sees | Allowed actions | Notification |
|---|---|---|---|---|
pending | reserving, charging, shipping | "We received your order and are checking stock and payment" | View, cancel request | Email "order received" |
confirmed | completed | "Your order is confirmed" | View, return later | Email "confirmed" |
cancelled (reason: out of stock) | cancelled | "Sorry, an item is no longer available" | Reorder | Email with reason |
cancelled (reason: payment declined) | cancelled | "Your payment was declined" | Retry with another card | Email with link |
cancelled (reason: timeout) | cancelled | "We could not complete your order in time; you were not charged" | Reorder | Email; 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 down | Degraded mode | Honest? | Cost / risk |
|---|---|---|---|
| Billing (charge) | Sales accepts the order as pending; the saga charges when Billing is back; the order times out after N minutes | Yes: status says pending | Orders for customers with bad cards fail later |
| Catalog (price) | Use the price snapshot already stored in Sales' own read model, flagged as of 09:02 | Yes if flagged | Price may be stale; business sets a maximum age |
| Catalog (images, reviews) | Feature flag hides the section | Yes | None for the core flow |
| Identity (login) | Existing sessions and tokens keep working; new logins fail | Yes | Cannot onboard |
| Fulfilment (stock) | Backorder mode: accept, promise later date | Needs a business rule | Oversell risk accepted explicitly |
| Broker down | The outbox keeps growing; the relay catches up on return | Yes (no loss) | Outbox backlog alarm, disk |
| Payment provider slow | Breaker open: fail fast, show "try again", keep cart | Yes | Lost 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).
| Mechanism | Where it lives | Protects | Pointer |
|---|---|---|---|
| Per-call timeout and deadline | HTTP/gRPC client adapter, context in Go, Http::timeout() in Laravel | Threads and connections | Timeouts, Retries & Jitter |
| Circuit breaker | Adapter around a dependency | The caller from a failing callee | Circuit Breaker |
| Bulkhead | Separate worker pools or queues per dependency | One dependency from starving others | Bulkheads |
| Rate limit / load shedding | Ingress of the context | The context from overload | Load Shedding |
| Saga deadline | Saga aggregate | The business process | Sagas |
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).
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| Layer | Mechanism | Scope |
|---|---|---|
| Client to Sales | Idempotency-Key header | One user action |
| Sales to broker | Outbox message_id | One event |
| Broker to Fulfilment/Billing | Inbox (consumer, message_id) | One delivery |
| Billing to card provider | Provider 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.
| Test | Injects | Asserts | In this chapter |
|---|---|---|---|
| Duplicates and reordering | Every message twice, newest first | One charge, stock reserved once, order confirmed | TestHappyPathSurvivesDuplicatesAndReordering |
| Compensation | Card declined | Stock released, order cancelled, no money taken | TestPaymentDeclinedCompensatesStock |
| Late replies | Billing down, timeout, Billing returns | Order cancelled, stock back, no second refund | TestBillingDownTimeoutThenLateReplies |
| Relay crash | Crash after publish, before marking | Outbox drained, one charge | TestRelayCrashAfterPublishIsHarmless |
| Lost publishes | First 3 publishes fail | Order still confirmed | TestLostPublishesAreRetriedByTheRelay |
| Stuck shipment | CreateShipment held past the deadline | Order cancelled, the late create refused by the tombstone, no parcel | TestShippingStallsThenLateCreateIsRefused |
| Poison | Bogus type, bad JSON | Parked with 1 attempt, queue not blocked | TestPoisonMessageIsParkedNotSwallowed |
| Atomicity | Invalid order | No order row and no outbox row | TestPlaceOrderIsAtomicWithItsOutboxRow |
| Replay | Re-deliver the whole history | Same final state | Re-run Pump with Duplicate; with a real inbox, a replay older than retention is the exception |
| Contract | Schema of OrderPlaced.v1 | Consumers still decode it | Context Maps |
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:
| Signal | Meaning | Alert when |
|---|---|---|
| Outbox backlog (unsent rows) and oldest unsent age | The relay is behind or stuck | Age above the accepted inconsistency window |
| Consumer lag (queue depth, Kafka consumer lag) | The consumer cannot keep up | Growing for N minutes |
| DLQ / parked depth | Poison messages exist | Any, then page |
Saga age by state (charging older than 2× step timeout) | Timers or neighbours broken | Count above zero |
| Compensations per hour | Business failure rate | Spike |
| Inbox duplicate rate | Redelivery frequency | Sudden jump (broker or relay trouble) |
| Retry rate and backoff time | Dependency health | Sustained |
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-pattern | Why it fails | Instead |
|---|---|---|
| Two-phase commit across services | Locks across the network; a dead coordinator leaves in-doubt transactions; many brokers and providers do not support it | Local transactions + outbox + saga |
| Dual write (commit, then publish) | A crash between the two loses the event; the opposite order publishes rolled-back facts | Outbox |
| Synchronous chains (A calls B calls C calls D) | Availability multiplies down; latency adds; one slow service cascades | Async messages, or one call with a deadline and a degraded mode |
| Retrying non-idempotent operations | Double charge after a lost response | Idempotency key, inbox |
| Silent fallbacks | A made-up value hides the failure and corrupts data | Explicit degraded mode with a flag, or fail loudly |
| Swallowing poison messages (catch, log, ack) | Business events vanish | Park with reason, alert, redrive |
| Infinite immediate retries | Retry storm; blocks the queue | Capped backoff with jitter, attempt limit |
| Ordering by timestamp | Clock skew | Aggregate version, sequence |
| Saga state in memory or Redis only | Lost on restart | Durable aggregate row |
| Compensation without idempotency or tombstones | Double refund; late forward step undoes the cancel | Idempotent, commutative compensations |
| "Exactly-once" as the only defence | It stops at the boundary of one system | Inbox at every consumer |
| Sharing the database to avoid messaging | One schema, no failure isolation, hidden coupling | Database per service |
Event as a remote procedure call (DoReserveStock published as an event, then waiting for the reply) | Coupling and hidden synchrony | Commands 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).
-- 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:
-- 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
| Product | Setting | Effect on this chapter |
|---|---|---|
| RabbitMQ | Publisher confirms | The relay marks a row sent only after the broker confirms; without confirms a message can be lost after "publish" returns |
| RabbitMQ | Manual consumer ack, prefetch_count | Ack after the inbox transaction commits; auto-ack loses messages on crash |
| RabbitMQ | Durable queues, persistent messages, quorum queues | Survive broker restart |
| Apache Kafka | acks=all, enable.idempotence=true, min.insync.replicas | No loss on leader change; producer retries do not duplicate within a session |
| Apache Kafka | enable.auto.commit=false, commit after the handler's transaction | At-least-once; a crash re-delivers |
| Apache Kafka | Partition key = aggregate id | Per-aggregate order |
| Redis Streams | XACK after the transaction; XAUTOCLAIM min-idle-time | Crashed consumers' entries are re-delivered |
| Amazon SQS | Visibility timeout greater than the handler's worst case | Otherwise a second copy is delivered while the first is running |
| Laravel queue | retry_after in config/queue.php larger than the job timeout | Otherwise a second worker picks up a running job |
| Laravel queue | after_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 |
| PostgreSQL | synchronous_commit, replica lag | Outbox rows read from a lagging replica are stale: read the relay's batch from the primary |
Error codes and what to do
| Code | Meaning | Handler action |
|---|---|---|
PostgreSQL 23505 unique_violation | Inbox or idempotency key already exists | Duplicate: skip, acknowledge |
| MySQL error 1062 | Duplicate entry | Same |
| MongoDB E11000 | Duplicate key | Same |
PostgreSQL 40001 serialization_failure | Concurrent transaction conflict | Retry the whole transaction |
PostgreSQL 40P01 deadlock_detected / MySQL 1213 | Deadlock victim | Retry with jitter (Deadlocks) |
| Optimistic version mismatch (0 rows updated) | Another writer changed the aggregate | Reload and retry, or park if stale |
HTTP 409 Conflict | Request with the same idempotency key still running | Client waits and retries |
| HTTP 422 | Validation failed | Permanent; do not retry |
| HTTP 429 / 503 / 504 | Overload, down, gateway timeout | Retry with backoff, honour Retry-After |
AMQP 406 PRECONDITION_FAILED | Channel closed (for example ack of an unknown delivery tag after a redelivery) | Reopen, continue; the inbox makes redelivery safe |
Kafka NotLeaderForPartition, RebalanceInProgress | Leader moved or group rebalancing | Client 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).
// 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):
// 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.
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.
// 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:
// 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
// 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:
// 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:
// 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
// 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)
}// 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.
// 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.
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.
// 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
// 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
// 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":
// 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:
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:
// 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.ExecContextfor the aggregate and outbox inserts; check the unique violation of the inbox with the driver's error type (pgx:*pgconn.PgErrorwith code23505). Alwaysdefer tx.Rollback()and commit explicitly.context: carry the deadline from the request to every outgoing call (context.WithTimeout); a handler that ignoresctx.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
CrashAfterPublishtest).
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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_commitis set orafterCommit()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]anduniqueId()) andWithoutOverlappingare cache-lock based and best effort; they reduce duplicate work but do not replace the inbox.RateLimited(withRateLimiter::for('payments', ...)) caps how fast jobs hit a provider andThrottlesExceptions(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 withretryUntil().- 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Order saved, event never sent | Transactional outbox | Message row in the same transaction; relay | No loss, no 2PC | Relay, duplicates, pruning |
| Customer charged twice | Inbox + idempotency keys | Unique (consumer, message_id); provider key charge-<order> | Safe retries everywhere | Key storage, retention |
| Stock held after a failed payment | Saga compensation + timer | ReleaseStock on decline; deadline per step | No manual cleanup | Saga state, compensation design |
| Poison message blocks the queue | Classify, park, alert, redrive | Permanent error type, DLQ with reason | Queue keeps moving, nothing lost | Someone must triage |
| Billing down at peak | Pending status + saga + throttled retry | Accept order, charge later, deadline | Revenue continues | Late failures, customer messaging |
| Cancel arrives before place | Version gap handling, retry later | seq check; transient error "saga not found yet" | Order-independent outcome | Needs a gap policy and a parking limit |
| Late reply after cancellation | Undo again | Saga answers a late StockReserved with ReleaseStock | No leaked reservations | Compensations must be idempotent |
| Outbox backlog grows | Index, batch, partition, or switch to log tailing | Partial index on unsent; relay per partition | Lower lag | More moving parts |
| Inbox table grows | Retention + partitions | Delete older than the replay window | Bounded size | A replay older than the window duplicates |
| Retry storm after recovery | Full jitter, retry budget, throttle | retry.Policy, ThrottlesExceptions | Recovery is not killed by its own clients | Slower catch-up |
| Message with an unknown schema | Versioned types, ACL, contract tests | ...OrderPlaced.v1 | Safe evolution | Several versions in flight |
| Two relays publish the same row | One relay (lock) or accept duplicates | Cache::lock, advisory lock, leader election | Order kept | Single point; failover delay |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One step crosses a context (notify, index) | Outbox + event, consumer with inbox | Natural idempotency if possible | No saga needed |
| Two or three steps, same team, stable | Choreography | Idempotent consumers, correlation id | Simple, no extra component |
| Four or more steps, compensations, deadlines | Orchestrated saga as an aggregate | Timers, outbox for commands | One place shows the state |
| Process lasts hours or days, human steps | A durable workflow engine | Temporal, Step Functions | Timers and history built in |
| Money moves | Idempotency key at every hop, saga, reconciliation | Ledger, daily report | One failure costs more than all the machinery |
| Read-mostly data from another context | Event-fed read model | Version check, as of timestamp | Neighbour outage freezes, not breaks |
| Need an immediate answer from a neighbour | Sync call with deadline, breaker, degraded mode | Cache last good value, flagged | Answer now, honest about age |
| Broker cannot do transactions | Outbox + inbox | Per-key partitioning | Works with any at-least-once broker |
| High event rate from one database | Log tailing (Debezium) | Outbox table with CDC filter | Low latency, no polling load |
| Ordering critical per aggregate | Partition key = aggregate id + version check | Single consumer per key | Order plus a safety net |
| Business says "never show pending" | Reconsider boundaries or accept sync coupling | Reserve capacity synchronously | A 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):
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
pendingafter the saga confirmed; set a short TTL or invalidate from theOrderConfirmedevent, 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×
| Scale | Publishing | Consuming | Sagas | Typical change |
|---|---|---|---|---|
| 1× (hundreds of orders a day) | Outbox + one polling relay (200 ms) | Inbox in each service | Hand-written saga row | The Laravel or Go code of this chapter |
| 10× (tens of orders a second) | Partial index, batch size tuning, relay per partition | Pruning, per-key partitions, parallel consumers with WithoutOverlapping per key | Timer with SKIP LOCKED, saga indexes | Kafka or RabbitMQ with quorum queues instead of database queues |
| 100× (thousands a second) | Log tailing (Debezium) from the outbox table, partitioned outbox | Partitioned inbox tables, idempotent writes in batches | Workflow engine (Temporal, Step Functions), sagas sharded by order id | Dedicated 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).
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/simStep 1: watch a duplicated broker do no harm (run).
go run ./cmd/demo== 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=0Every 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):
--- 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):
--- FAIL: TestRelayCrashAfterPublishIsHarmless (0.00s)
world_test.go:144: order o-6: got {... Status:pending ...}, want status confirmedA 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).
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=defaultStep 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
| Belief | Reality |
|---|---|
| The broker's exactly-once removes the need for idempotent consumers | It holds inside the broker's boundary; your database write is outside it |
| Retries make a system more reliable | Retries multiply load during an outage; they need backoff, jitter, limits and a budget |
| A saga is a distributed rollback | A saga runs compensating business actions; they are visible and may be imperfect |
| Choreography is always simpler | It is simple for two or three steps and opaque beyond that |
| Timestamps order events | Clocks skew; use the aggregate version or a sequence |
afterCommit dispatch is an outbox | The job can be lost between commit and push; the outbox row is durable |
| Commit then publish is almost atomic | A crash between the lines loses the event |
ShouldBeUnique makes handlers idempotent | It deduplicates queue entries by a cache lock; processing can still repeat |
| A DLQ is where messages go to die | It is a work queue for humans; alert on depth and redrive |
| A fallback keeps us safe | An untested fallback is a second system that fails during the outage |
| The UI can hide eventual consistency | Pending and failed states are product states the user sees |
| Two-phase commit is fine inside one company | It couples availability and locks across services and needs support from every participant |
Cheat sheet
| Topic | Remember |
|---|---|
| Failure model | Down, slow, garbage, duplicate, out of order, lost, partial, clock skew |
| Unit of work | One aggregate + one outbox row (or inbox row + effect) per local transaction |
| Delivery | Assume at-least-once; exactly-once is a boundary-local property |
| Outbox | Same transaction; relay publishes then marks; duplicates possible |
| Relay | One relay per outbox for order; polling is simple, log tailing is fast |
| Inbox | Unique (consumer, message_id) in the effect's transaction |
| Dedup key | Producer-assigned message id, never the broker offset |
| Ordering | Partition by aggregate id; check versions; make handlers commutative |
| Retries | Capped exponential backoff with full jitter; limit and budget |
| Poison | Permanent error means park with reason, alert on depth, redrive after the fix |
| Saga | Local transactions + compensations + deadlines; state is an aggregate |
| Compensation | A domain command; idempotent; commutative with its forward step (tombstones) |
| Late replies | Undo them again; never move backwards from a terminal state |
| Product | Pending and failed are real states with words, timers and actions |
| Degraded mode | Designed, flagged, exercised; never invent data |
| API edge | Idempotency-Key stored with the result; 202 with pending status |
| Testing | Inject duplicates, reordering, loss, crashes and a dead neighbour; assert the business outcome |
| Observability | Correlation and causation ids; outbox age, lag, DLQ depth, saga age |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Design for failure | Treating the failure of any service call as a normal case (Fowler and Lewis) |
| Failure taxonomy | The list of neighbour behaviours the design must tolerate |
| Consistency island | An aggregate (and its database) inside which invariants hold at every commit |
| Unit of work | One aggregate plus one outbox or inbox row in one local transaction |
| Helland entity | A uniquely keyed set of data living on one machine; the scope of serializability |
| Activity | Per-partner state an entity keeps, including the ids of processed messages |
| At-most-once | Send once, no retry; loss possible |
| At-least-once | Retry until acknowledged; duplicates possible |
| Effectively-once | At-least-once delivery plus an idempotent effect |
| Two generals problem | Impossibility of certainty over an unreliable link without further assumptions; why a missing ack is ambiguous |
| Transactional outbox | A message row written in the aggregate's transaction and published later |
| Relay | The process that moves outbox rows to the broker |
| Polling publisher | A relay that queries the outbox table periodically |
| Transaction log tailing | A relay that reads the database log (CDC, Debezium) |
| Inbox | A table of processed message ids with a unique key, written with the effect |
| Idempotent consumer | A consumer whose repeated processing of one message has no extra effect |
| Idempotency key | A client- or caller-supplied unique key that makes a command safe to retry |
| Dedup key | The identifier used to recognise a duplicate |
| Natural idempotency | An effect that is a set operation, not an increment |
| Commutative handler | A handler whose final state does not depend on message order |
| Tombstone | A record that marks something as already undone or cancelled so a late arrival is refused |
Version / seq | The aggregate's version carried in the message to order and detect gaps |
| Gap | A missing version between the stored one and the incoming one |
| Poison message | A message that can never be processed successfully |
| DLQ / parking lot | A queue or table for messages set aside with a reason |
| Redrive | Re-publishing parked messages after the fix |
| Backoff | Increasing wait between retries |
| Full jitter | A random wait in zero to the current backoff ceiling |
| Retry budget | A cap on the number of retries per time window across a process |
| Deadline propagation | One absolute deadline shared by the whole call tree |
| Circuit breaker | A guard that fails fast after repeated failures of a dependency |
| Bulkhead | Isolating resources per dependency so one cannot starve the rest |
| Saga | A coordinated sequence of local transactions with compensations |
| Choreography | Saga coordination by events between services |
| Orchestration | Saga coordination by a central object that sends commands |
| Process manager | The older DDD name for a stateful orchestrator |
| Compensating transaction | A business action that semantically undoes an earlier committed step |
| Late reply | A response that arrives after the saga gave up on that step |
| Status model | The customer-visible states of an aggregate during an asynchronous process |
| Degraded mode | A designed reduction of function during a dependency failure |
| Read model | A local, event-fed, eventually consistent copy of another context's data |
| Correlation id | An id shared by all messages of one business flow |
| Causation id | The id of the message that directly caused this one |
| Consumer lag | How far a consumer is behind the head of its queue |
| Consumer contract test | A test that a producer's message still satisfies a consumer's expectations |
| Failure injection | Making the test environment duplicate, delay, drop or crash on purpose |
| Dual write | Writing 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 |
ShouldBeUnique | Laravel interface that prevents the same job being queued twice by a cache lock |
ThrottlesExceptions | Laravel job middleware that pauses a job after consecutive exceptions |
failed_jobs | Laravel table for jobs that exhausted their attempts |
References
- Martin Fowler and James Lewis, Microservices, 25 March 2014: "Design for failure", decentralized data management and compensating operations. Saved:
sources/designing-for-failure-reliable-messaging/fowler-microservices.txt. - Martin Fowler, CircuitBreaker, 6 March 2014 (as printed on the page): the trip behaviour and the credit to Nygard's Release It!. Saved:
fowler-cb.txt. - Pat Helland, Life beyond Distributed Transactions: an Apostate's Opinion, CIDR 2007: entities, "Atomic Transactions Cannot Span Entities", at-least-once messaging, activities, idempotence. Saved:
helland-cidr.txt. - Chris Richardson, microservices.io: Saga, Transactional outbox, Idempotent Consumer, Polling publisher, Transaction log tailing. Saved:
msio-*.txt. - AWS Builders' Library, Timeouts, retries, and backoff with jitter and Avoiding fallback in distributed systems, both 5 December 2019. Saved:
aws-retries.txt,aws-fallback.txt. - Google SRE book, Addressing Cascading Failures: positive feedback, retries, deadline propagation, retry budget. Saved:
sre-cascading.txt. - Laravel 13, Queues:
ShouldBeUnique,UniqueFor,Tries,Backoff,MaxExceptions,Timeout,WithoutOverlapping,ThrottlesExceptions,RateLimited,dontRetry,failed(),queue:failed,queue:retry,queue:prune-failed, batches. Saved:laravel-queues.txt(rendered page, truncated) andlaravel-queues-13x.md(raw source of the 13.x docs, complete; used to confirmfailed(?Throwable $exception),queue:failedandqueue:prune-failed). - Eric Evans, Domain-Driven Design Reference (2015), the sentence "Within an aggregate boundary, apply consistency rules synchronously. Across boundaries, handle updates asynchronously." Saved:
evans-ddd-reference.normalized.txt(copied from the sibling chapter's sources). - Watermill documentation, watermill.io/docs: Forwarder (the outbox pattern), SQL Pub/Sub, router middleware, requeuing after error (index page only). Saved:
watermill.txt. - Martin Kleppmann, Designing Data-Intensive Applications (site read; chapters 11 and 12 on stream processing and the future of data systems were not fetched, so no claim here is quoted from them).
- Not read: Garcia-Molina and Salem, Sagas (SIGMOD 1987; the open PDF has no text layer); Helland, Idempotence Is Not a Medical Condition (ACM Queue 2012; blocked for automated clients); Nygard, Release It! and Newman, Building Microservices (books; no public excerpt read). Statements attributed to them rest on the secondary sources above and are labelled.
- Siblings: Aggregates & Factories, Domain Events vs Integration Events, Context Maps & Integration Patterns, Data Patterns, API Realization, Service Communication, Data Ownership, Error Handling & Fault Tolerance, Data Persistence in Design, Outbox, Saga, DLQ, Idempotent Consumers.