There is a common problem in backend systems that is easy to overlook:
You update a database record, then dispatch a job or publish an event so another part of your system can process it.
Both operations succeed most of the time.
But what happens when the database commits successfully and the application crashes before publishing the event?
Your database contains the new state, but the message was never delivered.
This is not a database transaction problem. It is a dual-write problem.
In this article, we'll explore the Transactional Outbox Pattern and implement it in Laravel 13 using a practical order-processing example.
We'll cover:
- Why database transactions are not enough
- Why
afterCommit()does not fully solve the problem - How the Transactional Outbox Pattern works
- Designing an outbox table
- Writing business data and events atomically
- Building and running a reliable publisher
- Handling retries and duplicate messages
- Making consumers idempotent
- Operational considerations and trade-offs
1. The Dual-Write Problem
Imagine a user places an order.
Your application needs to:
- Create the order in the database.
- Publish an
OrderCreatedevent to a queue or message broker.
A typical implementation might look like this:
DB::transaction(function () use ($data) { $order = Order::create($data); ProcessOrder::dispatch($order->id); }); At first glance, this looks reasonable.
However, the database transaction and queue dispatch are two independent operations. Here, the job is pushed to the queue before the transaction commits.
Consider these scenarios:
| Scenario | Database | Queue |
|---|---|---|
| Normal execution | Committed | Message published |
| Dispatch fails | Rolled back | Not published |
| Commit fails after dispatch | Rolled back | Message published (orphan job) |
| Worker picks up job before commit | Not yet committed | Message processed too early |
The third scenario is particularly dangerous.
The job is already on the queue, but the order it refers to was never committed. A worker will process a job for an order that does not exist.
The fourth scenario introduces another problem: a worker might receive the job before the transaction commits and fail to find the order, even though it will exist a moment later.
A database transaction cannot atomically commit changes in your database and publish a message to an independent messaging system.
That's the core problem.
2. Why afterCommit() Is Not Enough
Laravel provides a useful mechanism for dispatching jobs after a database transaction commits.
You can configure your queue connection:
'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => env('REDIS_QUEUE', 'default'), 'after_commit' => true, ], Or specify it for an individual job:
ProcessOrder::dispatch($order->id)->afterCommit(); This prevents a worker from processing the job before the transaction commits.
It also ensures that jobs dispatched within a transaction are discarded if that transaction rolls back. That fixes the orphan job scenario.
But it moves the failure window instead of removing it:
1. Database transaction commits. 2. Application process crashes, or the queue is unreachable. 3. Job is never published. afterCommit() controls when dispatching happens. It does not make the database commit and message publishing one atomic operation.
For applications where losing an event is unacceptable, we need a stronger approach.
A note on the
databasequeue driverIf you use Laravel's
databasequeue driver, thejobstable lives on the same connection as your business data, andafter_commitis disabled, a dispatch inside the transaction becomes part of that transaction. The job row is committed or rolled back together with the order.In that setup, the
jobstable already behaves like a simple outbox. The pattern in this article becomes necessary when the destination is an independent system, such as Redis, RabbitMQ, Kafka, SQS, or another service.
3. Introducing the Transactional Outbox Pattern
The Transactional Outbox Pattern solves the dual-write problem by storing the event in the same database transaction as the business operation.
Instead of immediately publishing the event, we save it in an outbox_messages table.
A separate process reads these records and publishes them to the message broker.
The important part is that the business data and the outbox message are committed together.
Application | | Database Transaction | +------+------+ | | Create Order Insert Event | | +------+------+ | COMMIT | | Outbox Publisher | | Message Broker | | Consumer Now consider the previous failure scenario.
If the application crashes after the transaction commits, the outbox record still exists.
The publisher can find it later and retry publishing.
If the transaction rolls back, both the order and the outbox record are rolled back.
This gives us an important guarantee:
A committed business operation cannot exist without its corresponding outbox record, provided both writes use the same database transaction and connection.
It does not guarantee that the message is delivered exactly once. We'll address that later.
4. Designing the Outbox Table
Let's start with a migration.
Schema::create('outbox_messages', function (Blueprint $table) { $table->id(); $table->uuid('event_id')->unique(); $table->string('aggregate_type'); $table->string('aggregate_id'); $table->string('event_type'); $table->json('payload'); $table->timestamp('available_at'); $table->timestamp('published_at')->nullable(); $table->timestamp('claimed_until')->nullable(); $table->uuid('lease_token')->nullable(); $table->unsignedInteger('claim_attempts')->default(0); $table->text('last_error')->nullable(); $table->timestamps(); $table->index([ 'published_at', 'available_at', 'id', ]); }); Let's understand the important columns.
| Column | Purpose |
|---|---|
event_id | Stable, unique identifier for the event |
aggregate_type | Entity type, such as order |
aggregate_id | Identifier of the related entity |
event_type | Event name, such as OrderCreated |
payload | Event data |
available_at | Earliest time the publisher can retry |
published_at | Indicates successful publishing |
claimed_until | Expiration time of a publisher's claim |
lease_token | Identifies the publisher that currently owns the claim |
claim_attempts | Number of times the record has been claimed |
last_error | Most recent publishing error |
Why do we need both event_id and the database id?
The database ID identifies the outbox record internally.
The event_id is a stable identifier that travels with the message. Consumers can use it to detect duplicate deliveries.
The claim-related columns allow multiple publisher processes to work concurrently without claiming the same record at the same time.
Notice that claim_attempts counts claims, not confirmed publishing attempts. A publisher can crash after claiming an event but before sending it.
The composite index matches the publisher's main query: unpublished events that are available, in ID order. It is a starting point. The actual query plan should be checked against your database and workload.
5. Writing Business Data and Events Atomically
Now let's implement the actual business operation.
The order and its event must be inserted inside the same transaction.
use App\Models\Order; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; final class CreateOrderAction { public function execute(array $data): Order { return DB::transaction(function () use ($data) { $order = Order::create($data); DB::table('outbox_messages')->insert([ 'event_id' => (string) Str::uuid(), 'aggregate_type' => 'order', 'aggregate_id' => (string) $order->id, 'event_type' => 'OrderCreated', 'payload' => json_encode([ 'order_id' => $order->id, 'user_id' => $order->user_id, 'total' => $order->total, ], JSON_THROW_ON_ERROR), 'available_at' => now(), 'created_at' => now(), 'updated_at' => now(), ]); return $order; }); } } There are two important details here.
First: both operations must use the same database transaction and connection.
If inserting the outbox record fails, the order creation is rolled back as well.
Second: the event identifier is generated once and stored with the event.
That identifier must remain unchanged across publishing retries. It will be essential when handling duplicate messages.
At this point, we have solved the database consistency problem.
But the event is still sitting in the outbox table.
We need a publisher.
6. Building an Outbox Publisher
The publisher is a background process responsible for:
- Finding unpublished events.
- Claiming a batch of events.
- Publishing them to the message broker.
- Marking successfully published events.
- Scheduling failed events for retry.
A naive implementation might simply query unpublished records and publish them.
However, running multiple publisher processes introduces another race condition:
Publisher A reads Event 100. Publisher B reads Event 100. Publisher A publishes Event 100. Publisher B publishes Event 100. We need a claiming mechanism.
Claiming events safely
We'll use database row locking with FOR UPDATE SKIP LOCKED.
Laravel's query builder allows custom lock clauses through lock().
The following example targets PostgreSQL and MySQL versions that support SKIP LOCKED (using InnoDB on MySQL). Other database engines may require a different claiming strategy.
use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; final class OutboxPublisher { private function claimBatch(): array { return DB::transaction(function () { $now = now(); $events = DB::table('outbox_messages') ->whereNull('published_at') ->where('available_at', '<=', $now) ->where(function ($query) use ($now) { $query->whereNull('claimed_until') ->orWhere('claimed_until', '<=', $now); }) ->orderBy('id') ->limit(20) ->lock('for update skip locked') ->get(); if ($events->isEmpty()) { return []; } $leaseToken = (string) Str::uuid(); DB::table('outbox_messages') ->whereIn('id', $events->pluck('id')) ->update([ 'lease_token' => $leaseToken, 'claimed_until' => now()->addMinutes(2), 'claim_attempts' => DB::raw('claim_attempts + 1'), 'updated_at' => now(), ]); return $events->map(fn ($event) => [ 'id' => $event->id, 'event_id' => $event->event_id, 'event_type' => $event->event_type, 'payload' => $event->payload, 'claim_attempts' => $event->claim_attempts + 1, 'lease_token' => $leaseToken, ])->all(); }); } } Why SKIP LOCKED?
When one publisher locks a row, another publisher skips that row instead of waiting for the lock to be released.
This allows multiple publishers to claim different batches concurrently.
The transaction is deliberately short.
We claim the records and commit before making any network requests. We should not hold database row locks while waiting for a message broker.
The batch size and lease duration must be chosen together.
For example, claiming a large batch and publishing each event sequentially can cause later events to reach lease expiration before they are processed.
For slower transports or longer-running publishing operations, use smaller batches or implement lease renewal.
The lease token prevents an old publisher from updating a record after another publisher has claimed it. It does not prevent duplicate publishing if the original publisher continues after its lease expires.
The transport abstraction
The publisher should not care which broker it talks to. Let's define a small contract:
interface EventTransport { /** * Must only return after the broker has durably accepted the message. * * @throws Throwable When the message could not be published. */ public function publish(string $eventId, string $eventType, array $payload): void; } The transport should only report success after receiving the broker acknowledgement required by your durability guarantees.
Many Laravel applications will publish to their own queue. Here is a transport that pushes a job onto a Redis queue connection:
use Illuminate\Support\Facades\Queue; final class LaravelQueueTransport implements EventTransport { public function publish(string $eventId, string $eventType, array $payload): void { Queue::connection('redis')->push( new HandleOutboxEvent($eventId, $eventType, $payload), '', 'events', ); } } And the job that routes the event to its consumer:
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; final class HandleOutboxEvent implements ShouldQueue { use Queueable; public function __construct( public string $eventId, public string $eventType, public array $payload, ) {} public function handle(): void { $event = [ 'event_id' => $this->eventId, 'payload' => $this->payload, ]; match ($this->eventType) { 'OrderCreated' => app(OrderCreatedConsumer::class)->handle($event), }; } } Bind the transport in a service provider:
$this->app->bind(EventTransport::class, LaravelQueueTransport::class); Keep in mind that a successful push to Redis is only as durable as your Redis configuration. Without persistence (such as AOF), a Redis restart can lose messages that the outbox already marked as published. If that matters, configure persistence or use a broker with durable acknowledgements.
Publishing the claimed events
This method lives in the same OutboxPublisher class. It returns the number of claimed events, so the process running it knows when the outbox is empty.
use Illuminate\Support\Facades\DB; use Throwable; public function publishBatch(EventTransport $transport): int { $events = $this->claimBatch(); foreach ($events as $event) { try { $transport->publish( eventId: $event['event_id'], eventType: $event['event_type'], payload: json_decode( $event['payload'], true, flags: JSON_THROW_ON_ERROR ), ); } catch (Throwable $exception) { $delay = min( 300, 2 ** min($event['claim_attempts'], 9) ); DB::table('outbox_messages') ->where('id', $event['id']) ->where('lease_token', $event['lease_token']) ->whereNull('published_at') ->update([ 'available_at' => now()->addSeconds($delay), 'claimed_until' => null, 'lease_token' => null, 'last_error' => mb_substr( $exception->getMessage(), 0, 2000 ), 'updated_at' => now(), ]); continue; } DB::table('outbox_messages') ->where('id', $event['id']) ->where('lease_token', $event['lease_token']) ->whereNull('published_at') ->update([ 'published_at' => now(), 'claimed_until' => null, 'lease_token' => null, 'updated_at' => now(), ]); } return count($events); } The publishing operation and the database update are deliberately separate.
If publishing succeeds but updating published_at fails, the event may be published again after its lease expires.
That is expected.
The lease token also ensures that an old publisher cannot mark a record as published after another publisher has acquired it.
The retry delay uses exponential backoff with a maximum delay.
For example:
Attempt 1: 2 seconds Attempt 2: 4 seconds Attempt 3: 8 seconds Attempt 4: 16 seconds ... Attempt 8: 256 seconds Attempt 9 and later: 300 seconds (maximum) In a production implementation, consider the following additional requirements:
- Sanitize error messages before storing them. Exception messages may contain sensitive information.
- Alert on records with unusually high claim counts.
- Monitor expired claims and repeated failures.
- Define a maximum retry policy and an explicit manual recovery or dead-letter process.
- Ensure the lease duration is appropriate for the transport's expected latency.
A failed database update after successful publishing must not be treated as proof that publishing failed. The broker may already have accepted the message.
Running the publisher
The publisher needs to run continuously. A simple approach is an Artisan command that loops, sleeps when the outbox is empty, and exits after a while so a process manager can restart it with a fresh memory footprint.
use Illuminate\Console\Command; final class PublishOutboxCommand extends Command { protected $signature = 'outbox:publish {--sleep=1 : Seconds to wait when the outbox is empty} {--max-time=3600 : Seconds to run before exiting}'; protected $description = 'Publish pending outbox messages'; public function handle(OutboxPublisher $publisher, EventTransport $transport): void { $stopAt = now()->addSeconds((int) $this->option('max-time')); while (now()->lessThan($stopAt)) { if ($publisher->publishBatch($transport) === 0) { sleep((int) $this->option('sleep')); } } } } Run it under Supervisor (or your platform's equivalent), just like queue:work:
[program:outbox-publisher] command=php /var/www/app/artisan outbox:publish autostart=true autorestart=true numprocs=2 process_name=%(program_name)s_%(process_num)02d Thanks to SKIP LOCKED and leases, running more than one process is safe.
7. The Duplicate Message Problem
There is still an important failure scenario.
Imagine this sequence:
1. Publisher sends the event. 2. Message broker accepts the event. 3. Publisher crashes. 4. published_at is never updated. 5. The lease expires. 6. Another publisher sends the same event again. The consumer receives the same event twice.
This is expected behavior.
The Transactional Outbox Pattern provides reliable, retryable publishing, but it does not provide exactly-once delivery.
In practice, we design the system around at-least-once delivery.
That means consumers must be prepared to receive duplicate messages.
This is where idempotency becomes essential.
8. Building an Idempotent Consumer
A consumer should be able to process the same event multiple times without applying the business operation more than once.
One common solution is an inbox or processed-messages table.
Schema::create('processed_messages', function (Blueprint $table) { $table->id(); $table->uuid('event_id')Source:https://dev.to/raadparsa/the-transactional-outbox-pattern-in-laravel-reliable-event-publishing-across-database-and-queue-5a1oRelated posts

MySQL 설치 및 사용법: Yum 저장소와 기본 SQL 시작하기

Designing a WhatsApp-Style Chat on GCP: Bigtable Row Keys Do the Heavy Lifting

503s During a Sale: How I Would Find the Cause With GCP Monitoring
SQLite Foreign Keys Let This RAG Eval Cite the Wrong Snapshot
