Laravel Webhook Idempotency: Prevent Duplicate Processing and Safe Retries

A practical MySQL inbox/outbox design for Stripe webhooks, queue workers, transactional writes and duplicate delivery tests

Webhook retries are normal. Duplicate business actions are not. A payment provider may deliver the same notification more than once after a timeout, an HTTP 500, a network interruption or a manual replay. Meanwhile, your Laravel queue worker may crash after charging a customer, writing a subscription row or sending an email but before recording success. In both cases, a simple “we received an event” check is insufficient.

The production-friendly answer is idempotency: the same logical event may arrive repeatedly, but the application commits its business effect no more than once. This guide develops that idea with a durable MySQL inbox table, a uniqueness constraint, a transaction boundary, an outbox handoff, and a small set of destructive tests. The code is an adaptable pattern, not a drop-in payment integration.

Laravel offers transaction and queue primitives; your application must still decide what a unique event means, verify that the sender is authentic, and handle partial external side effects. We will use Stripe as a concrete example without assuming that every webhook provider shares its signature format or replay rules.

Repeated webhook deliveries converging on a single verified database processing flow
Multiple deliveries can be legitimate. The database, not an in-memory flag, should decide whether a business effect is new.

Why Laravel webhooks are delivered more than once

An HTTP response can be lost even when your server successfully processed the request. The provider sees a timeout, retries, and you see what appears to be a second webhook. A queued job can also be attempted more than once after a worker failure. Ordering is not guaranteed for all event types, so “the latest request to arrive” does not necessarily describe the latest business state.

OWASP explicitly recommends persisting processed event IDs, safely acknowledging authenticated duplicates and making downstream effects idempotent. Stripe's webhook documentation likewise discusses signature verification, duplicate deliveries, asynchronous processing and event ordering. Those recommendations are not Laravel-specific; they apply to any endpoint that changes state based on messages sent by another system.

Three different identities must not be confused

Delivery attempt: one HTTP request. Retry attempts may carry the same logical event. Provider event ID: a stable identifier supplied for an event, such as a Stripe evt_... ID. Business operation ID: the payment, order or subscription being changed. A second legitimate event for the same payment is not automatically a duplicate event; it might be a later state transition.

Choose the deduplication key from the provider's documented event model. For Stripe-style event retries, a compound unique key on (provider, event_id) is a useful first line of defense. Some providers also emit semantically duplicate events with different event IDs, so business transitions need their own guard.

The architecture: verify, record, process

Separate receipt of the message from execution of business work. The HTTP route should authenticate the sender, validate the minimum fields, durably store the event, and acknowledge quickly. A background worker owns the business transaction. The worker must never depend on a temporary PHP process or a memory cache for its only record of prior work.

Three-step workflow: verify a webhook signature, write a unique inbox and outbox event, then perform one idempotent business effect
A durable inbox plus an outbox avoids a fragile gap between accepting an event and scheduling downstream work.

Inbox and outbox have different jobs

The inbox records authenticated incoming events, with one row per provider event ID. An outbox row, written in the same database transaction, records work the application must eventually perform. A scheduled worker can claim pending outbox rows and dispatch or process them. This closes a common reliability gap: acknowledging a webhook and then crashing before enqueuing its job.

A simple dispatch()->afterCommit() is helpful for avoiding reads of uncommitted rows, but it is not the same thing as a durable transactional outbox. Laravel documents after_commit behavior; if the process terminates after commit and before the dispatch is observed, your own recovery design still matters.

Step 1: create a durable MySQL inbox table

Start with a table whose database uniqueness constraint is the authority. This migration sketch works conceptually with Laravel 10–13, but review your installed Laravel version, current migrations and naming conventions before adapting it.

Schema::create('webhook_inbox', function (Blueprint $table) {
    $table->id();
    $table->string('provider', 40);
    $table->string('event_id', 191);
    $table->string('event_type', 120);
    $table->string('status', 24)->default('received');
    $table->json('payload');
    $table->timestamp('processed_at')->nullable();
    $table->timestamps();
    $table->unique(['provider', 'event_id']);
    $table->index(['status', 'created_at']);
});

Store only what you need. If the payload contains sensitive personal data, use encryption or a minimal normalized representation, restrict access, and define a retention policy. A hash may be sufficient for auditing certain event types, but it cannot replace the fields your worker needs to reconcile a transaction.

Why a SELECT-before-INSERT check fails

