Skip to content

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 forGo to
Guarantees and failure windows in one glanceEverything in one minute
Why publishing before or after COMMIT both failWhy it exists
The transaction boundary and the recordAtomic commit, Outbox record
Polling with locks or leasesPolling, Lease ownership
What “ordered” really requiresOrdering
Debezium EventRouter and INSERT-only tablesCDC relay
Duplicate publication and stable identitiesAt-least-once
Cleanup, poison rows and replayRetention
Exact settings and failure handlingMechanics, Solutions
The complete implementationsGo, Laravel, Broker differences
Choosing a relay and scaling itChoosing, Architecture
Fault experiments and quick recallLab, Cheat sheet, Self-check

Everything in one minute ​

PromiseWhat provides itWhat does not provide it
No committed order without a recorded event intentOrder and outbox INSERT use the same local transactionTwo independent commits, even on the same server
No event for a rolled-back orderRelay reads only committed outbox rowsPublishing while the order transaction is open
Event can survive application exitDatabase commit persists the outbox recordAn in-memory callback after commit
Delivery can resume after relay exitPending rows or CDC offsets are durableA process-local queue
Repeated sends do not repeat the consumer effectStable event ID plus transactional consumer dedupPublisher confirms alone
Per-aggregate business orderSerialized aggregate updates, an ordering key and disciplined relay/recoveryA global identity column alone
Progress during temporary broker failurePending storage, retries, capacity and an eventual recovery pathAn unconditional guarantee while dependencies remain unavailable
Crash happensDatabase stateBroker stateRecovery
Before producer COMMITBoth changes roll backNo publicationClient may retry the business command safely with its own idempotency key
After COMMIT, before relay claimBusiness row and pending intent existNo publicationRelay finds pending row
After claim, before sendRow is leased or lockedNo publicationLease expires or transaction lock releases
After send, before acknowledgmentPending intent existsUnknownRetry with the same event ID
After acknowledgment, before markingPending intent existsMessage acceptedRetry produces a possible duplicate
After successful markingPublished marker existsMessage accepted at configured durability boundaryConsumer processing is a separate responsibility
RelayReadsWrites backMain cost
Polling publisher with long transactionPending rows under row locksPublished marker in the same relay transactionDatabase connection and locks held through broker I/O
Polling publisher with leasePending rows in a short claim transactionOwnership-checked marker after publicationLease expiry, stale publishers and duplicate recovery
Transaction log tailing with CDCCommitted database logConnector offsets; no application published marker neededConnector, 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.

Two independent writes leave a crash gapCommit orderDatabaseProcess exitsEvent is missingPublish eventBrokerOne local commit records both factsOrder + outbox eventSame transactionRelay retriesStable event IDBroker acceptsConsumer dedupA durable intent survives application exit; delivery can still repeat.

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 requestTransactional outbox
Fewer moving partsA table/log path and a relay to operate
Broker failure may fail the requestRequests can commit until the pending-storage budget is exhausted
Database and publication can disagreeBusiness state and publication intent agree
Low publication latency when healthyPolling interval or CDC lag adds latency
An uncertain send needs recovery anywayRecovery 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.

text
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 A

Real 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.

DestinationProducer-side ruleDestination-side consequence
RabbitMQDo not publish from inside the business transactionRelay later waits for confirms and checks routing
KafkaA Kafka transaction cannot include the PostgreSQL commitRelay or CDC bridges the two systems
Redis StreamsMULTI/EXEC cannot include an external SQL transactionSQL 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.

sql
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.

text
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 key

Real 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.

FieldPurposeTrap
idLocal scan/claim identifierNot a global business sequence or commit timestamp
event_idStable identity across relay retriesGenerating it on every send defeats deduplication
aggregate_type, aggregate_idRouting and ordering scopeAn ID without its type may collide across domains
typeEvent contract nameA PHP class name couples readers to deployment internals
payloadCommitted event contentRebuilding from live tables changes history
headersTrace context and schema metadataDo not let arbitrary headers override event identity
created_atEvent recording timeWall-clock time is not a total order
available_at, attempts, last_errorPolling retry eligibility and diagnosticsLogging raw sensitive payloads in errors
locked_by, locked_untilTemporary claim owner and expiryLease ownership does not fence the broker
published_atRelay's accepted-publication markerNeither 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.

