KodingKaro

Laravel Development

Your Laravel Queue Job Runs Twice? Prevent Duplicate Jobs Before They Break Your Application

Laravel queues make background processing easier, but duplicate job execution can lead to repeated emails, duplicate records, and even double payment attempts. Learn how to use unique jobs, job middleware, database constraints, and idempotency to make your queue system more reliable.

5 min read
Your Laravel Queue Job Runs Twice? Prevent Duplicate Jobs Before They Break Your Application

Laravel Development

Your Laravel Queue Job Runs Twice? Prevent Duplicate Jobs Before They Break Your Application

Queues make Laravel applications faster and more scalable, but duplicate jobs can send repeated emails, process the same payment workflow twice, or create inconsistent data. Learn how to prevent duplicate dispatches and make critical jobs safe to retry.

Why does a Laravel queue job run twice?

Imagine a user places an order. Your application dispatches a job to send an order confirmation email. The user clicks the submit button twice, or an API request is retried, and the application dispatches the same job again.

The queue worker may then process both jobs. The customer receives two emails, or your application performs the same business operation more than once.

Duplicate execution can also happen because workers retry failed jobs, messages become available again after a timeout, or multiple requests dispatch equivalent work concurrently.

The important distinction is that preventing duplicate dispatches, preventing overlapping execution, and making an operation safe to repeat are three different problems.

1. Create a queue job

For example, generate a job for processing an order:

php artisan make:job ProcessOrder

A simplified job might look like this:

namespace App\Jobs;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessOrder implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public int $orderId
    ) {}

    public function handle(): void
    {
        $order = Order::findOrFail($this->orderId);

        // Process the order.
    }
}

Dispatch it from your application:

ProcessOrder::dispatch($order->id);

2. Use ShouldBeUnique to prevent duplicate dispatches

Laravel provides the ShouldBeUnique contract. It prevents a new job from being dispatched while another job with the same unique identity is already queued or being processed, subject to the uniqueness lock.

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;

class ProcessOrder implements ShouldQueue, ShouldBeUnique
{
    public int $uniqueFor = 3600;

    public function __construct(
        public int $orderId
    ) {}

    public function uniqueId(): string
    {
        return (string) $this->orderId;
    }

    public function handle(): void
    {
        // Process the order.
    }
}

In this example, jobs for the same order share the same unique ID. The uniqueness lock expires after the configured period. Choose a duration that fits the job's expected lifecycle and configure a shared cache store when multiple application servers or workers need to coordinate.

3. Prevent overlapping execution with WithoutOverlapping

Sometimes you want jobs to be allowed in the queue but never run concurrently for the same resource. Laravel's WithoutOverlapping middleware can help with that.

use Illuminate\Queue\Middleware\WithoutOverlapping;

public function middleware(): array
{
    return [
        (new WithoutOverlapping($this->orderId))
            ->expireAfter(180)
            ->releaseAfter(10),
    ];
}

The lock prevents another job using the same key from overlapping with the current execution. A conflicting job can be released and tried again later. Set the expiration carefully so a crashed worker does not leave a lock in place indefinitely, while also allowing enough time for normal processing.

4. Make jobs idempotent

Unique dispatching and overlap locks are useful, but they do not guarantee that a business operation happens exactly once. A worker can complete an external action and crash before acknowledging the job. The queue may deliver the job again.

This is why important jobs should be idempotent. An idempotent operation can be repeated without causing the business result to happen more than once.

For example, store a processing status and check it before performing an operation:

public function handle(): void
{
    $order = Order::findOrFail($this->orderId);

    if ($order->status === 'completed') {
        return;
    }

    // Perform the required work.

    $order->update([
        'status' => 'completed',
    ]);
}

This is a useful starting point, but for concurrent workers, the read-check-update sequence must be protected. Use database transactions, row locks where appropriate, and database constraints to enforce the business rule safely.

5. Use database constraints for critical operations

Application-level checks alone can fail when two requests arrive at almost the same time. A database unique constraint provides a stronger guarantee for records that must be unique.

For example, if each order should have one processing record, enforce that rule in the database:

Schema::create('order_processings', function (Blueprint $table) {
    $table->id();
    $table->foreignId('order_id')->constrained();
    $table->string('status');
    $table->timestamps();

    $table->unique('order_id');
});

Your job can then create the record using an approach that handles an existing unique record safely. For payments and other external side effects, also use the provider's idempotency mechanism when available.

6. Configure retries and timeouts carefully

Queue retries are important for reliability, but incorrect timeout settings can contribute to overlapping execution. Review your worker timeout, job timeout, retry settings, and the queue connection's retry-after configuration.

public int $tries = 3;

public int $timeout = 120;

Make sure the worker timeout is configured consistently with the queue connection's retry-after value. The retry-after period should be longer than the maximum worker execution time, with a sensible safety margin. Exact settings depend on the queue driver and deployment.

Run workers with an appropriate timeout, for example:

php artisan queue:work --tries=3 --timeout=120

In production, manage workers with a process manager such as Supervisor or your hosting platform's supported service manager.

7. Monitor failed jobs

Do not assume that every queued job will complete successfully. Laravel provides a failed jobs table and commands to inspect and retry failed work.

php artisan queue:failed
php artisan queue:retry all

Use logs and monitoring to identify repeated failures. Before retrying a job manually, confirm that its operations are safe to repeat.

Final thoughts

Duplicate queue execution is not just a queue configuration problem. It is a reliability problem that needs to be handled at multiple levels.

Use ShouldBeUnique to reduce duplicate dispatches, WithoutOverlapping to prevent concurrent processing for the same resource, and database constraints plus idempotent logic to protect important business operations.

Build queue jobs assuming they may run again. That mindset makes your Laravel application safer, more predictable, and easier to scale.