Skip to content

Expert Answers to Your Magento, Shopify & Shopware Questions

Vendor-neutral, engineer-written explanations. Clear definitions first, then practical steps with real examples — no fluff.

Stagebit builds and maintains stores on Magento, Adobe Commerce, Shopify, Shopware, and Laravel, and this library holds the questions our own engineers get asked most often on each platform.

How do I handle idempotent webhook processing in Laravel?

SB
Written by Stagebit Engineering Team
Updated November 2026 7 min read Verified by engineers

Webhook providers can send the same event more than once, so a production Laravel endpoint will see duplicates sooner or later. Idempotent webhook processing means the second delivery changes nothing. In Laravel, the database decides which delivery came first. The real work then runs in a queued job that can safely run again.

Quick answer

Verify the signature, then insert the provider’s event ID into a table with a unique index on provider and event_id. If the insert throws UniqueConstraintViolationException, return 200 and stop. Otherwise, queue a job that skips events with processed_at set and writes its changes inside one transaction. For Stripe, use the event id, and for Shopify, use the X-Shopify-Webhook-Id header.

Why does the same webhook arrive more than once?

Providers resend any delivery your endpoint does not acknowledge in time. Stripe documents that an endpoint may receive the same event more than once. Stripe also retries failed deliveries for up to three days in live mode. Shopify says the same. It gives your endpoint five seconds to respond, then retries up to 8 times over 4 hours.

Your own stack causes duplicates too. A slow query pushes the response past the timeout, or a deploy restarts PHP-FPM mid-request. The provider sees a failure and resends, even though your code may have finished the work. Duplicate webhooks are normal traffic, so webhook idempotency belongs in the design of your first endpoint.

The same failure can lead to a repeated business action. Picture a paid-order webhook that marks an order paid and sends a confirmation email. A second delivery could create a second payment record or send a second email. The rest of this page is about preventing that.

How to make Laravel webhook processing idempotent

Step 1: Verify the signature first

Check the provider’s signature before you touch the database. Otherwise anyone who finds the URL can fill your event table with forged IDs. Stripe sends a Stripe-Signature header, and Shopify sends X-Shopify-Hmac-SHA256. Both providers sign the raw request body, which you can read with $request->getContent().

Use the provider’s official library for the check. This Stripe example comes from the pattern in Stripe’s PHP documentation, with webhook_secret as a config key you define yourself.

try {
    $event = \Stripe\Webhook::constructEvent(
        $request->getContent(),
        $request->header('Stripe-Signature'),
        config('services.stripe.webhook_secret')
    );
} catch (\UnexpectedValueException | \Stripe\Exception\SignatureVerificationException $e) {
    abort(400);
}

A route middleware can hold this check if you want it out of the controller.

Step 2: Create a table with a unique key

Store one row per delivery. Put the unique index on the provider name and event ID together. IDs from two providers can then never collide.

Schema::create('webhook_events', function (Blueprint $table) {
    $table->id();
    $table->string('provider', 32);
    $table->string('event_id', 128);
    $table->string('type');
    $table->json('payload');
    $table->timestamp('processed_at')->nullable();
    $table->timestamps();

    $table->unique(['provider', 'event_id']);
});

The processed_at column is the single record of whether the work finished. A status column would add little here. The job in Step 5 commits its work and processed_at together, so no other process can ever see an in-progress state.

Each provider needs the right ID. Stripe’s event id identifies the event. Shopify’s guidance is to deduplicate on X-Shopify-Webhook-Id. The X-Shopify-Event-Id header only correlates deliveries from the same merchant action, such as two subscriptions to one topic.

Step 3: Claim the event with an insert, not a lookup

These snippets run inside one controller method, after the Step 1 check. The tempting version checks whether the ID exists and then creates the row. Two deliveries that arrive in the same instant both pass the check, and both run. To prevent duplicate webhook processing, insert first and let the unique index reject the loser.

Idempotent webhook processing in Laravel: a unique index accepts the first of two simultaneous deliveries and rejects the second.
use Illuminate\Database\UniqueConstraintViolationException;

try {
    $webhookEvent = WebhookEvent::create([
        'provider' => 'stripe',
        'event_id' => $event->id, // Shopify: $request->header('X-Shopify-Webhook-Id')
        'type'     => $event->type,
        'payload'  => $request->json()->all(),
    ]);
} catch (UniqueConstraintViolationException) {
    return response()->json(['received' => true, 'duplicate' => true]);
}

Add the four fields to the model’s $fillable array and cast payload to array. Laravel’s built-in database drivers raise this exception for a duplicate key, so one catch block covers MySQL, PostgreSQL and SQLite.

This is deliberately a plain create() call. A method like insertOrIgnore() can hide other insert errors behind a zero count, and your code would then treat a failed insert as a duplicate and drop the event.

Return 200 for the duplicate. A 4xx or 5xx response tells the provider the delivery failed, so it keeps retrying.

Step 4: Return quickly and queue the work

Dispatch a job with the stored row’s ID, then return 200 straight away. Pass the ID instead of the payload so the job always reads the saved row. Laravel attempts a job once by default, so set tries and a backoff on the job, or a failed event waits in failed_jobs. The Laravel queue documentation covers both options.