text
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 ID

Real 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 transactionWhat to awaitWhat a long wait holds
RabbitMQRouting result and publisher confirmSQL connection, row locks and an open transaction
KafkaProduce result for every recordThe same SQL resources through retries
Redis StreamsSuccessful command resultsSQL 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:

sql
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.

Short SQL transactions around a separate broker operation1. Claim + COMMITowner / lease from DB clock2. Publish + confirmNo SQL row lock held3. Mark publishedOnly if owner still matchesLease expires: another relaymay publish the same eventOwnership protects the SQL marker, not a stale publisher at the broker.

text
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 it

Real 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.

ConcernLease design responseRemaining limitation
Clock skew between relaysCompute claim and expiry from the database clockBroker deadlines and application shutdown use other clocks
Relay restartFresh random owner tokenReusing a token can authorize a stale marker
Partial batch publicationRelease or let lease expire, then resend stable IDsAlready accepted records can be duplicated
Graceful shutdownStop claims, allow bounded batch completion and bounded cleanupProcess kill can interrupt any stage
Mark affects fewer rows than claimedRecord lease-loss warning and investigateIncreasing 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.

text
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 watermark

Real scenarios: account balance transitions require an aggregate version; order state machines reject impossible transitions; independent customer aggregates can publish concurrently without a global order.

LayerRequired decisionLimit
ProducerLock the aggregate row or use optimistic version checks in the same transactionIdentity allocation before that discipline proves nothing
Pending-row relayStrictOrder blocks a committed row while an older committed row for that aggregate is pendingInvisible transactions and stale broker sends remain outside the guard
RabbitMQConsistent routing into an ordering scope; account for multiple publishers and redeliveryA queue does not reconstruct business versions
KafkaSame aggregate key within the same topic and partitioning schemeDifferent topics/partitions and producer sessions have no shared total order
Redis StreamsSame stream key, with controlled publication orderConcurrent relays determine the actual XADD arrival order
ConsumerStable event dedup; version/gap policy when applying transitionsA 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.

CDC variant: no polling published_at updatesOrder + outboxINSERTCOMMITPostgreSQLWAL + slotDebeziumOutbox EventRouterKafka recordkey: aggregate_idheader id: event_idDurable connector offsets + retained source logRestart can replay; consumers still deduplicatePredicate selects outbox records; INSERT-only lifecycle excludes marker UPDATEs.

text
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_id

Real 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 optionDefaultMapping for this chapter
table.field.event.ididevent_id, emitted in the id header
table.field.event.keyaggregateidaggregate_id, the Kafka record key
route.by.fieldaggregatetypeaggregate_type
route.topic.replacementoutbox.event.${routedByValue}One topic per aggregate type
table.field.event.payloadpayloadSaved JSON payload
table.field.event.timestampDebezium event timestampcreated_at if event recording time is wanted
table.fields.additional.placementNonetype:header:type
table.op.invalid.behaviorwarnfatal 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.

