Transactional Outbox Pattern
“The Message relay might publish a message more than once.” — Chris Richardson, Transactional Outbox, microservices.io
Summary: An outbox commits the business change and the intent to publish in one database transaction, then lets a separate relay deliver that intent. Focus: The dual-write failure, transactional records, polling and CDC relays, leases, per-aggregate ordering, broker acceptance, duplicates, Laravel transaction boundaries and operational recovery. Learning goal: Build and operate a relay whose failure windows are explicit, explain what its acknowledgment proves, and recover without inventing exactly-once delivery.
This chapter owns the database-to-broker handoff. Delivery guarantees explains the delivery vocabulary; the inbox pattern owns consumer deduplication; CDC owns log capture internals; sagas owns coordination across business steps. An outbox is useful inside each of those designs, but it does not implement their whole workflow.
Page map
| If you are looking for | Go to |
|---|---|
| Guarantees and failure windows in one glance | Everything in one minute |
| Why publishing before or after COMMIT both fail | Why it exists |
| The transaction boundary and the record | Atomic commit, Outbox record |
| Polling with locks or leases | Polling, Lease ownership |
| What “ordered” really requires | Ordering |
| Debezium EventRouter and INSERT-only tables | CDC relay |
| Duplicate publication and stable identities | At-least-once |
| Cleanup, poison rows and replay | Retention |
| Exact settings and failure handling | Mechanics, Solutions |
| The complete implementations | Go, Laravel, Broker differences |
| Choosing a relay and scaling it | Choosing, Architecture |
| Fault experiments and quick recall | Lab, Cheat sheet, Self-check |
Everything in one minute
| Promise | What provides it | What does not provide it |
|---|---|---|
| No committed order without a recorded event intent | Order and outbox INSERT use the same local transaction | Two independent commits, even on the same server |
| No event for a rolled-back order | Relay reads only committed outbox rows | Publishing while the order transaction is open |
| Event can survive application exit | Database commit persists the outbox record | An in-memory callback after commit |
| Delivery can resume after relay exit | Pending rows or CDC offsets are durable | A process-local queue |
| Repeated sends do not repeat the consumer effect | Stable event ID plus transactional consumer dedup | Publisher confirms alone |
| Per-aggregate business order | Serialized aggregate updates, an ordering key and disciplined relay/recovery | A global identity column alone |
| Progress during temporary broker failure | Pending storage, retries, capacity and an eventual recovery path | An unconditional guarantee while dependencies remain unavailable |
| Crash happens | Database state | Broker state | Recovery |
|---|---|---|---|
| Before producer COMMIT | Both changes roll back | No publication | Client may retry the business command safely with its own idempotency key |
| After COMMIT, before relay claim | Business row and pending intent exist | No publication | Relay finds pending row |
| After claim, before send | Row is leased or locked | No publication | Lease expires or transaction lock releases |
| After send, before acknowledgment | Pending intent exists | Unknown | Retry with the same event ID |
| After acknowledgment, before marking | Pending intent exists | Message accepted | Retry produces a possible duplicate |
| After successful marking | Published marker exists | Message accepted at configured durability boundary | Consumer processing is a separate responsibility |
| Relay | Reads | Writes back | Main cost |
|---|---|---|---|
| Polling publisher with long transaction | Pending rows under row locks | Published marker in the same relay transaction | Database connection and locks held through broker I/O |
| Polling publisher with lease | Pending rows in a short claim transaction | Ownership-checked marker after publication | Lease expiry, stale publishers and duplicate recovery |
| Transaction log tailing with CDC | Committed database log | Connector offsets; no application published marker needed | Connector, replication slot, WAL and offset operations |
Why it exists
An order service has two facts to establish: “order 42 exists” and “the shipping service can learn that order 42 exists.” A PostgreSQL transaction controls the first database. It cannot commit an unrelated RabbitMQ publish, Kafka produce or Redis XADD as part of that local transaction.
Publish first and the database might roll back after a consumer already ships the order. Commit first and the process might exit before publishing. Moving the publish into an afterCommit callback fixes the early-publication problem, but leaves the second crash window. Retrying an HTTP request does not reliably repair it: the request might never return, the caller might not retry, and a fresh retry can create a second order.
The outbox changes the second fact into a database fact: “there is a durable instruction to announce order 42.” Both facts can now commit together. A relay accepts responsibility for turning the instruction into broker traffic. This moves the availability dependency from the request path into a backlog; it does not make the dependency disappear.
Everyday picture: a shop records a sale and prints its delivery slip in the same bound ledger. A courier later picks up slips. If the courier loses the receipt saying a slip was collected, the shop may send the slip again. The delivery team checks the sale number before shipping twice. The ledger is the producer transaction; the courier is the relay; the delivery team's check is the consumer inbox.
| Direct publish from the request | Transactional outbox |
|---|---|
| Fewer moving parts | A table/log path and a relay to operate |
| Broker failure may fail the request | Requests can commit until the pending-storage budget is exhausted |
| Database and publication can disagree | Business state and publication intent agree |
| Low publication latency when healthy | Polling interval or CDC lag adds latency |
| An uncertain send needs recovery anyway | Recovery has a durable starting point |
Three misunderstandings to discard: an outbox is not a distributed transaction; published_at does not mean consumed; and an outbox table does not automatically provide business ordering.
Where it comes from
Richardson's pattern catalogue describes Transactional Outbox together with Polling Publisher and Transaction Log Tailing. The pattern separates the sender's local commit from the relay's delivery attempt. Relational implementations use a table; a document-oriented implementation can store pending events alongside an aggregate when the database can atomically update that unit. The atomic unit must be stated, not assumed from the word “NoSQL.”
Debezium's Outbox Event Router supplies a concrete CDC implementation: committed outbox INSERTs become keyed Kafka records with event identity in headers. Laravel supplies transaction and queue primitives, but an after_commit option is a scheduling boundary rather than a substitute for the durable outbox row. The implementations below combine these documented primitives; their lease policy and operational limits are teaching design choices, not framework guarantees.
The concepts, one by one
Atomic business state and publication intent Must-know
In plain words: write the order and its delivery slip together. Either both exist or neither exists.
Common misunderstanding: “Two writes are atomic because both use DB::transaction somewhere.” They must use the same database connection and the same transaction. A transaction on the aggregate's named connection does not include an outbox insert on the default connection.
Definition: the producer transaction commits both the aggregate change and an immutable event payload. Publication happens only after that transaction is visible to the relay. The outbox establishes a durable obligation, subject to the database's configured durability and recovery guarantees.
1 producer begins transaction on connection A
2 producer inserts/updates order on A
3 producer inserts outbox event on A using that transaction
4 producer commits A: both become visible together
5 relay reads committed event and publishes it
6 consumer receives the event later; this is outside transaction AReal scenarios: checkout records an order and requests fulfilment; billing records an invoice and notifies accounting; an account service changes permissions and emits a cache-invalidation event. In each case the event describes committed producer state, not proof that every downstream service has already changed.
| Destination | Producer-side rule | Destination-side consequence |
|---|---|---|
| RabbitMQ | Do not publish from inside the business transaction | Relay later waits for confirms and checks routing |
| Kafka | A Kafka transaction cannot include the PostgreSQL commit | Relay or CDC bridges the two systems |
| Redis Streams | MULTI/EXEC cannot include an external SQL transaction | SQL outbox remains the durable handoff source |
Fix: pass pgx.Tx to the Go writer; in Laravel insert through the aggregate's connection and reject calls outside an open transaction. Include the complete event payload in that transaction, rather than fetching a mutable order again during relay publication.
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status)
VALUES ('order-42', 'customer-7', 4200, 'placed');
INSERT INTO outbox (event_id, aggregate_type, aggregate_id, type, payload)
VALUES ('3f2c2e36-569a-4db5-9820-cbfe4b2b7994', 'order', 'order-42',
'OrderPlaced', '{"order_id":"order-42","total_cents":4200}');
COMMIT;
-- Never make a broker call between BEGIN and COMMIT in the producer path.The outbox record is a contract Must-know
In plain words: save enough information to deliver the same event tomorrow even if the order has changed again.
Common misunderstanding: “Saving order_id is enough; the relay can build the event later.” That can publish today's order state as yesterday's event, leak newly added fields, or fail after the order is deleted.
Definition: an outbox record contains an event identity, an ordering/routing identity, a type and a payload captured at the business transition. Polling metadata describes delivery attempts and must not replace event identity.
1 order-42 moves placed -> paid, event E1 captures that transition
2 order-42 moves paid -> cancelled, event E2 captures the next transition
3 delayed relay reads E1's saved payload, not the current cancelled order
4 relay sends E1 and E2 with different event IDs and the same aggregate keyReal scenarios: audit-sensitive status changes need the prior transition; deletion events must survive deletion of the source row; replay must not silently adopt a newer serializer.
| Field | Purpose | Trap |
|---|---|---|
id | Local scan/claim identifier | Not a global business sequence or commit timestamp |
event_id | Stable identity across relay retries | Generating it on every send defeats deduplication |
aggregate_type, aggregate_id | Routing and ordering scope | An ID without its type may collide across domains |
type | Event contract name | A PHP class name couples readers to deployment internals |
payload | Committed event content | Rebuilding from live tables changes history |
headers | Trace context and schema metadata | Do not let arbitrary headers override event identity |
created_at | Event recording time | Wall-clock time is not a total order |
available_at, attempts, last_error | Polling retry eligibility and diagnostics | Logging raw sensitive payloads in errors |
locked_by, locked_until | Temporary claim owner and expiry | Lease ownership does not fence the broker |
published_at | Relay's accepted-publication marker | Neither processing acknowledgment nor an audit event store |
Fix: keep business payload immutable, keep a stable event_id, and define envelope evolution in message design. A command's HTTP idempotency key and the event ID solve different duplicate problems; one request can legitimately create several events.
Polling publisher with a long transaction Important
In plain words: a worker locks a few delivery slips, sends them, marks them and commits.
Common misunderstanding: “SKIP LOCKED returns all pending work in the right order.” PostgreSQL skips rows another transaction locked. That helps work distribution, but makes the view deliberately incomplete. Another relay can see a later row first.
Definition: a polling publisher selects pending records, typically using FOR UPDATE SKIP LOCKED, and performs publication before committing the relay transaction. A process crash releases the locks and rolls back markers, so accepted messages can be sent again.
1 relay A BEGIN; locks E1 and E2 with SKIP LOCKED
2 relay B scans; skips A's locked rows and may select E3
3 A sends E1; broker confirms
4 A crashes before marking/COMMIT
5 PostgreSQL rolls A back; E1 is pending although broker already has it
6 another relay sends E1 again with its original event IDReal scenarios: modest workloads benefit from a simple lock-based relay; a broker stall can make this design expensive when database connections are scarce.
| Broker call inside relay transaction | What to await | What a long wait holds |
|---|---|---|
| RabbitMQ | Routing result and publisher confirm | SQL connection, row locks and an open transaction |
| Kafka | Produce result for every record | The same SQL resources through retries |
| Redis Streams | Successful command results | SQL resources even though Redis has a separate transaction |
Fix: limit batches and broker timeouts; never interpret a long relay transaction as a distributed commit. The following is the SQL sequence, with the broker operation deliberately identified between the queries:
BEGIN;
SELECT id, event_id, payload FROM outbox
WHERE published_at IS NULL AND available_at <= now()
ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED;
-- Application publishes selected rows and checks every broker result here.
-- If any result is uncertain: ROLLBACK, retain the original event IDs.
UPDATE outbox SET published_at = now() WHERE id = ANY(:accepted_ids);
COMMIT;Short claims, leases and ownership Must-know
In plain words: reserve the slips briefly in the database, then release database locks while the courier travels.
Common misunderstanding: “When the lease expires, the old worker stops.” A lease is a database rule. A paused process or an in-flight broker write can continue after expiry; only a resource that enforces a fencing token can reject stale work.
Definition: a short transaction assigns locked_by and locked_until; publication runs outside that transaction; marking or release checks the owner. An expired claim is eligible for recovery. The owner token is unique to a process incarnation or invocation, not a reusable hostname and PID.
1 A claims E1 until database time 12:00:30 and commits the claim
2 A publishes outside a SQL transaction, then pauses
3 lease expires; B claims E1 using a different owner token
4 B publishes E1 and marks it with WHERE locked_by = B
5 A resumes; its owner-checked mark affects zero rows
6 A's late broker send is still possible: consumers must handle itReal scenarios: a busy database should not lend connections to slow broker I/O; deployments need a bound on draining an in-flight batch; a stalled relay needs automatic recovery without manual unlocking.
| Concern | Lease design response | Remaining limitation |
|---|---|---|
| Clock skew between relays | Compute claim and expiry from the database clock | Broker deadlines and application shutdown use other clocks |
| Relay restart | Fresh random owner token | Reusing a token can authorize a stale marker |
| Partial batch publication | Release or let lease expire, then resend stable IDs | Already accepted records can be duplicated |
| Graceful shutdown | Stop claims, allow bounded batch completion and bounded cleanup | Process kill can interrupt any stage |
| Mark affects fewer rows than claimed | Record lease-loss warning and investigate | Increasing the lease alone is not broker fencing |
Fix: the Go PgStore uses one UPDATE ... RETURNING claim. The relay sorts the returned records because UPDATE RETURNING does not promise row order. Laravel uses a short transaction around selection and claim update. Size the lease for the batch's worst permitted publication time, including confirmation and database marking; use smaller batches when that time is hard to bound.
Per-aggregate ordering across the handoff Must-know
In plain words: if an order is paid before it is cancelled, its first logical publication must preserve that relationship.
Common misunderstanding: “An auto-increment ID or UUIDv7 is commit order.” A transaction can allocate an earlier ID and commit later. A scan cannot see its uncommitted row, and a timestamp does not repair that visibility problem.
Definition: ordering is a contract over an aggregate's committed transitions and the destination's ordering scope. It requires producer serialization or versioning, relay coordination and a recovery policy. It is not the numerical sort order of arbitrary rows from all services.
1 transaction A allocates outbox id 100, remains uncommitted
2 transaction B allocates id 101 and commits
3 relay sees 101; a watermark becomes 101
4 A commits id 100 later
5 WHERE id > 101 misses A forever: use pending-state scans, not that watermarkReal scenarios: account balance transitions require an aggregate version; order state machines reject impossible transitions; independent customer aggregates can publish concurrently without a global order.
| Layer | Required decision | Limit |
|---|---|---|
| Producer | Lock the aggregate row or use optimistic version checks in the same transaction | Identity allocation before that discipline proves nothing |
| Pending-row relay | StrictOrder blocks a committed row while an older committed row for that aggregate is pending | Invisible transactions and stale broker sends remain outside the guard |
| RabbitMQ | Consistent routing into an ordering scope; account for multiple publishers and redelivery | A queue does not reconstruct business versions |
| Kafka | Same aggregate key within the same topic and partitioning scheme | Different topics/partitions and producer sessions have no shared total order |
| Redis Streams | Same stream key, with controlled publication order | Concurrent relays determine the actual XADD arrival order |
| Consumer | Stable event dedup; version/gap policy when applying transitions | A duplicate from an old relay can arrive after a newer event |
Fix: serialize updates to each aggregate before recording events; use pending-state scans; decide whether a poison row blocks that aggregate; preserve an aggregate version in the event contract. The sample StrictOrder guard is a conservative pending-row gate, not a complete global ordering service. Full broker ordering mechanics belong in ordering and partitioning.
Transaction log tailing and Debezium Important
In plain words: watch the database's committed log instead of asking repeatedly which slips remain unsent.
Common misunderstanding: “CDC makes publication exactly once and gives me a free audit history.” Connectors can replay records after failure, snapshots can reintroduce rows, and offsets/log retention need operations. A short-lived outbox is not an event store.
Definition: a CDC connector captures committed outbox changes; the Debezium Outbox Event Router single-message transformation maps each event to a Kafka key, payload, topic and headers. It runs in the connector runtime, not inside the Kafka broker.
1 application commits order + outbox INSERT to PostgreSQL
2 PostgreSQL WAL exposes the committed change to the replication slot
3 Debezium reads the change; EventRouter maps its envelope
4 Kafka receives keyed event; connector advances its durable offset
5 restart before durable offset advancement may reproduce the event
6 consumer dedup still uses the original event_idReal scenarios: an organisation already operates Debezium; polling imposes excessive database scans; the desired handoff is from one database log to Kafka with a consistent event contract.
| Router option | Default | Mapping for this chapter |
|---|---|---|
table.field.event.id | id | event_id, emitted in the id header |
table.field.event.key | aggregateid | aggregate_id, the Kafka record key |
route.by.field | aggregatetype | aggregate_type |
route.topic.replacement | outbox.event.${routedByValue} | One topic per aggregate type |
table.field.event.payload | payload | Saved JSON payload |
table.field.event.timestamp | Debezium event timestamp | created_at if event recording time is wanted |
table.fields.additional.placement | None | type:header:type |
table.op.invalid.behavior | warn | fatal makes accidental UPDATEs explicit |
Fix: choose either the polling lifecycle or the CDC lifecycle for a given outbox. EventRouter expects INSERTs, filters DELETEs and treats UPDATEs as invalid; a polling relay's published_at updates must not run alongside that router. The fragment below is merged with a properly configured PostgreSQL connector, credentials and converters. Its predicate applies the router only to outbox records, not heartbeat or other connector messages.
{
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"plugin.name": "pgoutput",
"topic.prefix": "orders",
"slot.name": "orders_outbox",
"publication.name": "orders_outbox_pub",
"publication.autocreate.mode": "filtered",
"table.include.list": "public.outbox",
"transforms": "outbox",
"transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
"transforms.outbox.predicate": "isOutbox",
"predicates": "isOutbox",
"predicates.isOutbox.type": "org.apache.kafka.connect.transforms.predicates.TopicNameMatches",
"predicates.isOutbox.pattern": "orders\\.public\\.outbox",
"transforms.outbox.table.field.event.id": "event_id",
"transforms.outbox.table.field.event.key": "aggregate_id",
"transforms.outbox.route.by.field": "aggregate_type",
"transforms.outbox.route.topic.replacement": "outbox.event.${routedByValue}",
"transforms.outbox.table.field.event.payload": "payload",
"transforms.outbox.table.field.event.timestamp": "created_at",
"transforms.outbox.table.fields.additional.placement": "type:header:type",
"transforms.outbox.table.op.invalid.behavior": "fatal"
}For CDC cleanup, use the connector's durable progress and a recovery horizon; created_at < now() - interval '1 day' alone does not prove capture. Monitor replication-slot retained WAL and connector lag. When a slot or source log is lost, a resnapshot/reconciliation plan is required; detailed connector configuration belongs in CDC.
At-least-once publication and consumer deduplication Must-know
In plain words: sending twice is a normal recovery outcome; applying the business effect twice must not be.
Common misunderstanding: “The broker confirmed once, so the database can know it happened exactly once.” There is a crash window between the broker's acknowledgment and the database marker. Neither participant can infer the other's final state after every network failure.
Definition: the relay retries a committed intent until it reaches the configured acceptance boundary and records that outcome. Under recoverable failures this is at-least-once publication. Stable event IDs let consumers recognise repeats; consumer effect and inbox record must commit together.
1 relay publishes event E7
2 broker accepts E7, returns acknowledgment
3 relay exits before UPDATE published_at
4 recovery publishes E7 again with the same event_id
5 consumer transaction inserts inbox(E7) + applies effect
6 second E7 conflicts with inbox identity and skips the repeated effectReal scenarios: confirmation is lost in a network interruption; the database fails during marking; a CDC connector restarts from an older offset; an operator deliberately replays a published range.
| Broker feature | Helps with | Does not cover |
|---|---|---|
| RabbitMQ publisher confirms | Broker responsibility for the publish | Consumer completion or SQL marker atomicity |
| Kafka idempotent producer | Producer protocol retries in its producer identity/sequence scope | A fresh application-level replay of the same event |
Redis 8.6+ IDMP | Duplicate append within retained producer/idempotency history | Unbounded retention, every failover scenario, consumer effects |
Fix: never regenerate event_id during retry; never mark before broker acceptance. Consumer dedup storage must outlive the maximum replay horizon, and a deliberate new business operation must receive a new identity. The complete consumer transaction is in the inbox chapter.
Retention, poison rows and replay Important
In plain words: decide how long to keep slips, what to do with an undeliverable one, and how to resend without changing its identity.
Common misunderstanding: “Once a row is published, cleanup can ignore downstream lag.” The broker may trim or expire the only remaining message before a slow consumer reads it. Publication retention and consumer retention are different budgets.
Definition: the outbox lifecycle covers pending, leased, retry-delayed and published records; an operational parking state may be added for records requiring intervention. Published retention supports diagnosis and controlled replay but does not turn the outbox into the authoritative event-sourced domain model.
1 E8 cannot serialize or exceeds the destination's size limit
2 retry delay grows, but E8 remains pending and oldest age increases
3 strict ordering also holds E9 for the same aggregate
4 operator repairs the contract/configuration or explicitly parks E8
5 replay retains E8's identity unless this is a genuinely new business event
6 cleanup deletes only records beyond the chosen recovery and audit horizonReal scenarios: a schema deployment produces an invalid payload; a Kafka topic is deleted; a RabbitMQ binding is missing; a Redis stream is accidentally replaced by a string key.
| Problem | Safe operational response | Cost |
|---|---|---|
| Temporary broker outage | Retry with backoff and jitter; alert on oldest pending age | Backlog consumes database space |
| Permanently invalid event | Preserve payload securely, classify, repair or park with an audit trail | May block an aggregate's later events |
| Manual replay | Select an explicit range, keep IDs, confirm dedup horizon | Historical duplicates reach consumers |
| Published-row growth | Batched deletion or carefully designed partition retention | Deletion creates WAL and vacuum work |
| Broker retention too short | Increase retention or catch consumers up before trimming | More broker storage |
Fix: expose pending count, oldest age, attempts, publish errors and lease-loss counts. Keep payloads out of general error logs. Set a capacity limit for pending storage and choose how the request path behaves when that limit is approached. DLQ owns dead-letter transport patterns; the outbox must still record why an intent stopped progressing.
Mechanics and exact knobs
The producer's hot path performs two local writes and one commit. The relay's hot path performs a claim, broker I/O and a marker. Optimise the measured stage rather than hiding slow publication behind unbounded concurrency.
| Setting or structure | Sample choice | Why it matters |
|---|---|---|
| PostgreSQL pending partial index | ON outbox(id) WHERE published_at IS NULL | Keeps claim scans focused on outstanding work |
| Aggregate pending index | (aggregate_type, aggregate_id, id) for pending rows | Supports the predecessor guard |
| Batch size | Go command uses 500; Laravel command defaults to 4 | Throughput versus lease time, memory and duplicate replay size |
| Idle poll | 200 ms | Latency/load trade-off, not a guaranteed delivery deadline |
| Lease | 30 s in examples | Must cover the permitted batch duration and marking |
| Retry eligibility | available_at from database now() | A failed row does not spin on every poll |
| Per-row delay | min(2^attempts, 300) seconds, exponent capped first | Avoids arithmetic/interval overflow after many failures |
| Relay failure delay | Exponential full jitter with a configured cap | Avoids all relays hammering a failed dependency together |
| Claim owner | Fresh random token | Prevents a restarted worker inheriting stale ownership |
| Shard assignment | Stable aggregate hash modulo configured shard count | Changing shard count requires coordinated ownership transition |
| RabbitMQ publish | Persistent message, mandatory routing, confirm mode | A positive confirm can accompany an unroutable return |
| Kafka publish | acks=all and idempotence; deployment controls min.insync.replicas | Acceptance depends on replica configuration and failure policy |
| Redis publish | XADD; optional bounded IDMP; retention explicitly sized | Success is not unconditional durable disk persistence |
| Shutdown | Stop claims; bounded in-flight batch and cleanup | A hard process kill still leaves recovery work |
PostgreSQL now() is fixed at transaction start. Keep claim transactions short; a long transaction can make a newly assigned lease have less wall-clock life than expected. The examples do not hold the claim transaction open while publishing. Read outbox state from its owning primary, not a lagging read replica.
| Error or result | Meaning for this handoff | Action |
|---|---|---|
SQLSTATE 40001 | Serialization failure | Retry the whole producer transaction; keep external side effects outside it |
SQLSTATE 40P01 | Deadlock victim | Retry the whole transaction with a bounded policy |
SQLSTATE 23505 | Unique violation | Interpret the violated constraint; not every collision means “already delivered” |
SQLSTATE 57014 | Query cancelled/statement timeout | Roll back or reconcile the transaction outcome |
RabbitMQ 312 NO_ROUTE | Mandatory publish had no matching queue route | Keep row pending; repair topology |
RabbitMQ 406 PRECONDITION_FAILED | Incompatible declaration or protocol precondition | Replace the failed channel and fix configuration |
| Publisher nack / lost confirm | Broker rejection or uncertain publication | Do not mark; retry stable IDs |
Kafka NOT_ENOUGH_REPLICAS / timeout | Required acceptance was not obtained or is uncertain | Keep pending; check ISR and retry policy |
Redis WRONGTYPE | Destination key has another type | Repair the key/topology; preserve pending records |
Redis OOM / NOREPLICAS | Server rejected the write under configured policy | Keep pending and repair capacity/replication |
| Marked row count below claimed count | Claim ownership changed or record was already marked | Alert on lease loss; expect possible duplicates |
The Go AMQP client checks context cancellation around publication, but a context cannot interrupt every in-flight socket write. The command example adds a connection write deadline; a connection failure still requires supervisor-driven connection recreation. The PHP adapters need host application connection/read/write timeouts. A nominal lease is not a substitute for those transport bounds.
The synchronous PHP Kafka adapter can spend its configured delivery budget on each message, so the sample starts with four messages per batch and a 30-second lease. Keep batch size × per-message budget plus SQL/transport margin below the lease, and set the worker timeout above the permitted batch/cleanup time. The queued job's 50-second loop budget is checked only between batches; it is not a hard total deadline. Recalculate these budgets when broker settings or flush retries change. Lease loss remains a possible recovery event.
Solving the classic problems
| Problem | Solution | Advantage | Limitation |
|---|---|---|---|
| Event missing after successful request | Write the outbox in the business transaction | Durable recovery source | Application must consistently use that path |
| Event published for rolled-back data | Remove direct publish from the transaction | Consumers see only committed intent | Adds relay latency |
| Two relays claim the same pending row | Row lock during claim plus ownership token | Coordinates normal concurrent claims | Expiry still allows duplicate publication |
| Slow broker exhausts SQL connections | Short claim leases | Frees connections before network I/O | More ownership/recovery logic |
| Later aggregate event overtakes a failed predecessor | Predecessor guard and aggregate writer serialization | Isolates head-of-line blocking to an aggregate | A poison event intentionally blocks that aggregate |
| CDC emits update warnings | Stop polling-marker updates on the CDC table | Matches EventRouter's INSERT-only lifecycle | Choose a separate cleanup/progress policy |
| Relay marks after failed Kafka delivery | Inspect delivery reports as well as flush completion | Rejects permanent per-message failure | Client callback API must be verified |
| Tests pass but two DB connections break atomicity | Test named-connection rollback explicitly | Exercises the actual transaction boundary | Requires the host application's database fixture |
Backlog is a business decision
If producers add 500 events/s and a healthy relay can publish 700 events/s, it has 200 events/s of recovery capacity while traffic continues. A one-hour outage adds 1,800,000 events; draining that backlog takes 9,000 seconds at that surplus rate. These are arithmetic assumptions, not measured benchmark results. Storage sizing must include payload size, indexes, WAL, replication and safety margin.
A backlog threshold can reject new work, reduce optional events or trigger capacity changes. Silently deleting pending events to keep the table small breaks the guarantee. A monitoring dashboard should distinguish “no events arriving” from “relay has stopped.”
Deployment and contract changes
Deploy consumers that understand a new event before producers emit it, or use compatible evolution. Keep the old serializer contract for retained events; do not load arbitrary current Eloquent attributes during replay. During a polling-to-CDC migration, establish a cutover point and duplicate strategy before enabling the second relay. Running both indefinitely produces duplicate streams and conflicting lifecycle assumptions.
Recovery and disaster restoration
Restoring the producer database to an earlier time can resurrect published rows, and restoring a broker independently can lose accepted messages. Coordinate recovery objectives and retain event IDs. Reconcile business records against publication evidence and downstream state; a single published_at column cannot prove the entire system is consistent after independent restores. See backup and disaster recovery.
Choosing a relay
| Situation | Recommendation | Extra decision | Reason |
|---|---|---|---|
| Small service, modest event rate | Polling publisher | Lock-based versus lease-based relay | Lowest infrastructure overhead |
| Broker I/O can stall and SQL connections are scarce | Lease-based polling | Transport deadlines and duplicate policy | Keeps SQL transactions short |
| Existing Debezium platform and Kafka event backbone | CDC Outbox Event Router | Slot, offsets, snapshots and cleanup ownership | Reuses established capture operations |
| Strict order for one aggregate | Serialize its writes and publication ownership | Consumer version/gap handling | Broker key alone is insufficient |
| Independent aggregates at high volume | Sharded relay or CDC keyed partitioning | Safe ownership rebalance | Preserves useful parallelism |
| Atomic database update plus local background job only | Consider Laravel database queue on the same connection | Verify actual insert transaction and after-commit settings | A separate generic event outbox may be unnecessary |
| External event contract consumed by several services | Explicit event outbox | Envelope and retention ownership | Laravel job payload is not a public event schema |
| One database cannot contain business state and intent | Redesign the atomic boundary or use a supported transaction mechanism | Reconciliation and failure semantics | A second database called “outbox” does not solve dual writes |
| Need permanent event history as domain truth | Evaluate event sourcing | Different storage and replay model | An operational outbox is not that model |
Go
Before: commit, then hope
The before example makes two independent decisions. A successful database update followed by a failed publish leaves the application without a durable retry instruction.
// Package before shows the dual write: commit to the database, then publish
// to the broker. Each step is correct on its own; together they are not atomic.
package before
import (
"context"
"database/sql"
"encoding/json"
"fmt"
)
// Publisher is whatever broker client the service uses.
type Publisher interface {
Publish(ctx context.Context, topic, key string, body []byte) error
}
type OrderService struct {
db *sql.DB
pub Publisher
}
func NewOrderService(db *sql.DB, pub Publisher) *OrderService {
return &OrderService{db: db, pub: pub}
}
func (s *OrderService) PlaceOrder(ctx context.Context, orderID, customerID string, totalCents int64) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders (id, customer_id, total_cents, status) VALUES ($1, $2, $3, 'placed')`,
orderID, customerID, totalCents); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return err
}
// Write number two. If the process dies here, or the broker is down, or
// the network times out after the broker already stored the message,
// the database and the broker now disagree and nothing will repair it.
body, _ := json.Marshal(map[string]any{"order_id": orderID, "total_cents": totalCents})
if err := s.pub.Publish(ctx, "orders", orderID, body); err != nil {
// The order exists, the event does not. Returning an error here makes
// the caller retry and possibly create a second order.
return fmt.Errorf("order %s saved but event lost: %w", orderID, err)
}
return nil
}
// Publishing inside the transaction, before Commit, is no better: the broker
// accepts the event and then the commit fails, so consumers react to an order
// that never existed.After: write intent, then relay
The schema and Enqueue function use pgx.Tx; PlaceOrder commits the order and event through pgx.BeginFunc. The orders table belongs to the host service; its illustrative schema appears in the lab.
// Package after implements the transactional outbox: the event is a row
// written in the same transaction as the state change, and a separate relay
// moves rows to the broker.
package after
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Schema is the polling outbox. The relay claims rows with a lease
// (locked_by / locked_until), publishes outside any transaction and then
// marks them; attempts, last_error and available_at drive per-row backoff.
const Schema = `
CREATE TABLE outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- local relay scan ID, not commit order
event_id uuid NOT NULL UNIQUE, -- message id for consumer dedup
aggregate_type text NOT NULL, -- routes to topic / exchange / stream
aggregate_id text NOT NULL, -- partition key, ordering scope
type text NOT NULL, -- event name, e.g. OrderPlaced
payload jsonb NOT NULL,
headers jsonb NOT NULL DEFAULT '{}', -- traceparent, schema version...
created_at timestamptz NOT NULL DEFAULT now(),
available_at timestamptz NOT NULL DEFAULT now(), -- per-row retry backoff
attempts integer NOT NULL DEFAULT 0,
last_error text,
locked_by text, -- relay instance holding the lease
locked_until timestamptz, -- lease expiry (database clock)
published_at timestamptz
);
-- The relay only ever scans pending rows: keep that index tiny.
CREATE INDEX outbox_pending ON outbox (id) WHERE published_at IS NULL;
-- Used by the strict per-aggregate ordering guard (NOT EXISTS an older pending row).
CREATE INDEX outbox_pending_agg ON outbox (aggregate_type, aggregate_id, id) WHERE published_at IS NULL;
`
// Message is one outbox row as the relay and the publishers see it.
type Message struct {
ID int64
EventID string
AggregateType string
AggregateID string
Type string
Payload json.RawMessage
Headers map[string]string
CreatedAt time.Time
Attempts int
}
// Enqueue writes an event into the outbox using the caller's transaction.
// It takes pgx.Tx, not the pool: that type is the whole guarantee.
func Enqueue(ctx context.Context, tx pgx.Tx, aggType, aggID, eventType string, payload any, headers map[string]string) error {
body, err := json.Marshal(payload)
if err != nil {
return err
}
if headers == nil {
headers = map[string]string{}
}
hdr, err := json.Marshal(headers)
if err != nil {
return err
}
_, err = tx.Exec(ctx,
`INSERT INTO outbox (event_id, aggregate_type, aggregate_id, type, payload, headers)
VALUES ($1, $2, $3, $4, $5, $6)`,
NewUUID(), aggType, aggID, eventType, body, hdr)
return err
}
type OrderService struct{ pool *pgxpool.Pool }
func NewOrderService(pool *pgxpool.Pool) *OrderService { return &OrderService{pool: pool} }
// PlaceOrder commits the order and its event together, or neither.
// pgx.BeginFunc commits when the function returns nil and rolls back otherwise.
func (s *OrderService) PlaceOrder(ctx context.Context, orderID, customerID string, totalCents int64, traceparent string) error {
return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx,
`INSERT INTO orders (id, customer_id, total_cents, status) VALUES ($1, $2, $3, 'placed')`,
orderID, customerID, totalCents); err != nil {
return err
}
return Enqueue(ctx, tx, "order", orderID, "OrderPlaced",
map[string]any{"order_id": orderID, "customer_id": customerID, "total_cents": totalCents},
map[string]string{"traceparent": traceparent, "schema_version": "1"})
})
}
// NewUUID returns a random (version 4) UUID string using only the stdlib.
func NewUUID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}PgStore owns claims, ownership-checked markers, retry eligibility, gauges and batched cleanup. Its sharding fields are configuration for a coordinated relay deployment, not a dynamic rebalance protocol.
package after
import (
"context"
"encoding/json"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// PgStore claims rows with a short lease instead of holding row locks while
// the broker is slow. Every timestamp comes from the database clock (now()),
// never from the relay host, so relay clock skew cannot break the lease.
type PgStore struct {
Pool *pgxpool.Pool
// StrictOrder skips a row while an older row of the same aggregate is
// still pending (leased, backing off or failed). Several relays can then
// run in parallel, but writers must serialize aggregate updates. Identity IDs
// are not commit order, and a lease cannot fence late broker sends.
StrictOrder bool
// Shards > 1 makes this relay own only hash(aggregate_id) % Shards == Shard.
Shards, Shard int
}
const claimSQL = `
UPDATE outbox SET locked_by = $1,
locked_until = now() + make_interval(secs => $2),
attempts = attempts + 1
WHERE id IN (
SELECT o.id FROM outbox o
WHERE o.published_at IS NULL
AND o.available_at <= now()
AND (o.locked_until IS NULL OR o.locked_until < now())
AND ($4 <= 1 OR (hashtext(o.aggregate_id) & 2147483647) % $4 = $5)
AND (NOT $6 OR NOT EXISTS (
SELECT 1 FROM outbox p
WHERE p.aggregate_type = o.aggregate_type
AND p.aggregate_id = o.aggregate_id
AND p.published_at IS NULL
AND p.id < o.id))
ORDER BY o.id
LIMIT $3
FOR UPDATE SKIP LOCKED)
RETURNING id, event_id::text, aggregate_type, aggregate_id, type, payload, headers, created_at, attempts`
func (s *PgStore) Claim(ctx context.Context, owner string, limit int, lease time.Duration) ([]Message, error) {
rows, err := s.Pool.Query(ctx, claimSQL,
owner, lease.Seconds(), limit, s.Shards, s.Shard, s.StrictOrder)
if err != nil {
return nil, err
}
return pgx.CollectRows(rows, func(row pgx.CollectableRow) (Message, error) {
var m Message
var payload, hdr []byte
err := row.Scan(&m.ID, &m.EventID, &m.AggregateType, &m.AggregateID,
&m.Type, &payload, &hdr, &m.CreatedAt, &m.Attempts)
if err != nil {
return m, err
}
m.Payload = payload
return m, json.Unmarshal(hdr, &m.Headers)
})
}
func (s *PgStore) MarkPublished(ctx context.Context, owner string, ids []int64) (int64, error) {
// Alternative: DELETE ... WHERE id = ANY($2) AND locked_by = $1.
// The table stays small, but you lose the audit trail and replay.
tag, err := s.Pool.Exec(ctx, `
UPDATE outbox SET published_at = now(), locked_by = NULL, locked_until = NULL
WHERE id = ANY($2) AND locked_by = $1 AND published_at IS NULL`, owner, ids)
return tag.RowsAffected(), err
}
func (s *PgStore) Release(ctx context.Context, owner string, ids []int64, cause error) error {
// Per-row backoff: 2^attempts seconds, capped at five minutes.
_, err := s.Pool.Exec(ctx, `
UPDATE outbox SET locked_by = NULL, locked_until = NULL, last_error = $3,
available_at = now() + least(make_interval(secs => power(2, least(attempts, 9))),
interval '5 minutes')
WHERE id = ANY($2) AND locked_by = $1`, owner, ids, cause.Error())
return err
}
// Stats are the two numbers to export as gauges: depth and age of the oldest
// pending row. Age is what you alert on; depth alone hides a stuck relay.
func (s *PgStore) Stats(ctx context.Context) (depth int64, oldestAge time.Duration, err error) {
var secs float64
err = s.Pool.QueryRow(ctx, `
SELECT count(*), COALESCE(EXTRACT(EPOCH FROM now() - min(created_at)), 0)
FROM outbox WHERE published_at IS NULL`).Scan(&depth, &secs)
return depth, time.Duration(secs * float64(time.Second)), err
}
// Cleanup deletes published rows older than keep, in small batches so it
// never holds long locks or produces one huge WAL burst. Call it in a loop
// until it returns 0, or partition by created_at and drop old partitions.
func (s *PgStore) Cleanup(ctx context.Context, keep time.Duration) (int64, error) {
tag, err := s.Pool.Exec(ctx, `
DELETE FROM outbox WHERE id IN (
SELECT id FROM outbox
WHERE published_at < now() - make_interval(secs => $1)
ORDER BY id LIMIT 5000)`, keep.Seconds())
return tag.RowsAffected(), err
}Relay owns the process loop. A failed publish leaves the batch pending even when some records reached the broker. A successful publish followed by failed marking is handled the same way. context.WithoutCancel is bounded again for cleanup so shutdown does not create an unlimited release call.
package after
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"sort"
"time"
)
// Publisher is the one interface the relay knows. The RabbitMQ, Kafka and
// Redis Streams adapters implement it. PublishBatch must return nil only when
// every message reached the configured broker acceptance boundary.
// Durability depends on broker persistence/replication; acceptance is not consumption.
// Preserve submission order within each broker ordering scope.
type Publisher interface {
PublishBatch(ctx context.Context, msgs []Message) error
}
// ErrPublisherClosed asks the process supervisor to restart with a fresh client.
var ErrPublisherClosed = errors.New("publisher connection closed; recreate client")
// Store is the outbox table as the relay sees it. PgStore is the PostgreSQL
// implementation; MemStore is the in-memory one used by tests and the lab.
type Store interface {
// Claim leases up to limit publishable rows to owner for lease.
Claim(ctx context.Context, owner string, limit int, lease time.Duration) ([]Message, error)
// MarkPublished marks rows still leased by owner; it returns how many.
MarkPublished(ctx context.Context, owner string, ids []int64) (int64, error)
// Release gives the rows back with a per-row backoff and the error text.
Release(ctx context.Context, owner string, ids []int64, cause error) error
}
type Relay struct {
Store Store
Pub Publisher
Owner string // unique per process incarnation; never reuse after restart
BatchSize int // rows per claim
Lease time.Duration // must exceed the slowest publish of one batch
Idle time.Duration // sleep when the outbox is empty
MaxBackoff time.Duration // cap for the broker-failure backoff
Log *slog.Logger
}
// Run polls until ctx is cancelled. Cancellation stops new claims but lets
// the batch in flight finish and be marked: that is the graceful shutdown.
func (r *Relay) Run(ctx context.Context) error {
if r.Idle <= 0 || r.MaxBackoff <= 0 {
return errors.New("idle and max backoff must be positive")
}
if err := r.validate(); err != nil {
return err
}
failures := 0
for {
if ctx.Err() != nil {
return nil
}
// Detach the batch from shutdown, but bound it by the lease.
bctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), r.Lease)
n, err := r.RelayOnce(bctx)
cancel()
var wait time.Duration
switch {
case errors.Is(err, ErrPublisherClosed):
return err
case err != nil:
failures++
wait = r.backoff(failures)
r.logger().Error("outbox relay batch failed", "err", err, "retry_in", wait)
case n == 0:
failures = 0
wait = r.Idle
default:
failures = 0
continue // more may be waiting; do not sleep
}
select {
case <-ctx.Done():
return nil
case <-time.After(wait):
}
}
}
// RelayOnce claims one batch, publishes it and marks it.
func (r *Relay) RelayOnce(ctx context.Context) (int, error) {
if err := r.validate(); err != nil {
return 0, err
}
batch, err := r.Store.Claim(ctx, r.Owner, r.BatchSize, r.Lease)
if err != nil || len(batch) == 0 {
return 0, err
}
// UPDATE ... RETURNING has no guaranteed order: restore outbox order.
sort.Slice(batch, func(i, j int) bool { return batch[i].ID < batch[j].ID })
ids := make([]int64, len(batch))
for i, m := range batch {
ids[i] = m.ID
}
if err := r.Pub.PublishBatch(ctx, batch); err != nil {
// Some messages may have reached the broker anyway; they will be
// published again later. Consumers dedup on event_id.
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), min(r.Lease, 5*time.Second))
releaseErr := r.Store.Release(cleanup, r.Owner, ids, err)
cancel()
if releaseErr != nil {
return 0, errors.Join(err, fmt.Errorf("release claim: %w", releaseErr))
}
return 0, err
}
// Crash window: the broker has the batch, the marks are not written yet.
// After a restart (or lease expiry) the same rows are published again.
marked, err := r.Store.MarkPublished(ctx, r.Owner, ids)
if err != nil {
return 0, err
}
if marked < int64(len(ids)) {
// Our lease expired and another relay took some rows: they will be
// (or were) published twice. Raise Lease or shrink BatchSize.
r.logger().Warn("outbox lease lost before mark", "claimed", len(ids), "marked", marked)
}
return len(batch), nil
}
// backoff is exponential with full jitter, capped at MaxBackoff.
func (r *Relay) backoff(failures int) time.Duration {
d := 100 * time.Millisecond << min(failures, 16)
if d > r.MaxBackoff || d <= 0 {
d = r.MaxBackoff
}
return time.Duration(rand.Int64N(int64(d)) + 1)
}
func (r *Relay) validate() error {
if r.Store == nil || r.Pub == nil || r.Owner == "" || r.BatchSize <= 0 || r.Lease <= 0 {
return errors.New("relay needs store, publisher, unique owner, positive batch and lease")
}
return nil
}
func (r *Relay) logger() *slog.Logger {
if r.Log != nil {
return r.Log
}
return slog.Default()
}The command wires the store and selected publisher, uses a fresh owner token and stops taking new work on SIGTERM/SIGINT. Its RabbitMQ connection must be recreated by process supervision after connection failure; it does not pretend to implement an automatic connection manager.
// Command relay runs the outbox relay as its own process, with graceful
// shutdown on SIGTERM (deploys, Kubernetes) and SIGINT (Ctrl-C).
package main
import (
"context"
"fmt"
"log/slog"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
amqp "github.com/rabbitmq/amqp091-go"
"academy/outbox-pattern/after"
)
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
fmt.Println("set DATABASE_URL and BROKER=kafka|rabbitmq to run the relay")
return
}
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
// ctx is cancelled on the first SIGTERM/SIGINT; Run then finishes the
// batch in flight, marks it, and returns.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
log.Error("connect postgres", "err", err)
os.Exit(1)
}
defer pool.Close()
var pub after.Publisher
switch os.Getenv("BROKER") {
case "rabbitmq":
conn, err := amqp.DialConfig(os.Getenv("AMQP_URL"), amqp.Config{Dial: func(network, address string) (net.Conn, error) {
c, err := net.DialTimeout(network, address, 5*time.Second)
if err != nil {
return nil, err
}
return &boundedWriteConn{Conn: c}, nil
}})
if err != nil {
log.Error("connect rabbitmq", "err", err)
os.Exit(1)
}
defer conn.Close()
if pub, err = after.NewRabbitPublisher(conn, "domain-events"); err != nil {
log.Error("open channel", "err", err)
os.Exit(1)
}
default:
kp, err := after.NewKafkaPublisher(strings.Split(os.Getenv("KAFKA_BROKERS"), ",")...)
if err != nil {
log.Error("kafka client", "err", err)
os.Exit(1)
}
defer kp.Close() // ProduceSync already waited for every ack; Close frees connections
pub = kp
}
// A fresh incarnation token prevents a restarted process marking an older claim.
relay := &after.Relay{
Store: &after.PgStore{Pool: pool, StrictOrder: true},
Pub: pub,
Owner: after.NewUUID(),
BatchSize: 500,
Lease: 30 * time.Second,
Idle: 200 * time.Millisecond,
MaxBackoff: 30 * time.Second,
Log: log,
}
if err := relay.Run(ctx); err != nil {
log.Error("relay stopped", "err", err)
os.Exit(1)
}
log.Info("relay drained and stopped")
}
// amqp091-go context cancellation cannot interrupt an in-flight socket write.
// This cap is per write and is separate from the batch context deadline.
type boundedWriteConn struct{ net.Conn }
func (c *boundedWriteConn) Write(p []byte) (int, error) {
if err := c.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
return 0, err
}
return c.Conn.Write(p)
}The Go angle
A small Store and Publisher interface make the crash window testable without a broker. The memory model below deliberately omits StrictOrder: it demonstrates duplicate and out-of-order recovery, not PostgreSQL locking correctness. A unit test passing against it does not establish real SKIP LOCKED or broker durability behaviour.
package after
import (
"context"
"errors"
"sync"
"time"
)
// MemStore models leases but does NOT implement PgStore.StrictOrder.
// The lab deliberately demonstrates duplicates and out-of-order recovery.
// Now is injectable so tests can expire leases without sleeping.
type MemStore struct {
mu sync.Mutex
rows []*memRow
next int64
Now func() time.Time
}
type memRow struct {
Message
availableAt time.Time
lockedBy string
lockedUntil time.Time
publishedAt time.Time
lastError string
}
func NewMemStore() *MemStore { return &MemStore{Now: time.Now} }
// Append plays the role of Enqueue inside a committed transaction.
func (s *MemStore) Append(aggType, aggID, eventType string, payload []byte) Message {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
m := Message{ID: s.next, EventID: NewUUID(), AggregateType: aggType,
AggregateID: aggID, Type: eventType, Payload: payload, CreatedAt: s.Now()}
s.rows = append(s.rows, &memRow{Message: m, availableAt: m.CreatedAt})
return m
}
func (s *MemStore) Claim(_ context.Context, owner string, limit int, lease time.Duration) ([]Message, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := s.Now()
var out []Message
for _, r := range s.rows {
if len(out) == limit {
break
}
if !r.publishedAt.IsZero() || r.availableAt.After(now) ||
(r.lockedBy != "" && r.lockedUntil.After(now)) {
continue
}
r.lockedBy, r.lockedUntil = owner, now.Add(lease)
r.Attempts++
out = append(out, r.Message)
}
return out, nil
}
func (s *MemStore) MarkPublished(_ context.Context, owner string, ids []int64) (int64, error) {
s.mu.Lock()
defer s.mu.Unlock()
var n int64
for _, r := range s.rows {
if contains(ids, r.ID) && r.lockedBy == owner && r.publishedAt.IsZero() {
r.publishedAt, r.lockedBy = s.Now(), ""
n++
}
}
return n, nil
}
func (s *MemStore) Release(_ context.Context, owner string, ids []int64, cause error) error {
s.mu.Lock()
defer s.mu.Unlock()
for _, r := range s.rows {
if contains(ids, r.ID) && r.lockedBy == owner {
backoff := min(time.Second<<min(r.Attempts, 9), 5*time.Minute)
r.lockedBy, r.lastError, r.availableAt = "", cause.Error(), s.Now().Add(backoff)
}
}
return nil
}
// Pending returns how many rows are not yet published.
func (s *MemStore) Pending() int {
s.mu.Lock()
defer s.mu.Unlock()
n := 0
for _, r := range s.rows {
if r.publishedAt.IsZero() {
n++
}
}
return n
}
func contains(ids []int64, id int64) bool {
for _, x := range ids {
if x == id {
return true
}
}
return false
}
// ErrBrokerDown is what MemBroker returns while FailNext > 0.
var ErrBrokerDown = errors.New("broker unavailable")
// MemBroker is an in-memory broker: an append-only log per aggregate type,
// like one Kafka topic or one Redis stream. It never deduplicates.
type MemBroker struct {
mu sync.Mutex
Log map[string][]Message
FailNext int // fail this many PublishBatch calls
}
func NewMemBroker() *MemBroker { return &MemBroker{Log: map[string][]Message{}} }
func (b *MemBroker) PublishBatch(_ context.Context, msgs []Message) error {
b.mu.Lock()
defer b.mu.Unlock()
if b.FailNext > 0 {
b.FailNext--
return ErrBrokerDown
}
for _, m := range msgs {
b.Log[m.AggregateType] = append(b.Log[m.AggregateType], m)
}
return nil
}
// Deduper is the consumer half: process an event_id once, skip repeats.
// In production this is the inbox table, written in the consumer's own
// transaction together with the effect.
type Deduper struct {
seen map[string]bool
Processed int
Duplicates int
}
func NewDeduper() *Deduper { return &Deduper{seen: map[string]bool{}} }
func (d *Deduper) Handle(m Message, effect func(Message)) {
if d.seen[m.EventID] {
d.Duplicates++
return
}
d.seen[m.EventID] = true
d.Processed++
effect(m)
}package after
import (
"context"
"io"
"log/slog"
"testing"
"time"
)
func newRelay(st Store, pub Publisher, owner string) *Relay {
return &Relay{Store: st, Pub: pub, Owner: owner, BatchSize: 10,
Lease: 30 * time.Second, Idle: time.Millisecond, MaxBackoff: time.Millisecond,
Log: slog.New(slog.NewTextHandler(io.Discard, nil))}
}
// The lab scenario: the relay publishes a batch and dies before marking it.
// After the lease expires a second relay publishes the same rows again; the
// broker holds duplicates, the deduplicating consumer applies each once.
func TestCrashBetweenPublishAndMark(t *testing.T) {
ctx := context.Background()
clock := time.Date(2026, 11, 25, 12, 0, 0, 0, time.UTC)
st := NewMemStore()
st.Now = func() time.Time { return clock }
broker := NewMemBroker()
for i := 0; i < 5; i++ {
st.Append("order", "o-1", "OrderEvent", []byte(`{}`))
}
// Relay A: claim + publish, then "kill -9" before MarkPublished.
batch, _ := st.Claim(ctx, "relay-a", 3, 30*time.Second)
if err := broker.PublishBatch(ctx, batch); err != nil {
t.Fatal(err)
}
// Relay B starts at once: A's rows are still leased, so B skips them.
b := newRelay(st, broker, "relay-b")
if n, _ := b.RelayOnce(ctx); n != 2 {
t.Fatalf("relay-b first batch = %d, want 2 (rows 4-5)", n)
}
clock = clock.Add(31 * time.Second) // A's lease expires
if n, _ := b.RelayOnce(ctx); n != 3 {
t.Fatalf("relay-b second batch = %d, want 3 (rows 1-3 again)", n)
}
log := broker.Log["order"]
if len(log) != 8 {
t.Fatalf("broker holds %d records, want 8 (5 + 3 duplicates)", len(log))
}
d := NewDeduper()
applied := 0
for _, m := range log {
d.Handle(m, func(Message) { applied++ })
}
if applied != 5 || d.Duplicates != 3 || st.Pending() != 0 {
t.Fatalf("applied=%d dup=%d pending=%d", applied, d.Duplicates, st.Pending())
}
}
// A broker outage leaves rows pending with a per-row backoff; nothing is lost.
func TestBrokerDownReleasesRows(t *testing.T) {
ctx := context.Background()
clock := time.Now()
st := NewMemStore()
st.Now = func() time.Time { return clock }
broker := NewMemBroker()
broker.FailNext = 1
st.Append("order", "o-1", "OrderPlaced", []byte(`{}`))
r := newRelay(st, broker, "relay-a")
if _, err := r.RelayOnce(ctx); err != ErrBrokerDown {
t.Fatalf("err = %v, want ErrBrokerDown", err)
}
if n, _ := r.RelayOnce(ctx); n != 0 {
t.Fatal("row must wait for its backoff")
}
clock = clock.Add(3 * time.Second)
if n, _ := r.RelayOnce(ctx); n != 1 || st.Pending() != 0 {
t.Fatalf("n=%d pending=%d", n, st.Pending())
}
}
// Run stops claiming on cancel but the in-flight batch is still marked.
func TestRunStopsOnCancel(t *testing.T) {
st := NewMemStore()
st.Append("order", "o-1", "OrderPlaced", []byte(`{}`))
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- newRelay(st, NewMemBroker(), "relay-a").Run(ctx) }()
time.Sleep(20 * time.Millisecond)
cancel()
select {
case err := <-done:
if err != nil || st.Pending() != 0 {
t.Fatalf("err=%v pending=%d", err, st.Pending())
}
case <-time.After(time.Second):
t.Fatal("Run did not return after cancel")
}
}package after
import (
"context"
"errors"
"strings"
"testing"
"time"
amqp "github.com/rabbitmq/amqp091-go"
)
func TestClosedReturnChannelDoesNotSpin(t *testing.T) {
ch := make(chan amqp.Return, 1)
ch <- amqp.Return{MessageId: "E1", ReplyText: "NO_ROUTE"}
close(ch)
done := make(chan error, 1)
go func() { done <- checkReturns(ch) }()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "E1") || !strings.Contains(err.Error(), "closed") {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("closed return channel caused an infinite drain")
}
}
func TestAllMandatoryReturnsAreDrained(t *testing.T) {
ch := make(chan amqp.Return, 2000)
for i := 0; i < cap(ch); i++ {
ch <- amqp.Return{MessageId: "E1", ReplyText: "NO_ROUTE"}
}
if err := checkReturns(ch); err == nil {
t.Fatal("unroutable batch accepted")
}
if len(ch) != 0 {
t.Fatal("returns left in the buffer")
}
}
type publishFunc func(context.Context, []Message) error
func (f publishFunc) PublishBatch(ctx context.Context, m []Message) error { return f(ctx, m) }
type releaseProbe struct {
Store
deadline bool
cancelled bool
}
func (s *releaseProbe) Release(ctx context.Context, owner string, ids []int64, cause error) error {
deadline, ok := ctx.Deadline()
s.deadline = ok && time.Until(deadline) > 0 && time.Until(deadline) <= 5*time.Second
s.cancelled = ctx.Err() != nil
return s.Store.Release(ctx, owner, ids, cause)
}
func TestFailedPublishCleanupHasIndependentBoundedContext(t *testing.T) {
st := NewMemStore()
st.Append("order", "o1", "Placed", []byte(`{}`))
probe := &releaseProbe{Store: st}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
pub := publishFunc(func(context.Context, []Message) error { cancel(); return ErrBrokerDown })
r := newRelay(probe, pub, "fresh-owner")
if _, err := r.RelayOnce(ctx); !errors.Is(err, ErrBrokerDown) {
t.Fatal(err)
}
if !probe.deadline || probe.cancelled {
t.Fatalf("deadline=%v cancelled=%v", probe.deadline, probe.cancelled)
}
}
func TestRetryDelayDoesNotOverflowAfterManyFailures(t *testing.T) {
st := NewMemStore()
clock := time.Now()
st.Now = func() time.Time { return clock }
m := st.Append("order", "o1", "Placed", []byte(`{}`))
st.rows[0].Attempts = 100000
st.rows[0].lockedBy = "owner"
if err := st.Release(context.Background(), "owner", []int64{m.ID}, ErrBrokerDown); err != nil {
t.Fatal(err)
}
if got := st.rows[0].availableAt.Sub(clock); got != 5*time.Minute {
t.Fatal(got)
}
}
func TestRunRejectsZeroBackoff(t *testing.T) {
r := newRelay(NewMemStore(), NewMemBroker(), "owner")
r.MaxBackoff = 0
if err := r.Run(context.Background()); err == nil {
t.Fatal("zero backoff accepted")
}
}
func TestRunStopsWhenPublisherMustBeRecreated(t *testing.T) {
st := NewMemStore()
st.Append("order", "o1", "Placed", []byte(`{}`))
r := newRelay(st, publishFunc(func(context.Context, []Message) error { return ErrPublisherClosed }), "owner")
if err := r.Run(context.Background()); !errors.Is(err, ErrPublisherClosed) {
t.Fatal(err)
}
}Use one relay loop per owner token; do not run simultaneous RelayOnce calls with the same owner. Bound dependency calls, close clients at shutdown and keep database-driver errors intact enough to classify. This chapter's checked-in module records its actual dependency/toolchain requirements.
Laravel 13
Before: a transaction plus an unrelated publish
A transaction around Eloquent work does not include Redis, RabbitMQ or Kafka. Moving dispatch after the transaction avoids premature consumption but still leaves a crash window before enqueueing.
<?php
// app/Services/PlaceOrder.php — the dual write. The order commits, then the
// event is sent. Nothing ties the two together.
namespace App\Services;
use App\Jobs\NotifyWarehouse;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Junges\Kafka\Facades\Kafka;
final class PlaceOrder
{
public function __invoke(string $customerId, int $totalCents): Order
{
$order = DB::transaction(function () use ($customerId, $totalCents) {
return Order::create([
'customer_id' => $customerId,
'total_cents' => $totalCents,
'status' => 'placed',
]);
});
// Write number two. A crash, a deploy or a broker outage between the
// commit above and this line loses the event for good. A timeout after
// the broker stored it makes the caller retry and publish twice.
Kafka::publish()
->onTopic('orders')
->withKafkaKey((string) $order->id)
->withBodyKey('order_id', $order->id)
->withBodyKey('total_cents', $order->total_cents)
->send();
// Same problem with a queued job: Redis or SQS is a second resource.
// Moving it inside the closure, or using ->afterCommit(), only changes
// which half of the dual write can be lost.
NotifyWarehouse::dispatch($order->id);
return $order;
}
}After: a database record on the same connection
Install the migration in the producer's database. The Eloquent model casts payload and headers; the writer uses the aggregate's connection and requires an existing transaction.
<?php
// database/migrations/2026_11_25_000000_create_outbox_messages_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::connection(config('outbox.connection'))->create('outbox_messages', function (Blueprint $table) {
$table->id(); // local relay scan ID, not commit order
$table->uuid('event_id')->unique(); // message id for consumer dedup
$table->string('aggregate_type'); // routes to topic / exchange / stream
$table->string('aggregate_id'); // partition key, ordering scope
$table->string('type'); // event name, e.g. OrderPlaced
$table->jsonb('payload');
$table->jsonb('headers')->default('{}'); // traceparent, schema version...
$table->timestampTz('created_at')->useCurrent();
$table->timestampTz('available_at')->useCurrent(); // per-row retry backoff
$table->unsignedInteger('attempts')->default(0);
$table->text('last_error')->nullable();
$table->string('locked_by')->nullable(); // relay instance holding the lease
$table->timestampTz('locked_until')->nullable(); // lease expiry, database clock
$table->timestampTz('published_at')->nullable();
});
// Partial indexes (PostgreSQL): the relay only ever looks at pending rows.
DB::connection(config('outbox.connection'))->statement('CREATE INDEX outbox_pending ON outbox_messages (id) WHERE published_at IS NULL');
DB::connection(config('outbox.connection'))->statement('CREATE INDEX outbox_pending_agg ON outbox_messages (aggregate_type, aggregate_id, id) WHERE published_at IS NULL');
}
public function down(): void
{
Schema::connection(config('outbox.connection'))->dropIfExists('outbox_messages');
}
};<?php
// app/Models/OutboxMessage.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class OutboxMessage extends Model
{
public $timestamps = false;
protected $guarded = [];
protected function casts(): array
{
return [
'payload' => 'array',
'headers' => 'array',
'created_at' => 'immutable_datetime',
'available_at' => 'immutable_datetime',
'locked_until' => 'immutable_datetime',
'published_at' => 'immutable_datetime',
];
}
}<?php
// app/Outbox/Outbox.php — the one place that writes outbox rows.
namespace App\Outbox;
use App\Models\OutboxMessage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use LogicException;
final class Outbox
{
/**
* Record an event for $aggregate. Never talks to a broker.
* Refuses to run outside a transaction: an autocommitted outbox row next
* to an autocommitted aggregate row is the dual write again.
*/
public function record(Model $aggregate, string $type, array $payload, array $headers = []): OutboxMessage
{
if (DB::connection($aggregate->getConnectionName())->transactionLevel() === 0) {
throw new LogicException("Outbox::record({$type}) must run inside DB::transaction");
}
return OutboxMessage::on($aggregate->getConnectionName())->create([
'event_id' => (string) Str::uuid7(),
'aggregate_type' => Str::snake(class_basename($aggregate)),
'aggregate_id' => (string) $aggregate->getKey(),
'type' => $type,
'payload' => $payload,
'headers' => $headers + ['schema_version' => '1'],
]);
}
}<?php
// app/Models/Concerns/RecordsOutboxEvents.php — `use RecordsOutboxEvents;` on a model.
namespace App\Models\Concerns;
use App\Models\OutboxMessage;
use App\Outbox\Outbox;
trait RecordsOutboxEvents
{
public function recordOutboxEvent(string $type, array $payload, array $headers = []): OutboxMessage
{
return app(Outbox::class)->record($this, $type, $payload, $headers);
}
}<?php
// app/Services/PlaceOrder.php — explicit style: one transaction, two rows, no broker call.
namespace App\Services;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
final class PlaceOrder
{
public function __invoke(string $customerId, int $totalCents): Order
{
return (new Order)->getConnection()->transaction(function () use ($customerId, $totalCents) {
$order = Order::create([
'customer_id' => $customerId,
'total_cents' => $totalCents,
'status' => 'placed',
]);
// Order uses the RecordsOutboxEvents trait.
$order->recordOutboxEvent('OrderPlaced', [
'order_id' => $order->id,
'customer_id' => $customerId,
'total_cents' => $totalCents,
]);
return $order; // both rows commit, or neither does
});
}
}An observer is an alternative for a specific transition. Do not also emit the same event explicitly, and do not implement ShouldHandleEventsAfterCommit on the outbox observer: the insert belongs before commit. Eloquent bulk updates/deletes do not dispatch individual model events, so a mass-update path must record its own events deliberately.
<?php
// app/Observers/OrderObserver.php — implicit style, registered with
// #[ObservedBy([OrderObserver::class])] on Order. Eloquent's save() opens no
// transaction of its own, so the caller must wrap the save in DB::transaction;
// Outbox::record() throws if it does not. It must NOT implement
// ShouldHandleEventsAfterCommit: that would move the outbox insert after the
// commit and bring the dual write back.
namespace App\Observers;
use App\Models\Order;
final class OrderObserver
{
public function updated(Order $order): void
{
if ($order->wasChanged('status')) {
$order->recordOutboxEvent('OrderStatusChanged', [
'order_id' => $order->id,
'from' => $order->getOriginal('status'),
'to' => $order->status,
]);
}
}
}The relay's connection must point at that same producer database. Named-connection deployments need one correctly configured relay per database; the connection used for a business transaction is not automatically inherited by a separately running command.
<?php
// app/Outbox/OutboxPublisher.php — the one contract the relay knows.
namespace App\Outbox;
use App\Models\OutboxMessage;
use Illuminate\Support\Collection;
interface OutboxPublisher
{
/**
* Return only when the broker accepted every message at its configured durability boundary.
* Preserve order within each topic/partition/stream; this is not consumer processing.
* Throw otherwise, so the relay releases the rows and retries later.
*
* @param Collection<int, OutboxMessage> $messages
*/
public function publishBatch(Collection $messages): void;
}<?php
// config/outbox.php — deploy one relay configuration per producer database.
return [
'connection' => env('OUTBOX_DB_CONNECTION', env('DB_CONNECTION', 'pgsql')),
];<?php
namespace App\Providers;
use App\Outbox\OutboxPublisher;
use App\Outbox\OutboxRelay;
use Illuminate\Support\ServiceProvider;
final class OutboxServiceProvider extends ServiceProvider
{
public function register(): void
{
// The host binds OutboxPublisher to the chosen broker adapter.
$this->app->bind(OutboxRelay::class, fn ($app) => new OutboxRelay(
publisher: $app->make(OutboxPublisher::class),
strictOrder: true,
connection: config('outbox.connection'),
));
}
}<?php
// app/Outbox/OutboxRelay.php — claim with a lease, publish outside any
// transaction, mark. Same algorithm as the Go PgStore. PostgreSQL SQL.
namespace App\Outbox;
use App\Models\OutboxMessage;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;
final class OutboxRelay
{
public function __construct(
private OutboxPublisher $publisher,
private bool $strictOrder = true,
private ?string $connection = null,
) {}
/** Relay one batch; returns how many rows were published. */
public function relayBatch(string $owner, int $size = 4, int $leaseSeconds = 30): int
{
if ($owner === '' || $size <= 0 || $leaseSeconds <= 0) {
throw new \InvalidArgumentException('owner, positive batch and lease are required');
}
// 1. Claim: a SHORT transaction. Row locks live only until the lease is written.
$ids = DB::connection($this->connection)->transaction(function () use ($owner, $size, $leaseSeconds) {
$ids = OutboxMessage::on($this->connection)
->whereNull('published_at') // never "id > last seen id"
->whereRaw('available_at <= now()') // database clock, not PHP's
->where(fn ($q) => $q->whereNull('locked_until')->orWhereRaw('locked_until < now()'))
->when($this->strictOrder, fn ($q) => $q->whereNotExists(
fn (Builder $p) => $p->from('outbox_messages as p')
->whereColumn('p.aggregate_type', 'outbox_messages.aggregate_type')
->whereColumn('p.aggregate_id', 'outbox_messages.aggregate_id')
->whereNull('p.published_at')
->whereColumn('p.id', '<', 'outbox_messages.id')
))
->orderBy('id')
->limit($size)
// No skipLocked() in the query builder: lock() takes the raw clause,
// the same string Laravel's DatabaseQueue uses to pop jobs.
->lock('for update skip locked')
->pluck('id');
if ($ids->isNotEmpty()) {
OutboxMessage::on($this->connection)->whereKey($ids)->update([
'locked_by' => $owner,
'locked_until' => DB::raw('now() + make_interval(secs => '.(int) $leaseSeconds.')'),
'attempts' => DB::raw('attempts + 1'),
]);
}
return $ids;
});
if ($ids->isEmpty()) {
return 0;
}
$batch = OutboxMessage::on($this->connection)->whereKey($ids)->orderBy('id')->get();
// 2. Publish: no transaction open, no row locks held while the broker is slow.
try {
$this->publisher->publishBatch($batch);
} catch (Throwable $e) {
OutboxMessage::on($this->connection)->whereKey($ids)->where('locked_by', $owner)->update([
'locked_by' => null,
'locked_until' => null,
'last_error' => mb_substr($e->getMessage(), 0, 2000),
// Per-row backoff: 2^attempts seconds, capped at five minutes.
'available_at' => DB::raw("now() + least(make_interval(secs => power(2, least(attempts, 9))), interval '5 minutes')"),
]);
throw $e;
}
// 3. Mark. A crash before this line republishes the batch after the lease
// expires: the at-least-once contract. Consumers dedup on event_id.
$marked = OutboxMessage::on($this->connection)
->whereKey($ids)
->where('locked_by', $owner)
->whereNull('published_at')
->update(['published_at' => DB::raw('now()'), 'locked_by' => null, 'locked_until' => null]);
if ($marked < $ids->count()) {
Log::warning('outbox lease lost before mark; rows will be published twice', [
'claimed' => $ids->count(), 'marked' => $marked,
]);
}
return $batch->count();
}
}<?php
// app/Console/Commands/RelayOutbox.php — long-lived relay under Supervisor/systemd.
namespace App\Console\Commands;
use App\Outbox\OutboxRelay;
use Illuminate\Console\Command;
use Throwable;
final class RelayOutbox extends Command
{
protected $signature = 'outbox:relay
{--batch=4 : Rows per claim}
{--lease=30 : Lease in seconds; must exceed the slowest publish of one batch}
{--once : Relay one batch and exit}';
protected $description = 'Publish pending outbox rows to the broker';
private bool $running = true;
public function handle(OutboxRelay $relay): int
{
// Graceful shutdown: finish and mark the batch in flight, then exit.
$this->trap([SIGTERM, SIGINT], fn () => $this->running = false);
$owner = bin2hex(random_bytes(16)); // unique for this invocation/incarnation
$failures = 0;
do {
try {
$sent = $relay->relayBatch($owner, (int) $this->option('batch'), (int) $this->option('lease'));
$failures = 0;
} catch (Throwable $e) {
report($e);
$sent = 0;
$failures++;
}
if ($sent === 0 && ! $this->option('once')) {
// Idle poll 200 ms; on broker errors exponential backoff with full jitter, max 30 s.
$cap = $failures === 0 ? 200_000 : min(30_000_000, 100_000 * 2 ** min($failures, 10));
usleep(random_int(1, $cap));
}
} while ($this->running && ! $this->option('once'));
return $failures > 0 ? self::FAILURE : self::SUCCESS;
}
}The Laravel angle
Laravel's after_commit queue option delays enqueueing until parent transactions commit and discards dispatches when those transactions roll back. It does not persist an enqueue obligation before the process can die. A database queue insert can share a local transaction only when it actually uses the same connection and executes inside it; configuration and dispatch timing matter.
Laravel 13 documents database, Redis, Amazon SQS and Beanstalkd queue backends alongside synchronous/deferred/background and other queue options. RabbitMQ and Kafka require third-party drivers/packages. Laravel's Redis queue uses lists and sorted sets; the Streams publisher below is an explicit Redis command adapter.
A scheduled unique job can drive the relay in applications already operating Horizon. ShouldBeUnique/#[UniqueFor] reduce duplicate scheduling; they do not replace database claim ownership or consumer idempotency. A separate command avoids depending on the same failing queue infrastructure that the relay is meant to recover.
Use a shared lock-capable cache for uniqueness and onOneServer; set the queue's retry_after above the worker timeout (for example, 120 seconds versus this Horizon excerpt's 90). The detailed worker lifecycle belongs in Laravel queue internals.
<?php
// app/Jobs/RelayOutboxBatch.php — the relay as a queued job, for apps that
// already run Horizon and would rather not add a Supervisor program.
namespace App\Jobs;
use App\Outbox\OutboxRelay;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\UniqueFor;
#[UniqueFor(60)]
final class RelayOutboxBatch implements ShouldQueue, ShouldBeUnique
{
use Queueable;
public int $tries = 1; // the next scheduled run is the retry
public function handle(OutboxRelay $relay): void
{
$owner = bin2hex(random_bytes(16)); // unique for this invocation/incarnation
$deadline = microtime(true) + 50;
// Soft loop budget: checked BETWEEN batches, not a hard job deadline.
// Set worker timeout above this budget + one permitted batch duration.
while (microtime(true) < $deadline && $relay->relayBatch($owner, 4) > 0) {
}
}
}<?php
// routes/console.php — scheduling for the outbox.
use App\Jobs\RelayOutboxBatch;
use App\Models\OutboxMessage;
use Illuminate\Support\Facades\Schedule;
// Option 1 (no Supervisor program): queue the relay job every second onto the
// "outbox" queue, which a single-process Horizon supervisor works (see horizon.php).
// ShouldBeUnique reduces duplicate scheduling while its unique lock is valid;
// onOneServer needs a shared lock-capable cache across application servers.
Schedule::job(new RelayOutboxBatch, 'outbox')->everySecond()->onOneServer();
// Option 2: one batch per tick as a command, if a few seconds of latency is fine.
// Schedule::command('outbox:relay --once --batch=4')->everyFiveSeconds()->withoutOverlapping()->onOneServer();
// Retention: delete published rows older than 7 days, 5,000 at a time.
// (PostgreSQL compiles delete + limit to a ctid subquery.) At high volume,
// partition by created_at and drop whole partitions instead.
Schedule::call(function () {
do {
$deleted = OutboxMessage::on(config('outbox.connection'))
->where('published_at', '<', now()->subDays(7))
->limit(5000)
->delete();
} while ($deleted === 5000);
})->hourly()->onOneServer()->name('outbox-retention');<?php
// config/horizon.php (excerpt) — a dedicated supervisor for the outbox queue.
// One process, no balancing: two relay jobs in parallel would still be safe
// (leases + SKIP LOCKED). StrictOrder is a pending-row gate, not broker fencing.
// Set the Redis queue connection retry_after above 90 seconds, e.g. 120.
return [
'environments' => [
'production' => [
'supervisor-outbox' => [
'connection' => 'redis',
'queue' => ['outbox'],
'balance' => false,
'minProcesses' => 1,
'maxProcesses' => 1,
'tries' => 1,
'timeout' => 90, // 50 s soft loop budget + one bounded batch + margin
],
// 'supervisor-1' => [...] your normal queues
],
],
];The feature tests require a Laravel 13 host with the shown models/migration, dependencies and a PostgreSQL test database. They are proposed integration tests; syntax checking these files does not execute that fixture.
<?php
// tests/Feature/OutboxTest.php — needs PostgreSQL (partial indexes, SKIP LOCKED).
namespace Tests\Feature;
use App\Models\Order;
use App\Models\OutboxMessage;
use App\Outbox\OutboxPublisher;
use App\Outbox\OutboxRelay;
use App\Services\PlaceOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use RuntimeException;
use Tests\TestCase;
final class OutboxTest extends TestCase
{
use RefreshDatabase;
public function test_order_and_event_commit_together(): void
{
$order = (new PlaceOrder)('cust-1', 4200);
$this->assertDatabaseHas('outbox_messages', [
'aggregate_type' => 'order',
'aggregate_id' => (string) $order->id,
'type' => 'OrderPlaced',
'published_at' => null,
]);
}
public function test_rollback_leaves_no_event(): void
{
try {
DB::transaction(function () {
$order = Order::create(['customer_id' => 'c', 'total_cents' => 1, 'status' => 'placed']);
$order->recordOutboxEvent('OrderPlaced', ['order_id' => $order->id]);
throw new RuntimeException('payment declined');
});
} catch (RuntimeException) {
}
$this->assertDatabaseCount('outbox_messages', 0);
}
public function test_relay_marks_only_after_publish(): void
{
(new PlaceOrder)('cust-1', 4200);
$fake = new class implements OutboxPublisher
{
public array $sent = [];
public function publishBatch(Collection $messages): void
{
array_push($this->sent, ...$messages->pluck('event_id'));
}
};
$this->assertSame(1, (new OutboxRelay($fake))->relayBatch('test'));
$this->assertCount(1, $fake->sent);
$this->assertNotNull(OutboxMessage::sole()->published_at);
}
public function test_broker_failure_keeps_row_pending_with_backoff(): void
{
(new PlaceOrder)('cust-1', 4200);
$down = new class implements OutboxPublisher
{
public function publishBatch(Collection $messages): void
{
throw new RuntimeException('broker down');
}
};
try {
(new OutboxRelay($down))->relayBatch('test');
$this->fail('expected the publisher exception');
} catch (RuntimeException) {
}
$row = OutboxMessage::sole();
$this->assertNull($row->published_at);
$this->assertSame(1, $row->attempts);
$this->assertSame('broker down', $row->last_error);
$this->assertNull($row->locked_by);
}
public function test_named_connection_keeps_order_and_outbox_in_the_same_rollback(): void
{
$default = config('database.default');
config(['database.connections.outbox_test' => config("database.connections.{$default}")]);
$connection = DB::connection('outbox_test');
$connection->beginTransaction();
try {
$order = new Order(['customer_id' => 'named-connection-customer', 'total_cents' => 100, 'status' => 'placed']);
$order->setConnection('outbox_test');
$order->save();
$event = $order->recordOutboxEvent('OrderPlaced', ['order_id' => $order->id]);
$this->assertSame('outbox_test', $event->getConnectionName());
$eventId = $event->event_id;
} finally {
$connection->rollBack();
}
$this->assertFalse(OutboxMessage::on('outbox_test')->where('event_id', $eventId)->exists());
}
}Broker differences
RabbitMQ
A polling relay publishes persistent messages to the declared exchange with mandatory=true, enables publisher confirms, and checks both confirms and returns. A positive confirm for an unroutable message means RabbitMQ handled the publication, not that a queue retained it. Configure the expected exchange, binding and durable queue before publishing; quorum-queue durability depends on the deployed quorum and available replicas.
The Go adapter uses a fresh channel per batch and buffers at most one return per message. A closed return channel is treated as uncertain instead of spinning forever. The PHP adapter uses the RabbitMQ Laravel package for connection settings and php-amqplib for explicit confirms; generic Laravel job dispatch does not express this event acceptance contract.
package after
import (
"context"
"errors"
"fmt"
amqp "github.com/rabbitmq/amqp091-go"
)
// RabbitPublisher uses a fresh confirm channel per batch. Call PublishBatch
// serially on each relay. Reconnect the connection after a connection failure.
type RabbitPublisher struct {
conn *amqp.Connection
exchange string
}
func NewRabbitPublisher(conn *amqp.Connection, exchange string) (*RabbitPublisher, error) {
if conn == nil || conn.IsClosed() {
return nil, ErrPublisherClosed
}
return &RabbitPublisher{conn: conn, exchange: exchange}, nil
}
func (p *RabbitPublisher) PublishBatch(ctx context.Context, msgs []Message) error {
if p.conn.IsClosed() {
return ErrPublisherClosed
}
if len(msgs) == 0 {
return nil
}
if err := ctx.Err(); err != nil {
return err
}
ch, err := p.conn.Channel()
if err != nil {
return err
}
defer ch.Close()
if err := ch.Confirm(false); err != nil {
return err
}
// At most one return per publish. Capacity covers the entire batch, so
// the AMQP reader can process all returns before the matching confirms.
returns := ch.NotifyReturn(make(chan amqp.Return, len(msgs)))
confirms := make([]*amqp.DeferredConfirmation, 0, len(msgs))
for _, m := range msgs {
hdr := amqp.Table{}
for k, v := range m.Headers {
hdr[k] = v
}
hdr["aggregate_id"] = m.AggregateID
dc, err := ch.PublishWithDeferredConfirmWithContext(ctx, p.exchange,
m.AggregateType+"."+m.Type, true, false, amqp.Publishing{
MessageId: m.EventID, Type: m.Type, ContentType: "application/json",
DeliveryMode: amqp.Persistent, Timestamp: m.CreatedAt,
Headers: hdr, Body: m.Payload,
})
if err != nil {
return err
}
confirms = append(confirms, dc)
}
for i, dc := range confirms {
ok, err := dc.WaitContext(ctx)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("rabbitmq nacked outbox id %d", msgs[i].ID)
}
}
// basic.return precedes basic.ack; the channel reader has already queued
// returns once every deferred confirmation completes. A confirm alone
// does not prove routing. Fresh channels avoid stale returns across batches.
return checkReturns(returns)
}
func checkReturns(returns <-chan amqp.Return) error {
var first error
for {
select {
case r, ok := <-returns:
if !ok {
return errors.Join(first, errors.New("AMQP return channel closed; outcome uncertain"))
}
if first == nil {
first = fmt.Errorf("unroutable event %s: %s", r.MessageId, r.ReplyText)
}
default:
return first
}
}
}<?php
// app/Outbox/RabbitMqOutboxPublisher.php
// Uses vladimir-yuldashev/laravel-queue-rabbitmq for the connection settings in
// config/queue.php. Its pushRaw() wraps Laravel job payloads and does not enable
// publisher confirms, so we open our own php-amqplib channel on its connection.
namespace App\Outbox;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Queue;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use RuntimeException;
final class RabbitMqOutboxPublisher implements OutboxPublisher
{
public function __construct(private string $exchange = 'domain-events') {}
public function publishBatch(Collection $messages): void
{
/** @var \VladimirYuldashev\LaravelQueueRabbitMQ\Queue\RabbitMQQueue $queue */
$queue = Queue::connection('rabbitmq');
$channel = $queue->getConnection()->channel();
$channel->confirm_select();
$nacked = [];
$returned = [];
$channel->set_nack_handler(function (AMQPMessage $m) use (&$nacked) {
$nacked[] = $m->get('message_id');
});
$channel->set_return_listener(function ($code, $text, $exchange, $key, AMQPMessage $m) use (&$returned) {
$returned[] = $m->get('message_id'); // mandatory + no matching binding
});
try {
foreach ($messages as $m) {
$channel->basic_publish(new AMQPMessage(json_encode($m->payload, JSON_THROW_ON_ERROR), [
'message_id' => $m->event_id, // consumers dedup on this
'type' => $m->type,
'content_type' => 'application/json',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,
'application_headers' => new AMQPTable($m->headers + ['aggregate_id' => $m->aggregate_id]),
]), $this->exchange, "{$m->aggregate_type}.{$m->type}", true);
}
// One wait for the whole batch: confirms for persistent messages arrive
// after the broker's batched fsync, so waiting per message is slow.
$channel->wait_for_pending_acks_returns(5.0);
} finally {
$channel->close();
}
if ($nacked !== [] || $returned !== []) {
throw new RuntimeException('RabbitMQ refused outbox events: '.implode(',', [...$nacked, ...$returned]));
}
}
}A channel per batch is deliberately simple and has setup overhead. A high-throughput long-lived publisher needs bounded in-flight tracking, correlation of returns/confirms and tested channel recovery. Confirmed publication is still independent of the SQL marker and consumer acknowledgment.
Kafka
Publish with the aggregate ID as the key and preserve stable event identity in a header. acks=all, idempotence and the topic's min.insync.replicas determine the accepted-write boundary. Producer idempotence handles protocol retries; replaying a SQL row after restart is a new produce operation and still needs consumer dedup.
The Go adapter waits for every ProduceSync result. The Laravel adapter uses the verified withDrMsgCb API from mateusjunges/laravel-kafka: successful flush only says pending requests completed, so each delivery report must also indicate success. It uses a simple per-message synchronous producer path; a production batch implementation may reuse a producer while retaining per-record result tracking.
package after
import (
"context"
"github.com/twmb/franz-go/pkg/kgo"
)
// KafkaPublisher keys every record by aggregate id, so all events of one
// aggregate land in one partition per topic. Concurrent relays and late retries
// still require the ordering discipline described on the page.
type KafkaPublisher struct {
cl *kgo.Client
}
func NewKafkaPublisher(brokers ...string) (*KafkaPublisher, error) {
cl, err := kgo.NewClient(
kgo.SeedBrokers(brokers...),
kgo.RequiredAcks(kgo.AllISRAcks()),
// Idempotent writes are franz-go's default: the broker drops retries
// of the same batch within this producer session. It does NOT dedup
// a relay that crashed and republished on restart; event_id does.
)
if err != nil {
return nil, err
}
return &KafkaPublisher{cl: cl}, nil
}
func (p *KafkaPublisher) PublishBatch(ctx context.Context, msgs []Message) error {
recs := make([]*kgo.Record, 0, len(msgs))
for _, m := range msgs {
hdrs := []kgo.RecordHeader{
{Key: "id", Value: []byte(m.EventID)}, // same header name Debezium's router uses
{Key: "type", Value: []byte(m.Type)},
}
for k, v := range m.Headers {
if k == "id" || k == "type" {
continue
} // reserved event identity
hdrs = append(hdrs, kgo.RecordHeader{Key: k, Value: []byte(v)})
}
recs = append(recs, &kgo.Record{
Topic: "outbox.event." + m.AggregateType,
Key: []byte(m.AggregateID),
Value: m.Payload,
Headers: hdrs,
})
}
// ProduceSync returns after every record is acknowledged or failed.
return p.cl.ProduceSync(ctx, recs...).FirstErr()
}
// Close releases the client's connections; call it on shutdown.
func (p *KafkaPublisher) Close() { p.cl.Close() }<?php
// Laravel adapter using mateusjunges/laravel-kafka and its verified withDrMsgCb API.
namespace App\Outbox;
use Illuminate\Support\Collection;
use Junges\Kafka\Facades\Kafka;
use Junges\Kafka\Message\Message;
use RuntimeException;
final class KafkaOutboxPublisher implements OutboxPublisher
{
public function publishBatch(Collection $messages): void
{
foreach ($messages as $m) {
$reported = false;
$deliveryError = null;
// send() flushes. A drained producer queue is not by itself proof
// of successful delivery: inspect the per-message delivery report.
$sent = Kafka::publish()
->onTopic("outbox.event.{$m->aggregate_type}")
->withConfigOptions([
'enable.idempotence' => 'true',
'delivery.timeout.ms' => '5000',
'request.timeout.ms' => '3000',
])
->withDrMsgCb(function ($producer, $report) use (&$reported, &$deliveryError) {
$reported = true;
if ($report->err !== RD_KAFKA_RESP_ERR_NO_ERROR) {
$deliveryError = $report->errstr();
}
})
->withMessage(new Message(
headers: ['id' => $m->event_id, 'type' => $m->type] + $m->headers,
body: $m->payload,
key: $m->aggregate_id,
))
->send();
if (! $sent || ! $reported || $deliveryError !== null) {
throw new RuntimeException('Kafka delivery not confirmed: '.($deliveryError ?? 'no successful report'));
}
}
}
}A Kafka transaction can atomically group Kafka writes/offsets within its documented scope. It does not make the PostgreSQL business transaction and SQL outbox marker part of that commit. CDC is an alternative relay implementation, not a reason to remove stable event IDs.
Redis Streams
Append stable event_id, aggregate identity, type and payload to a stream. MULTI/EXEC prevents interleaving within its Redis execution boundary but does not roll back successful commands when another command fails at runtime. Check all command results; partial success means the SQL batch remains pending and may be appended again.
The default PHP adapter leaves trimming disabled. If you set MAXLEN, size it for offline/slow consumers and replay requirements; a published outbox marker cannot recover an event already trimmed from the stream unless retained source records and a replay procedure exist. Redis 8.6+ IDMP is optional and bounded by its configured history; it does not replace the consumer inbox. Persistence and replication settings decide what survives a crash or failover.
package after
import (
"context"
"strconv"
"github.com/redis/go-redis/v9"
)
// RedisPublisher appends to one stream per aggregate type. Redis Streams has
// no partitions: order is the order of XADD calls on that key.
type RedisPublisher struct {
rdb *redis.Client
producerID string // stable per relay deployment, used by IDMP
maxLen int64
useIDMP bool // Redis 8.6+ only
}
func NewRedisPublisher(rdb *redis.Client, producerID string, maxLen int64, useIDMP bool) *RedisPublisher {
return &RedisPublisher{rdb: rdb, producerID: producerID, maxLen: maxLen, useIDMP: useIDMP}
}
func (p *RedisPublisher) PublishBatch(ctx context.Context, msgs []Message) error {
// MULTI/EXEC prevents interleaving on one Redis server, not rollback.
// A runtime error can leave part of this batch appended; retry with stable IDs.
// XADD success follows configured Redis durability, not an unconditional fsync.
_, err := p.rdb.TxPipelined(ctx, func(pipe redis.Pipeliner) error {
for _, m := range msgs {
args := &redis.XAddArgs{
Stream: "outbox:" + m.AggregateType,
ID: "*",
MaxLen: p.maxLen, // 0 disables trimming; size retention for the slowest consumer
Approx: true, // MAXLEN ~ is much cheaper than exact trimming
Values: map[string]any{
"event_id": m.EventID, // consumer-side dedup field
"outbox_id": strconv.FormatInt(m.ID, 10),
"aggregate_id": m.AggregateID,
"type": m.Type,
"payload": string(m.Payload),
},
}
if p.useIDMP {
// XADD ... IDMP <producer> <event_id> *: a republished event
// returns the original entry id while its bounded IDMP history remains.
// Consumer dedup is still required after expiry/failover/history eviction.
args.ProducerID = p.producerID
args.IdempotentID = m.EventID
}
pipe.XAdd(ctx, args)
}
return nil
})
return err
}<?php
// app/Outbox/RedisStreamOutboxPublisher.php — the Redis facade (phpredis).
// Laravel's redis queue driver uses lists and sorted sets, not streams.
namespace App\Outbox;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Redis;
use RuntimeException;
final class RedisStreamOutboxPublisher implements OutboxPublisher
{
public function __construct(
private int $maxLen = 0,
private bool $useIdmp = false, // Redis 8.6+ only
private string $producerId = 'orders-outbox-relay',
) {}
public function publishBatch(Collection $messages): void
{
$results = Redis::transaction(function ($redis) use ($messages) {
// rawCommand() bypasses phpredis's key prefix; xadd() applies it.
$prefix = (string) $redis->getOption(\Redis::OPT_PREFIX);
foreach ($messages as $m) {
$stream = "outbox:{$m->aggregate_type}";
$fields = [
'event_id' => $m->event_id, // consumer-side dedup field
'outbox_id' => (string) $m->id,
'aggregate_id' => $m->aggregate_id,
'type' => $m->type,
'payload' => json_encode($m->payload, JSON_THROW_ON_ERROR),
];
if (! $this->useIdmp) {
// phpredis: xadd(key, id, fields, maxlen, approximate)
$redis->xadd($stream, '*', $fields, $this->maxLen, true);
continue;
}
// phpredis's xadd() has no IDMP parameter, so send the raw command.
// IDMP suppresses duplicates only while bounded history retains the ID.
// Set a stable producer ID; still deduplicate in consumers.
$args = [$prefix.$stream, 'IDMP', $this->producerId, $m->event_id];
if ($this->maxLen > 0) {
array_push($args, 'MAXLEN', '~', (string) $this->maxLen);
}
$args[] = '*';
foreach ($fields as $k => $v) {
array_push($args, $k, $v);
}
$redis->rawCommand('XADD', ...$args);
}
});
// MULTI/EXEC has no rollback: earlier XADDs may succeed before an error.
// EXEC returns false if the transaction failed, and false per command
// that errored. Either way the relay must not mark the batch.
if ($results === false || in_array(false, (array) $results, true)) {
throw new RuntimeException('Redis rejected part of the outbox batch');
}
}
}The PHP raw-command path explicitly includes the phpredis prefix, because raw commands bypass automatic key prefixing. Redis Cluster multi-key transactions require compatible hash slots; the sample transaction is for a single Redis server. Use per-stream publication or an intentionally designed shared hash tag if adapting it to Cluster.
In production systems
- PostgreSQL documents
SKIP LOCKEDas useful for queue-like tables while warning that it provides an inconsistent view. That is exactly why relay work distribution and business ordering are separate decisions. - Debezium documents the Outbox Event Router's event ID header, aggregate key and INSERT-only expectation. Those constraints shape the table lifecycle and connector predicate here.
- RabbitMQ documents publisher confirms separately from consumer acknowledgments and returns unroutable mandatory publications before confirming them. A relay must evaluate both signals.
- Laravel's transaction/queue APIs and the Kafka package's delivery callback implementation expose the boundaries used by the sample. No claim here depends on an undocumented company's deployment story.
In architecture: from a single process to a distributed system
Monolith: one process and one database
A monolith creating an order and running a local report may need only a transactional database job. Add an event outbox when the work must survive process exit or leave the application through a stable contract. The simplest version uses one application transaction and one small polling relay; it does not need a fleet of brokers to demonstrate the boundary.
Modular monolith and multiple databases
The Sales module owns its outbox and event schema. Another module can consume the contract without querying Sales tables. If modules use separate databases, the Sales outbox stays in Sales's database; moving all outboxes into a shared “integration database” restores the dual-write problem. Explicit connection selection is especially important in multi-tenant Laravel applications.
Microservices: order to fulfilment
Sales commits an order and event together. A relay publishes; Fulfilment's consumer commits its inbox record and reservation together. Fulfilment may create its own outbox event for the next service. Every service has its own local atomic boundary; no one database transaction encloses the entire chain. A multi-step business decision uses a saga, which is outside this chapter's relay responsibility.
1 Sales transaction: order + Sales outbox(E1)
2 Sales relay: publish E1 -> broker
3 Fulfilment transaction: inbox(E1) + reservation + Fulfilment outbox(E2)
4 Fulfilment relay: publish E2 -> broker
5 another consumer applies E2 in its own transactionDistributed data: replicas, shards and regions
A replica can lag behind a producer commit; claim from the primary that owns the outbox. A sharded service needs an outbox inside each shard's atomic transaction boundary and a relay ownership scheme for those shards. CDC offsets and database restore positions belong to the same recovery plan.
Cross-region failover can lose recently accepted data according to database/broker replication policy, or reintroduce already delivered events after a restore. Leases use database time to reduce relay-host skew, but clock choice does not create a globally ordered log. Retain stable identity and a consumer version policy across region changes.
Scaling path: 1×, 10× and 100×
| Stage | Change | Check before adding more workers |
|---|---|---|
| 1× | One relay, small batches, pending partial index | Correct transaction and crash recovery |
| 10× | Multiple claimers across independent aggregates | Database connection pressure, oldest age, duplicate ratio |
| 100× | Coordinated aggregate/shard ownership or mature CDC platform | Ordering during rebalance, WAL/offset capacity, retention budget |
| Recovery surge | Temporarily increase safe surplus throughput | Broker quotas, consumer capacity, retry amplification |
Adding workers cannot bypass one aggregate's required serial order. Measure claim duration, publish duration and mark duration separately; a saturated broker needs capacity or workload changes, not unbounded SQL claiming.
Lab
Every experiment below is expected, not run. Use an already provisioned PostgreSQL and the selected broker; no Docker setup is required or executed. Go unit tests and PHP syntax checks are separate source QA, not evidence that these integration experiments ran.
- Prepare the producer schema. Apply
Schemafromgo/after/outbox.goand create the illustrative business table below. Laravel users apply the migration and supply their hostOrdermodel instead.
CREATE TABLE orders (
id text PRIMARY KEY,
customer_id text NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0),
status text NOT NULL
);
-- Expected, not run: orders and outbox exist in the same database.- Rollback the producer. In terminal A, run the atomic-commit INSERTs but replace
COMMITwithROLLBACK. In terminal B, inspect both tables.
SELECT count(*) FROM orders WHERE id = 'order-42';
SELECT count(*) FROM outbox WHERE aggregate_id = 'order-42';
-- Expected, not run: 0 and 0 after rollback.- Commit while the broker is unavailable. Commit one order/event, then run the relay against an unavailable test endpoint. Inspect retry state; restore the endpoint and retry.
SELECT event_id, attempts, available_at, published_at
FROM outbox WHERE aggregate_id = 'order-42';
-- Expected, not run: row remains pending, attempts increase, retry is delayed.
-- After recovery: publication is accepted, then published_at becomes non-null.- Crash after publish but before mark. Pause the relay at that boundary in a debugger, terminate it, let the lease expire and start another relay. Observe repeated
event_idat the destination. For a broker-free illustration, the checked-in memory lab follows the same crash window but does not model strict ordering.
cd docs/snippets/messaging/outbox-pattern/go
go run ./lab
# Expected, not run: six logical events, ten broker-log entries, four duplicates skipped.
# This is a memory simulation, not a RabbitMQ/Kafka/Redis durability test.- Exercise a real destination rejection. Remove the RabbitMQ output binding, use an unavailable Kafka topic under your topic-creation policy, or put a string at the Redis stream key in a disposable namespace. Confirm that the row is not marked as published. Restore the topology; resend with the same event ID.
SELECT event_id, published_at, last_error FROM outbox WHERE published_at IS NULL;
-- Expected, not run: rejection remains visible and no false published marker appears.- Prove the ordering limit. Hold a low-ID INSERT uncommitted in terminal A, commit a higher-ID INSERT in B and observe what a pending scan can see. Then repeat updates to one existing aggregate with a row lock/version discipline. Compare the logical transition order; do not infer it from identity values alone. In a CDC variant, stop the polling relay and verify EventRouter rejects an accidental UPDATE under
fatalmode.
The source tests cover release/retry, duplicate publication and bounded control flow. A release still needs integration evidence for PostgreSQL claims, actual broker persistence, PHP dependency configuration and the operational recovery plan.
Common misconceptions
| Belief | Reality |
|---|---|
| “An outbox is exactly once” | Publication may repeat; consumers need idempotent effects |
| “After commit dispatch is an outbox” | It postpones dispatch but does not persist the obligation |
| “The relay should mark before publish to avoid duplicates” | A crash then loses the event permanently |
| “A confirm means the customer saw the event” | It describes publisher/broker acceptance, not processing |
| “A Kafka transaction includes my SQL update” | It does not cross into that independent database transaction |
| “SKIP LOCKED guarantees ordering” | It intentionally skips locked rows |
| “Identity/UUIDv7 order is commit order” | Allocation and commit can occur in different orders |
| “A lease expiry stops the old publisher” | External broker writes are not fenced by the SQL lease |
| “CDC never duplicates” | Restarts/snapshots can reproduce records |
| “Redis EXEC rolls back a bad batch” | Runtime command errors do not undo successful commands |
| “Published means safe to trim the broker immediately” | Slow consumers may still need that message |
| “The outbox is the event store” | Its retention and meaning are operational, not necessarily domain history |
| “Every failed row should be skipped automatically” | Skipping can violate aggregate ordering and business obligations |
Cheat sheet
| Topic | Remember |
|---|---|
| Producer boundary | Business row and outbox row share one transaction and connection |
| Payload | Capture the event at the transition; do not rebuild from mutable state |
| Identity | Keep the same event ID across every resend |
| Claim | Short database transaction, bounded batch, owner token |
| Lease | Database time; unique incarnation; no broker fencing |
| Marker | Only after the configured acceptance boundary |
| Ordering | Serialize aggregate writes, key publication, handle gaps/late duplicates |
| Polling | Pending-state scan; never a naive increasing-ID watermark |
| CDC | INSERT-only event lifecycle; filter other connector records |
| RabbitMQ | Persistent + mandatory + confirm + return handling |
| Kafka | Key + acknowledged produce + delivery-report errors |
| Redis | Check each result; no rollback; explicit durability/retention |
| Laravel | Same named connection; observers before commit; after_commit is different |
| Operations | Oldest pending age, retry count, lease loss and recovery capacity |
| Cleanup | Published retention and broker retention are separate budgets |
| Replay | Explicit scope, stable identities and sufficient consumer dedup retention |
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 — Why do publish-before-commit and publish-after-commit both fail? Must-know
Answer
Answer: The first can announce rolled-back state; the second can lose the announcement if the process exits after committing. The outbox persists intent in the same local commit.
2 — Which condition is missing if an outbox model uses the default database while the order uses a named connection? Important
Answer
Answer: The two writes do not share the same transaction. Select the aggregate's connection for the outbox insert and configure its relay accordingly.
3 — What happens after the broker accepts an event but the relay crashes before marking it? Must-know
Answer
Answer: The event remains pending, is resent with the same identity and may appear twice. The consumer's effect/inbox transaction handles that repeat.
4 — Why can a WHERE id > last_seen polling cursor lose an event? Important
Answer
Answer: An earlier allocated ID can commit after a later one. The cursor can advance past a row that was invisible during the scan.
5 — Does an ownership-checked marker stop an expired relay from publishing? Good to know
Answer
Answer: No. It protects the database marker, while an external broker send can still complete. Ordering and consumer recovery must account for late duplicates.
6 — Why cannot the polling relay update published_at on a table used by EventRouter unchanged? Good to know
Answer
Answer: EventRouter expects INSERT events and treats UPDATEs as invalid. Choose a CDC lifecycle with connector progress and a separate cleanup policy.
7 — Why is Kafka flush success alone insufficient for the PHP adapter? Important
Answer
Answer: It says outstanding requests completed, including permanent failures. The delivery report for each record must also report success.
8 — What should happen if a Redis transaction appends one event and another command fails with WRONGTYPE? Important
Answer
Answer: Do not mark the SQL batch as fully published. Redis does not roll back the successful append, so retry stable IDs and expect duplicates.
9 — Which two retention periods must be coordinated with replay? Important
Answer
Answer: The retained publication/replay source and the consumer's dedup history; broker retention must also cover consumers that have not yet received the event.
10 — Why might more relay workers fail to reduce the oldest pending age? Important
Answer
Answer: A poison predecessor, one hot aggregate's serial order, broker saturation or insufficient recovery surplus can be the bottleneck. More concurrent claims do not remove it.
Glossary
| Term | Meaning |
|---|---|
| Transactional Outbox | Local commit of business state and durable publication intent |
| Dual write | Independent writes to two systems that can disagree after failure |
| Atomic boundary | The actual unit a transaction commits or rolls back together |
| Publication intent | Durable instruction to send a particular event |
| Aggregate | Business consistency unit whose transitions may need ordering |
Event ID / event_id | Stable identity of one logical event across retries |
Aggregate ID / aggregate_id | Identity used for routing and ordering scope |
Event type / type | Name of the public event contract |
| Payload | Saved content describing the committed transition |
| Headers | Event metadata such as trace context and schema version |
created_at | Time recorded with the event, not proof of global commit order |
available_at | Earliest database time at which polling may retry the row |
attempts / last_error | Retry count and bounded diagnostic information |
published_at | Relay marker that the configured acceptance check succeeded |
| Message relay | Process that moves durable intent to the broker |
| Polling Publisher | Relay that queries pending records |
| Transaction Log Tailing | Relay strategy that follows committed database log changes |
| CDC | Change Data Capture, used here to implement log-based relay |
| WAL | PostgreSQL write-ahead log read by logical capture |
| Replication slot | PostgreSQL capture position that can retain required WAL |
| Connector offset | Durable progress position used during CDC restart |
| Snapshot / resnapshot | Reading current source rows to initialise or rebuild capture |
| EventRouter / SMT | Debezium transformation mapping an outbox record into an event |
| Predicate | Connector filter selecting records to transform |
| INSERT-only | Event lifecycle with creation, not state-changing UPDATEs |
table.op.invalid.behavior | EventRouter policy for invalid outbox UPDATE operations |
route.by.field | Column used to choose the routed topic |
route.topic.replacement | Template for that topic name |
table.field.event.id | Router mapping for the event identity header |
table.field.event.key | Router mapping for the Kafka key |
table.field.event.payload | Router mapping for the event body |
table.field.event.timestamp | Optional mapping for the emitted event timestamp |
table.fields.additional.placement | Router mapping for extra header/envelope fields |
FOR UPDATE SKIP LOCKED | PostgreSQL locking scan that avoids waiting on other claimers |
| Partial index | Index containing only rows matching a predicate, such as pending events |
| Claim | Temporary assignment of pending work to a relay |
Lease / locked_until | Claim validity interval measured by the database |
Owner / locked_by | Token checked before changing a claimed row |
| Incarnation token | Fresh identity for one process lifetime or job invocation |
| Fencing | Resource-enforced rejection of operations from stale owners |
| StrictOrder | Sample predecessor guard over visible pending aggregate rows |
| Identity column | Sequence-backed local identifier; not transaction commit order |
| Watermark | Scan progress boundary; unsafe when based on uncommitted-ID assumptions |
| Head-of-line blocking | A predecessor prevents later work in its ordering scope |
| Partition key | Key selecting the destination's ordering/placement scope |
| At-least-once | Recovery may deliver the same logical event more than once |
| Idempotent consumer / inbox | Consumer dedup record committed with the business effect |
| Publisher confirm | RabbitMQ publisher acknowledgment of broker responsibility |
| Mandatory return | RabbitMQ report that a publication had no route |
acks=all / ISR | Kafka acknowledgment from the current in-sync replicas |
min.insync.replicas | Minimum ISR requirement used with Kafka all-ISR acknowledgments |
| Delivery report | Per-record producer completion result, including permanent failure |
withDrMsgCb | Laravel Kafka builder API attaching a delivery-report callback |
XADD | Redis command appending to a stream |
MULTI/EXEC | Redis transaction execution without runtime-error rollback |
IDMP | Redis 8.6+ bounded producer/idempotency-ID append deduplication |
MAXLEN | Stream trimming limit that can remove unread entries |
| Backoff / jitter | Increasing retry delay and randomisation to reduce retry synchronisation |
| Poison row / parking | Intent requiring operator policy rather than endless blind retry |
| Replay horizon | Maximum interval over which historical events may be resent |
| Oldest pending age | Age of the earliest unfulfilled publication intent |
| Recovery surplus | Healthy publish capacity minus ongoing event arrival rate |
after_commit / afterCommit | Laravel dispatch timing after transaction commit, not a durable intent record |
transactionLevel() | Laravel connection's current transaction nesting level |
ShouldBeUnique / UniqueFor | Scheduling deduplication and its lock lifetime |
| Horizon | Laravel Redis queue management; not an outbox correctness mechanism |
| 2PC | Distributed commit protocol that this local-transaction pattern does not require |
| Event sourcing | Domain state derived from retained events; a separate storage model |
References
- Chris Richardson: Transactional Outbox, Polling Publisher, Transaction Log Tailing.
- PostgreSQL: SELECT and locking clauses, sequence functions.
- Debezium: Outbox Event Router, PostgreSQL connector.
- RabbitMQ: Publisher confirms and consumer acknowledgments, amqp091-go channel implementation, php-amqplib channel implementation.
- Apache Kafka: Producer configuration; franz-go client documentation.
- Redis: XADD, transactions, persistence, go-redis client.
- Go PostgreSQL client: pgx.
- Laravel 13: Database, Query Builder, Eloquent, Queues, Scheduling, Horizon.
- Laravel RabbitMQ: package README. Laravel Kafka: README, builder, callback API, producer implementation.
- php-rdkafka: client README, delivery reports, flush.