Connect a database change to a reliable side effect
Use an outbox when a transaction must lead to a message.
See the dual-write gap
Saving an order and then publishing an event are two separate systems. A crash between them leaves an order with no notification. Publishing first has the opposite failure: an event about an order that rolls back. A database transaction cannot atomically commit an external message broker call.
Record intent with the data
In one transaction, write the order and an outbox row describing the event. A worker later reads unsent rows, publishes them, and marks them delivered. The worker may publish twice if it crashes before marking success, so consumers still need an idempotency key.
DB::transaction(function () use ($order, $event) {
$order->save();
OutboxMessage::create(['event_id' => $event->id, 'payload' => $event->json]);
});
Operate the queue
Monitor outbox age and repeated failures. Keep payloads small and avoid unnecessary personal data. Test a rollback, a worker crash after publish, and a duplicate consumer delivery. The design succeeds when the business record and the intent to notify remain consistent, even if delivery is delayed.
Check your understanding
Does an outbox guarantee a consumer sees an event only once?
Show explanation
No. It keeps data and delivery intent together; consumers must still handle duplicate publication safely.
You can read for free. Create an account to save your progress.
← Previous lesson: Page large results with the right index Next lesson: Verify webhooks and test failure paths →Put this lesson into practice
A practice activity at this level in the same module.
Try: Diagnose and remove an N+1 queryFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.