json
{
  "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.

text
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 effect

Real 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 featureHelps withDoes not cover
RabbitMQ publisher confirmsBroker responsibility for the publishConsumer completion or SQL marker atomicity
Kafka idempotent producerProducer protocol retries in its producer identity/sequence scopeA fresh application-level replay of the same event
Redis 8.6+ IDMPDuplicate append within retained producer/idempotency historyUnbounded 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.

text
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 horizon

Real 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.

ProblemSafe operational responseCost
Temporary broker outageRetry with backoff and jitter; alert on oldest pending ageBacklog consumes database space
Permanently invalid eventPreserve payload securely, classify, repair or park with an audit trailMay block an aggregate's later events
Manual replaySelect an explicit range, keep IDs, confirm dedup horizonHistorical duplicates reach consumers
Published-row growthBatched deletion or carefully designed partition retentionDeletion creates WAL and vacuum work
Broker retention too shortIncrease retention or catch consumers up before trimmingMore 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 structureSample choiceWhy it matters
PostgreSQL pending partial indexON outbox(id) WHERE published_at IS NULLKeeps claim scans focused on outstanding work
Aggregate pending index(aggregate_type, aggregate_id, id) for pending rowsSupports the predecessor guard
Batch sizeGo command uses 500; Laravel command defaults to 4Throughput versus lease time, memory and duplicate replay size
Idle poll200 msLatency/load trade-off, not a guaranteed delivery deadline
Lease30 s in examplesMust cover the permitted batch duration and marking
Retry eligibilityavailable_at from database now()A failed row does not spin on every poll
Per-row delaymin(2^attempts, 300) seconds, exponent capped firstAvoids arithmetic/interval overflow after many failures
Relay failure delayExponential full jitter with a configured capAvoids all relays hammering a failed dependency together
Claim ownerFresh random tokenPrevents a restarted worker inheriting stale ownership
Shard assignmentStable aggregate hash modulo configured shard countChanging shard count requires coordinated ownership transition
RabbitMQ publishPersistent message, mandatory routing, confirm modeA positive confirm can accompany an unroutable return
Kafka publishacks=all and idempotence; deployment controls min.insync.replicasAcceptance depends on replica configuration and failure policy
Redis publishXADD; optional bounded IDMP; retention explicitly sizedSuccess is not unconditional durable disk persistence
ShutdownStop claims; bounded in-flight batch and cleanupA 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 resultMeaning for this handoffAction
SQLSTATE 40001Serialization failureRetry the whole producer transaction; keep external side effects outside it
SQLSTATE 40P01Deadlock victimRetry the whole transaction with a bounded policy
SQLSTATE 23505Unique violationInterpret the violated constraint; not every collision means “already delivered”
SQLSTATE 57014Query cancelled/statement timeoutRoll back or reconcile the transaction outcome
RabbitMQ 312 NO_ROUTEMandatory publish had no matching queue routeKeep row pending; repair topology
RabbitMQ 406 PRECONDITION_FAILEDIncompatible declaration or protocol preconditionReplace the failed channel and fix configuration
Publisher nack / lost confirmBroker rejection or uncertain publicationDo not mark; retry stable IDs
Kafka NOT_ENOUGH_REPLICAS / timeoutRequired acceptance was not obtained or is uncertainKeep pending; check ISR and retry policy
Redis WRONGTYPEDestination key has another typeRepair the key/topology; preserve pending records
Redis OOM / NOREPLICASServer rejected the write under configured policyKeep pending and repair capacity/replication
Marked row count below claimed countClaim ownership changed or record was already markedAlert 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 ​

ProblemSolutionAdvantageLimitation
Event missing after successful requestWrite the outbox in the business transactionDurable recovery sourceApplication must consistently use that path
Event published for rolled-back dataRemove direct publish from the transactionConsumers see only committed intentAdds relay latency
Two relays claim the same pending rowRow lock during claim plus ownership tokenCoordinates normal concurrent claimsExpiry still allows duplicate publication
Slow broker exhausts SQL connectionsShort claim leasesFrees connections before network I/OMore ownership/recovery logic
Later aggregate event overtakes a failed predecessorPredecessor guard and aggregate writer serializationIsolates head-of-line blocking to an aggregateA poison event intentionally blocks that aggregate
CDC emits update warningsStop polling-marker updates on the CDC tableMatches EventRouter's INSERT-only lifecycleChoose a separate cleanup/progress policy
Relay marks after failed Kafka deliveryInspect delivery reports as well as flush completionRejects permanent per-message failureClient callback API must be verified
Tests pass but two DB connections break atomicityTest named-connection rollback explicitlyExercises the actual transaction boundaryRequires 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 ​

SituationRecommendationExtra decisionReason
Small service, modest event ratePolling publisherLock-based versus lease-based relayLowest infrastructure overhead
Broker I/O can stall and SQL connections are scarceLease-based pollingTransport deadlines and duplicate policyKeeps SQL transactions short
Existing Debezium platform and Kafka event backboneCDC Outbox Event RouterSlot, offsets, snapshots and cleanup ownershipReuses established capture operations
Strict order for one aggregateSerialize its writes and publication ownershipConsumer version/gap handlingBroker key alone is insufficient
Independent aggregates at high volumeSharded relay or CDC keyed partitioningSafe ownership rebalancePreserves useful parallelism
Atomic database update plus local background job onlyConsider Laravel database queue on the same connectionVerify actual insert transaction and after-commit settingsA separate generic event outbox may be unnecessary
External event contract consumed by several servicesExplicit event outboxEnvelope and retention ownershipLaravel job payload is not a public event schema
One database cannot contain business state and intentRedesign the atomic boundary or use a supported transaction mechanismReconciliation and failure semanticsA second database called “outbox” does not solve dual writes
Need permanent event history as domain truthEvaluate event sourcingDifferent storage and replay modelAn 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.

go
// 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.

go
// 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.

go
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.

go
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.

go
// 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.

go
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)
}
go
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")
	}
}
go
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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?php