Two PHP-FPM workers can both execute SELECT ... WHERE event_id = ?, both find no row, and both continue to write business data. A unique index moves the decision into the database's concurrency control. A preliminary lookup is convenient for metrics; it must not be the sole duplicate protection.

Step 2: authenticate before you acknowledge

A bot, test script or attacker can send JSON that looks like a payment event. Always verify the provider's signature using its official SDK and the exact raw request body before trusting the event ID. Do not copy Stripe's signing scheme to providers that document a different scheme.

For a Stripe integration where stripe/stripe-php has already been installed and the webhook signing secret is configured server-side, the verification boundary can look like this:

$payload = $request->getContent(); // exact raw body
$signature = $request->header('Stripe-Signature', '');

try {
    $event = \Stripe\Webhook::constructEvent(
        $payload,
        $signature,
        config('services.stripe.webhook_secret')
    );
} catch (\Throwable $e) {
    // Invalid payload/signature: never persist as verified.
    return response('Invalid event', 400);
}

$eventId = $event->id;
$eventType = $event->type;

Production implementations should catch the SDK's documented verification exceptions, enforce a request-size limit before heavy parsing, and avoid logging raw signed bodies or secrets. Exempt only the specific webhook route from CSRF middleware where your Laravel version requires that adjustment. CSRF exemptions do not replace signature verification.

Step 3: insert once, then acknowledge authenticated duplicates

The following pseudocode uses a database transaction to insert an inbox row and an outbox action together. The decisive rule is the UNIQUE(provider, event_id) constraint. The outbox row must reference the inserted inbox ID; write both rows or neither.