ProcessWebhookEvent::dispatch($webhookEvent->id);

return response()->json(['received' => true]);

Step 5: Make the job safe to retry

The claim row proves an event arrived. It does not prove the work finished. A worker can die after step three of five, and the retry has to finish the job without repeating the first three steps.

use App\Models\WebhookEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;

#[Tries(5)]
#[Backoff([10, 30, 60, 120])]
class ProcessWebhookEvent implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $webhookEventId) {}

    public function handle(): void
    {
        DB::transaction(function () {
            $event = WebhookEvent::lockForUpdate()->findOrFail($this->webhookEventId);

            if ($event->processed_at !== null) {
                return;
            }

            // Business logic here. Prefer upserts and natural keys for writes.

            $event->update(['processed_at' => now()]);
        });
    }
}

The job looks the row up by its own ID, so it can never pick up another provider’s event. The lockForUpdate() call makes a second worker wait on the same row, then see processed_at already set. If the business logic throws, the transaction rolls back and processed_at stays empty, so the event never counts as complete.

The attributes above are Laravel 13 syntax. Earlier versions use the equivalent tries property and backoff() method. After the last attempt, the job lands in failed_jobs and the row keeps its empty processed_at. Add a failed() method to the job if you want an alert at that point.

The transaction cannot undo an email already sent or an API call already made. For those, rely on a key the downstream system enforces, such as a unique order reference. Send an idempotency key too if the downstream API accepts one, and reuse the same key on every retry of the same operation. Keep slow external calls short, because the row lock and the transaction stay open until the closure ends.

Step 6: Recover events that were stored but never queued

The server can fail after the insert in Step 3 and before the dispatch in Step 4. The row then exists, the provider’s retry will hit the duplicate path and get a 200, and no job will ever run. A scheduled sweep closes that gap by re-dispatching rows that never finished.

// routes/console.php
use App\Jobs\ProcessWebhookEvent;
use App\Models\WebhookEvent;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    WebhookEvent::whereNull('processed_at')
        ->where('created_at', '<', now()->subMinutes(10))
        ->each(fn (WebhookEvent $event) => ProcessWebhookEvent::dispatch($event->id));
})->everyFiveMinutes();

The sweep can dispatch a job that is still queued or running. That is safe, because the job from Step 5 checks processed_at under a row lock. The ten-minute age and five-minute interval are starting points to tune. If a permanently broken event should stop retrying, add an attempts counter or an age cap to the query. Laravel’s scheduler also needs its single cron entry running, and an alert on old rows with an empty processed_at doubles as your failed-event monitor.

Can ShouldBeUnique or Cache::lock replace the unique index?

No. ShouldBeUnique only stops duplicate dispatches of a job while a cache lock is held. The Laravel queue documentation says that lock releases when the job finishes or exhausts its retries. It also says unique jobs need a lock-capable cache driver shared by every server.

MechanismWhat it guardsWhere the state livesBest use
Unique index on webhook_eventsDuplicate deliveries, for as long as the row existsYour databaseThe primary duplicate check
lockForUpdate()Two workers on the same eventYour databaseInside the job in Step 5
ShouldBeUniqueDuplicate job dispatches while the lock is heldCache driverAn optional extra guard
Cache::lock()Short critical sectionsCache driverSerialising work on one hot resource

How do I test duplicate and concurrent webhook deliveries?

Test the failure cases before you go live, because the happy path will pass even when the design is wrong.

  • Send the same event twice and confirm the business operation runs once.
  • Send two identical requests at the same moment and confirm only one webhook_events row exists.
  • Make the job throw halfway through and confirm the retry creates no duplicate payment or order.
  • Send a request with an invalid signature and confirm it gets a 400 and no row.
  • Stop the app after the insert and before the dispatch, then confirm the Step 6 sweep picks the row up.
  • Replay a real Stripe event with the Stripe CLI command stripe events resend and confirm it counts as a duplicate.

Which edge cases still cause duplicate effects?

  • Two separate events can describe one change. Stripe says it sometimes generates two Event objects and suggests comparing the data.object ID and the event type. An event-ID table cannot catch that, so put a unique key on the business record as well.
  • Webhooks can arrive out of order. Stripe does not guarantee delivery order, so fetch the current object from the provider’s API instead of trusting the payload as the latest state.
  • On PostgreSQL, a unique violation inside an open transaction aborts that transaction. Run the claim insert outside any wrapping transaction.
  • A duplicate returns 200 even when the first attempt failed, so a provider resend will not rerun it. Rely on the Step 6 sweep or a manual re-dispatch from the stored row, and prune old rows only after the provider’s retry window has passed.

What should I build first?

Start with the unique index and the 200 on duplicates, because those two pieces stop a repeated delivery from running twice. Add the retry-safe job and the recovery sweep before the first provider goes live. A second provider then needs only a new value in the provider column and its own ID header. For help with a larger Laravel build, see our Laravel development services.

Was this answer helpful?

Your feedback helps us improve our answers.

Still need help?

Questions about duplicate webhooks in your Laravel app?

If you're weighing how to make your webhook handling safe to retry, we're happy to walk through what you're seeing and what your options are.

Talk to Laravel Experts