// config/outbox.php — deploy one relay configuration per producer database.
return [
    'connection' => env('OUTBOX_DB_CONNECTION', env('DB_CONNECTION', 'pgsql')),
];
php
<?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
<?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
<?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
<?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
<?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
<?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
<?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.

go
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
<?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.

go
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
<?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.

go
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
<?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 LOCKED as 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.

text
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 transaction

Distributed 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× ​

StageChangeCheck before adding more workers
1×One relay, small batches, pending partial indexCorrect transaction and crash recovery
10×Multiple claimers across independent aggregatesDatabase connection pressure, oldest age, duplicate ratio
100×Coordinated aggregate/shard ownership or mature CDC platformOrdering during rebalance, WAL/offset capacity, retention budget
Recovery surgeTemporarily increase safe surplus throughputBroker 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.

  1. Prepare the producer schema. Apply Schema from go/after/outbox.go and create the illustrative business table below. Laravel users apply the migration and supply their host Order model instead.
sql
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.
  1. Rollback the producer. In terminal A, run the atomic-commit INSERTs but replace COMMIT with ROLLBACK. In terminal B, inspect both tables.
sql
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.
  1. 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.
sql
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.
  1. 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_id at the destination. For a broker-free illustration, the checked-in memory lab follows the same crash window but does not model strict ordering.
sh
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.
  1. 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.
sql
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.
  1. 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 fatal mode.

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 ​

BeliefReality
“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 ​

TopicRemember
Producer boundaryBusiness row and outbox row share one transaction and connection
PayloadCapture the event at the transition; do not rebuild from mutable state
IdentityKeep the same event ID across every resend
ClaimShort database transaction, bounded batch, owner token
LeaseDatabase time; unique incarnation; no broker fencing
MarkerOnly after the configured acceptance boundary
OrderingSerialize aggregate writes, key publication, handle gaps/late duplicates
PollingPending-state scan; never a naive increasing-ID watermark
CDCINSERT-only event lifecycle; filter other connector records
RabbitMQPersistent + mandatory + confirm + return handling
KafkaKey + acknowledged produce + delivery-report errors
RedisCheck each result; no rollback; explicit durability/retention
LaravelSame named connection; observers before commit; after_commit is different
OperationsOldest pending age, retry count, lease loss and recovery capacity
CleanupPublished retention and broker retention are separate budgets
ReplayExplicit scope, stable identities and sufficient consumer dedup retention

Self-check: questions & answers ​

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

1 — Why 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 ​

