Payments

Designing Idempotent Stripe Webhook Handlers

Why payment webhooks arrive twice, out of order or late — and a practical pattern for processing Stripe events exactly once in Laravel or Node.js.

Most payment bugs are not caused by the payment provider. They come from assumptions in the code that receives the provider’s events: that each event arrives once, that events arrive in order, and that the customer’s browser will always return to the success page. None of those assumptions hold in production.

This article describes a webhook handling pattern that has proven reliable for Stripe integrations. The same principles apply to almost any provider that delivers events over HTTP.

Why webhooks are the source of truth

When a customer pays through Stripe Checkout, they are redirected back to your site. It is tempting to mark the order as paid on that redirect. But the customer may close the tab, lose connectivity, or the payment may require an asynchronous step such as 3D Secure or a bank debit that settles days later.

Webhooks such as checkout.session.completed , payment_intent.succeeded and invoice.paid are delivered server-to-server, retried automatically on failure and signed so you can verify their origin. They should drive every state change that matters: fulfilling orders, granting access and updating subscriptions. The redirect should only update the user interface.

Understand the delivery guarantees

Stripe delivers events at least once. That has three practical consequences:

  • The same event can be delivered more than once, for example when your endpoint responds slowly and Stripe retries.
  • Events are not guaranteed to arrive in the order they were created.
  • Events can arrive long after the underlying action, during retries after an outage on your side.

A correct handler therefore needs to be idempotent — processing the same event twice must have the same effect as processing it once — and it should not rely on ordering.

A reliable handling pattern

  1. Verify the signature using the raw request body and your endpoint secret. Reject anything that fails.
  2. Record the event ID in a table with a unique constraint. If the insert fails because the ID already exists, acknowledge with a 200 and stop.
  3. Acknowledge quickly. Push the real work onto a queue and return a 2xx response within a few seconds.
  4. In the background job, re-fetch the latest state of the object from the API rather than trusting the payload snapshot.
  5. Apply the change using a state transition that is safe to repeat, for example “mark order paid if not already paid”.

Signature verification and deduplication in Node.js

app.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body, req.headers['stripe-signature'] as string, process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return res.status(400).send('Invalid signature');
  }

  // Unique index on webhook_events.event_id makes this insert the dedupe gate.
  const inserted = await db.webhookEvents.insertIfAbsent({ eventId: event.id, type: event.type });
  if (!inserted) return res.sendStatus(200); // already seen

  await queue.add('stripe-event', { eventId: event.id });
  return res.sendStatus(200);
});

Idempotent processing in a Laravel job

public function handle(StripeClient $stripe): void
{
    $event = $stripe->events->retrieve($this->eventId);

    if ($event->type === 'checkout.session.completed') {
        $session = $stripe->checkout->sessions->retrieve($event->data->object->id);

        DB::transaction(function () use ($session) {
            $order = Order::where('checkout_session_id', $session->id)
                ->lockForUpdate()
                ->firstOrFail();

            if ($order->status !== OrderStatus::Paid && $session->payment_status === 'paid') {
                $order->markPaid($session->payment_intent);
            }
        });
    }
}

The row lock and the explicit status check make the operation safe to run concurrently and repeatedly. If two deliveries of the same logical change slip past the event-ID gate — for example two different event types describing the same payment — the state check still prevents double fulfilment.

Handling out-of-order events

Because the job re-fetches the current object from Stripe, it always acts on the latest state rather than on a potentially stale snapshot. That removes most ordering problems. For subscriptions, compare timestamps or the subscription status you fetched before overwriting local data, and never let an older event downgrade a newer state.

Operational safeguards

  • Log every event ID, type and processing outcome so you can trace a customer complaint to the exact event.
  • Alert on repeated job failures — a silently failing webhook queue means paid customers are not being served.
  • Use the Stripe CLI to replay events locally and in staging, including duplicate and out-of-order scenarios.
  • Keep a reconciliation job that periodically compares recent Stripe payments with local orders.

Never store raw card numbers. Stripe Checkout and Elements keep card data on Stripe’s infrastructure, which keeps your own systems out of the most demanding parts of PCI DSS scope.

Summary

Treat webhooks as the source of truth, verify every signature, deduplicate by event ID, acknowledge fast, process in the background against fresh data and make every state change safe to repeat. With those rules in place, payment integrations become one of the most predictable parts of your system rather than one of the most stressful.

Suman Ramanandi

Founder & Technical Lead at RaxnexuS, with 8+ years of software development experience.

All insights

Start a conversation

Have an ambitious idea? Let’s engineer it.

Tell us about your product, platform or integration. You will receive a considered response from an engineer — not a sales script.

Engineering Digital Possibilities.

An independent software engineering and digital technology brand, led by Suman Ramanandi. Working remotely with businesses in the United States, United Kingdom, Europe and India.

© 2026 RaxnexuS. All rights reserved.