DB::transaction(function () use ($eventId, $eventType, $payload) {
    $inboxId = DB::table('webhook_inbox')->insertGetId([
        'provider'   => 'stripe',
        'event_id'   => $eventId,
        'event_type' => $eventType,
        'payload'    => $payload, // adjust to column encoding
        'status'     => 'received',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    DB::table('webhook_outbox')->insert([
        'inbox_id' => $inboxId,
        'status'   => 'pending',
        'created_at' => now(),
        'updated_at' => now(),
    ]);
});

This is intentionally an architecture sketch: create the outbox migration, validate the provider event, encode JSON correctly for your connection, and handle duplicate-key exceptions in the controller. In the duplicate exception branch, first confirm that an inbox row actually exists for the same provider and event ID; do not blindly treat every SQL error as a successful replay. Errors other than a verified duplicate should return an appropriate failure so the provider can retry.

Once the inbox and outbox transaction commits, the endpoint can return a successful 2xx acknowledgement. A later authenticated delivery of that same event can also receive 2xx without inserting another outbox row. If persistence failed, do not falsely acknowledge success.

Step 4: make the business transition idempotent too

Deduplicating inbound IDs prevents the same event record from being accepted twice, but it does not automatically make all downstream operations safe. Your worker may time out after changing an order yet before updating webhook_inbox.status. The next attempt must not issue a second refund, credit a balance twice or send two order-confirmation emails.

Use a business-level unique guard

For money-related operations, add a unique reference on the business object—for example ledger_entries(provider, charge_id, entry_type). In a transaction, claim or insert that reference and update the relevant balance only if the claim is genuinely new. Put the two changes on the same database connection and within the same transaction, and lock the affected order when competing events may arrive.

DB::transaction(function () use ($paymentId, $orderId) {
    $order = DB::table('orders')
        ->where('id', $orderId)
        ->lockForUpdate()
        ->first();

    if (! $order) {
        throw new RuntimeException('Order missing');
    }

    if ($order->payment_status === 'paid') {
        return; // repeat delivery: no second transition
    }

    DB::table('orders')->where('id', $orderId)->update([
        'payment_status' => 'paid',
        'provider_payment_id' => $paymentId,
    ]);
});

This shortened example assumes you have already verified that the payment belongs to the order and that the amount and currency match. It does not replace an audit ledger, nor does it safely handle every payment state. A complete system also stores the provider's transaction reference under a unique constraint and verifies that events cannot regress the order from a newer state to an older one.

External API calls are a separate failure domain

If processing an event triggers a separate API request—such as creating a refund—use that API's documented idempotency-key feature with a stable business-operation key. Stripe exposes an Idempotency-Key header for supported requests. An HTTP timeout does not tell you whether the external operation completed, so reconcile its state before attempting again; never simply generate a fresh key and send another charge.

Step 5: queue work after commit, or poll the outbox

Laravel's queue system supports afterCommit() and an after_commit connection option, which prevents a queued worker from seeing transaction data that was never committed. For straightforward jobs, this is a useful default. For strict delivery guarantees, keep the outbox row as a durable source and use a scheduled poller to recover work after worker crashes.

The worker should claim pending rows with a concurrency-safe mechanism, update an attempt marker, perform one guarded business transition, and write a completion receipt. Do not claim “exactly once network delivery.” The practical target is at-least-once delivery plus idempotent, auditable effects.

Retry policy should distinguish safe and unsafe failures

Retry transient database deadlocks and temporary service failures using bounded attempts with backoff and jitter. Laravel's DB::transaction supports a retry count for deadlocks. Do not automatically replay operations when the result is unknown and the downstream provider cannot reconcile it. Quarantine those cases for manual review, with enough IDs to inspect without exposing secrets.

A test matrix that catches duplicate processing

Before enabling a production payment webhook, exercise each failure mode against a sandbox environment and confirm that the database shows one business effect. Unit tests are useful, but at least one integration test should use real database uniqueness and concurrent workers.

ScenarioExpected resultWhat to inspect
Same signed event delivered twiceOne inbox row, one outbox rowUnique key and HTTP 2xx replay response
Two deliveries at the same instantOne committed insertRace against a real MySQL unique index
Crash after inbox commitOutbox remains pending and recoverableScheduled outbox poller
Crash after business updateLater retry does not repeat the effectBusiness-level unique reference and status
Forged or malformed signatureReject, no inbox rowRaw body signature validation
Out-of-order eventNo regression to an obsolete stateProvider truth and state-transition checks
External API timeoutNo blind second chargeStable idempotency key and reconciliation

Operational checklist for a small Laravel VPS

On a modest PHP/MySQL VPS, the database is already the strongest durable primitive you have. You do not need a large message broker on day one; you do need explicit constraints, error handling, and audit records. Begin with a MySQL inbox/outbox pair, a single worker and bounded throughput. Scale queue workers only after verifying the concurrency behavior.

  • Verify signatures from the raw request body before trusting IDs or metadata.
  • Store one durable record per provider event and enforce a database unique constraint.
  • Separate inbox receipt from downstream processing using an outbox or equivalent recovery contract.
  • Ensure one business transition per operation, not merely one HTTP request per event.
  • Persist stable idempotency keys for outbound payment/refund requests.
  • Log job IDs, event IDs, final status and exception class; do not log webhook secrets.
  • Alert on stuck pending rows, repeated deadlocks and quarantined uncertain outcomes.
  • Test parallel redelivery and process termination against a staging database.

Related Rubic8 guides and developer tools

The same persistence and replay-safety principles apply outside payments. Rubic8's OpenAI Agents API time-awareness and async tools guide discusses durable state and safe retries for agent workflows. For another queued-API example, see our Google Indexing API quotas guide, which covers retry windows and request budgets.

When debugging redacted webhook fixtures, use the Rubic8 JSON Validator to check payload structure and the Rubic8 JSON Formatter to inspect nested event data. Never paste actual signing secrets, customer payment data or unredacted production webhooks into online tools.

Frequently asked questions

Does Laravel prevent duplicate webhooks automatically?

No. Laravel gives you database transactions, queues and locks, but you must define the event identity and create database constraints or business guards yourself.

Can I just cache processed event IDs in Redis?

A cache can reduce redundant work, but expiry, eviction and cache/database timing can reintroduce duplicates. A durable unique constraint should remain the source of truth for important money-related effects.

Should a repeated webhook return HTTP 409?

Usually not for an authenticated event that has already been durably accepted. A successful acknowledgement tells the provider it can stop retrying that event. Follow each provider's documented response contract.

Is one provider event ID enough to prevent a double payment?

No. It protects against exact event replays. Preventing a duplicate charge or refund also requires business-operation idempotency and the downstream provider's documented idempotency support.

What about Laravel 12 versus Laravel 13?

The core pattern—MySQL uniqueness, transactions, queued work after commit and defensive retries—does not require Laravel 13. Check your installed framework and PHP version for exact syntax, queue configuration and CSRF middleware before applying code examples.

Official references and further reading

Reviewed November 23, 2026. This article explains defensive architecture; adapt it to your provider's current API contract, your Laravel version and your application's accounting requirements.


Rubic8 Editorial Team

Editorial Team

Rubic8 creates practical guides and free tools for developers, webmasters, and digital publishers. Our fast-changing technical content is reviewed against current primary documentation before publication.

We care about your data and would love to use cookies to improve your experience.