TermMeaning
Transactional OutboxLocal commit of business state and durable publication intent
Dual writeIndependent writes to two systems that can disagree after failure
Atomic boundaryThe actual unit a transaction commits or rolls back together
Publication intentDurable instruction to send a particular event
AggregateBusiness consistency unit whose transitions may need ordering
Event ID / event_idStable identity of one logical event across retries
Aggregate ID / aggregate_idIdentity used for routing and ordering scope
Event type / typeName of the public event contract
PayloadSaved content describing the committed transition
HeadersEvent metadata such as trace context and schema version
created_atTime recorded with the event, not proof of global commit order
available_atEarliest database time at which polling may retry the row
attempts / last_errorRetry count and bounded diagnostic information
published_atRelay marker that the configured acceptance check succeeded
Message relayProcess that moves durable intent to the broker
Polling PublisherRelay that queries pending records
Transaction Log TailingRelay strategy that follows committed database log changes
CDCChange Data Capture, used here to implement log-based relay
WALPostgreSQL write-ahead log read by logical capture
Replication slotPostgreSQL capture position that can retain required WAL
Connector offsetDurable progress position used during CDC restart
Snapshot / resnapshotReading current source rows to initialise or rebuild capture
EventRouter / SMTDebezium transformation mapping an outbox record into an event
PredicateConnector filter selecting records to transform
INSERT-onlyEvent lifecycle with creation, not state-changing UPDATEs
table.op.invalid.behaviorEventRouter policy for invalid outbox UPDATE operations
route.by.fieldColumn used to choose the routed topic
route.topic.replacementTemplate for that topic name
table.field.event.idRouter mapping for the event identity header
table.field.event.keyRouter mapping for the Kafka key
table.field.event.payloadRouter mapping for the event body
table.field.event.timestampOptional mapping for the emitted event timestamp
table.fields.additional.placementRouter mapping for extra header/envelope fields
FOR UPDATE SKIP LOCKEDPostgreSQL locking scan that avoids waiting on other claimers
Partial indexIndex containing only rows matching a predicate, such as pending events
ClaimTemporary assignment of pending work to a relay
Lease / locked_untilClaim validity interval measured by the database
Owner / locked_byToken checked before changing a claimed row
Incarnation tokenFresh identity for one process lifetime or job invocation
FencingResource-enforced rejection of operations from stale owners
StrictOrderSample predecessor guard over visible pending aggregate rows
Identity columnSequence-backed local identifier; not transaction commit order
WatermarkScan progress boundary; unsafe when based on uncommitted-ID assumptions
Head-of-line blockingA predecessor prevents later work in its ordering scope
Partition keyKey selecting the destination's ordering/placement scope
At-least-onceRecovery may deliver the same logical event more than once
Idempotent consumer / inboxConsumer dedup record committed with the business effect
Publisher confirmRabbitMQ publisher acknowledgment of broker responsibility
Mandatory returnRabbitMQ report that a publication had no route
acks=all / ISRKafka acknowledgment from the current in-sync replicas
min.insync.replicasMinimum ISR requirement used with Kafka all-ISR acknowledgments
Delivery reportPer-record producer completion result, including permanent failure
withDrMsgCbLaravel Kafka builder API attaching a delivery-report callback
XADDRedis command appending to a stream
MULTI/EXECRedis transaction execution without runtime-error rollback
IDMPRedis 8.6+ bounded producer/idempotency-ID append deduplication
MAXLENStream trimming limit that can remove unread entries
Backoff / jitterIncreasing retry delay and randomisation to reduce retry synchronisation
Poison row / parkingIntent requiring operator policy rather than endless blind retry
Replay horizonMaximum interval over which historical events may be resent
Oldest pending ageAge of the earliest unfulfilled publication intent
Recovery surplusHealthy publish capacity minus ongoing event arrival rate
after_commit / afterCommitLaravel dispatch timing after transaction commit, not a durable intent record
transactionLevel()Laravel connection's current transaction nesting level
ShouldBeUnique / UniqueForScheduling deduplication and its lock lifetime
HorizonLaravel Redis queue management; not an outbox correctness mechanism
2PCDistributed commit protocol that this local-transaction pattern does not require
Event sourcingDomain state derived from retained events; a separate storage model

References ​

Built by Morteza Negahi