Laravel makes background processing look simple.
You create a job, dispatch it, and let a queue worker handle the rest.
ProcessPayment::dispatch($payment);
For many applications, that's enough.
But as your system grows, background processing becomes more complicated.
What happens if a worker crashes halfway through a job? What if the same job runs twice? What if the database transaction commits, but the job never reaches the queue? What if an external API processes your request, but your application never receives the response?
These are not unusual edge cases. They are normal failure scenarios in distributed systems.
A reliable background processing system must account for them.
In this article, we'll go beyond Laravel's basic queue features and explore how to build background processing that can recover from failures without corrupting business data or repeating unwanted side effects.
1. Understand What a Queue Actually Guarantees
The first mistake is assuming that dispatching a job means it will execute exactly once.
It doesn't.
Most queue systems provide delivery and retry behavior that can result in a job being processed more than once.
Consider this scenario:
- A worker receives a job.
- The job updates a database record.
- The worker crashes before acknowledging successful completion.
- The queue considers the job unfinished.
- The job becomes available again.
- Another worker processes it.
The business operation may have already happened, even though the queue doesn't know that.
This is why we need to distinguish between two things:
- Message delivery: How the queue delivers a job to a worker.
- Business execution: What the application actually does while processing that job.
A queue can manage message delivery, retries, and acknowledgments. It cannot automatically guarantee that your business operation happens only once.
This leads to an important principle:
Design background jobs to tolerate repeated execution.
2. Idempotency: Make Repeated Execution Safe
Idempotency means that performing the same operation multiple times produces the same intended business result as performing it once.
Imagine a job that processes a payment.
A naive implementation might look like this:
class ProcessPayment implements ShouldQueue
{
public function __construct(
public Payment $payment,
) {}
public function handle(): void
{
$this->payment->update([
'status' => 'completed',
]);
// Update the user's balance.
}
}
What happens if the job runs twice?
The payment status may remain correct, but the balance could be credited twice.
The problem is that setting a status and applying a financial side effect are two different operations.
We need to protect the business operation itself.
For example, we can use a database transaction and a conditional state transition:
DB::transaction(function () {
$payment = Payment::query()
->whereKey($this->paymentId)
->lockForUpdate()
->firstOrFail();
if ($payment->status !== 'pending') {
return;
}
$payment->update([
'status' => 'completed',
]);
$payment->user->increment(
'balance',
$payment->amount
);
});
Now, if the job executes again after the payment has been completed, it does not credit the balance again.
This example assumes the payment state transition and balance update happen in the same database transaction.
For financial systems, an immutable ledger entry with a unique business reference is often a stronger design than directly modifying a balance. It gives you an auditable record and a database-enforced way to prevent duplicate credits.
For example:
Schema::create('ledger_entries', function (Blueprint $table) {
$table->id();
$table->foreignId('payment_id');
$table->string('type');
$table->decimal('amount', 20, 8);
$table->unique(['payment_id', 'type']);
$table->timestamps();
});
The unique constraint provides a final line of defense against duplicate ledger entries.
The important point is that idempotency should be tied to the business operation, not merely the Laravel job ID.
A job can have a different queue identifier every time it is dispatched. The business operation should still have the same stable identity.
3. Prevent Duplicate Dispatches and Concurrent Execution
Laravel provides two useful mechanisms that solve different problems.
ShouldBeUnique
Sometimes the same job is dispatched multiple times before the existing job has finished.
For example, several requests may trigger a search index update for the same product.
You can prevent duplicate dispatches using ShouldBeUnique:
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
class UpdateProductIndex implements ShouldQueue, ShouldBeUnique
{
public function __construct(
public int $productId,
) {}
public function uniqueId(): string
{
return "product-index:{$this->productId}";
}
public function handle(): void
{
// Update the product search index.
}
}
Laravel uses a cache lock to determine whether another job with the same unique key is already active.
This prevents additional matching jobs from being dispatched while the existing unique job is outstanding.
WithoutOverlapping
But what if multiple jobs have already been dispatched and you only want to prevent them from executing simultaneously?
That's where WithoutOverlapping comes in:
use Illuminate\Queue\Middleware\WithoutOverlapping;
class UpdateProductIndex implements ShouldQueue
{
public function __construct(
public int $productId,
) {}
public function middleware(): array
{
return [
(new WithoutOverlapping(
"product-index:{$this->productId}"
))->expireAfter(180),
];
}
public function handle(): void
{
// Update the product search index.
}
}
The lock prevents overlapping execution for the same key.
The expiration is important because a process may terminate unexpectedly without releasing its lock.
However, choosing an expiration value requires care. If the lock expires while the original process is still running, another worker may acquire it and start processing the same resource.
Also remember that releasing an overlapping job consumes an attempt. Your retry configuration must account for this.
The Difference
| Mechanism | What it protects |
|---|---|
ShouldBeUnique |
Duplicate job dispatch |
WithoutOverlapping |
Concurrent execution |
| Idempotency | Duplicate business side effects |
These mechanisms complement each other. None replaces the others.
4. Database Transactions and the After-Commit Problem
Consider a common Laravel workflow:
DB::transaction(function () use ($order) {
$order->update([
'status' => 'paid',
]);
SendOrderConfirmation::dispatch($order);
});
There is a potential race condition here.
The queue worker might pick up the job before the database transaction commits.
The job may try to read an order that is not yet visible to it, or it may see outdated data.
Laravel provides a solution:
SendOrderConfirmation::dispatch($order)->afterCommit();
Alternatively, you can configure the queue connection:
'redis' => [
'driver' => 'redis',
// ...
'after_commit' => true,
],
With this configuration, Laravel waits until open database transactions have committed before dispatching queued jobs.
If the transaction rolls back, the queued jobs are discarded.
This solves the problem of a worker processing data before it becomes visible.
But there is another problem.
What If the Database Commits but Dispatching Fails?
Imagine this sequence:
- The application updates the order.
- The database transaction commits successfully.
- The application attempts to dispatch the job.
- Redis is temporarily unavailable.
- The job is never dispatched.
Your order is now marked as paid, but the confirmation workflow was never started.
afterCommit() solves transaction visibility. It does not make the database commit and queue publication one atomic operation.
For workflows where losing a job is unacceptable, we need a stronger pattern.
5. The Transactional Outbox Pattern
The Transactional Outbox Pattern solves the problem of coordinating database changes with message publication.
Instead of writing to the database and directly publishing a message to the queue, we write both the business change and an event record in the same database transaction.
For example:
DB::transaction(function () use ($order) {
$order->update([
'status' => 'paid',
]);
OutboxMessage::create([
'event_id' => (string) Str::uuid(),
'event_type' => 'order.paid',
'aggregate_id' => $order->id,
'payload' => [
'order_id' => $order->id,
],
'published_at' => null,
]);
});
Both records are committed together.
If the transaction fails, neither change is committed.
If it succeeds, the outbox message is safely stored in the database.
A separate publisher process reads unpublished messages and dispatches them:
OutboxMessage::query()
->whereNull('published_at')
->orderBy('id')
->chunkById(100, function ($messages) {
foreach ($messages as $message) {
PublishOutboxMessage::dispatch($message->id);
}
});
The publisher is responsible for making sure that stored messages eventually reach the queue.
However, there is an important detail: publishing and marking a message as published are not atomic across the database and the queue.
If the publisher dispatches a message and crashes before updating published_at, it may dispatch the same message again.
That's expected.
The consumer must be idempotent, and the outbox message needs a stable event identifier.
A production implementation should also consider:
- Claiming messages safely when multiple publishers run.
- Tracking publication attempts and errors.
- Handling messages that remain unpublished for too long.
- Avoiding long-running database transactions.
- Retrying failed publication without losing the original event.
The outbox pattern does not magically provide exactly-once delivery.
It provides durable event storage and a reliable mechanism
Top comments (0)