# Stripe webhooks arrive twice or out of order. How do I handle them safely?

Source: https://gitshowcase.com/forum/discuss/stripe-webhooks-arrive-twice-or-out-of-order-how-do-i-handle-them/
Site: GitShowcase Forum, category Payment, Email and SMS APIs
Published: 2026-11-17. Updated: 2026-11-17. Replies: 0.

## Question by Nils Haugen (staff), 2026-11-17

Treat every webhook as "something changed, go check." Verify the signature on the raw body, store each event ID so a repeat does nothing, return a 2xx fast, and fetch the current object from Stripe instead of trusting arrival order. Duplicates and shuffled order are documented behaviour, not a bug in your setup.

## What Stripe actually promises

The [Stripe webhooks docs](https://docs.stripe.com/webhooks) are direct about this, as of the docs in November 2026:

- Endpoints might occasionally receive the same event more than once.
- Stripe does not guarantee events arrive in the order they were generated. Creating a subscription, for example, can produce `customer.subscription.created`, `invoice.created`, `invoice.paid` and `charge.created` in any order.
- In some cases two separate Event objects are generated for the same thing.
- Failed deliveries are retried automatically, in live mode for up to three days with exponential backoff.

So your handler has to be safe to run twice and safe to run in any order. The rest of this answer is how.

## Check first

1. What status code does your endpoint return? Anything other than 2xx, a redirect, or a slow response counts as a failure and triggers a retry. The docs treat 3xx as failures too.
2. Does your framework parse the body before Stripe verification? Stripe needs the raw body, and any manipulation makes signature verification fail.
3. In Workbench, open your endpoint's Event deliveries tab. It shows each event as Delivered, Pending or Failed, with the HTTP status of each attempt.

## Step 1: Verify the signature on the raw body

Never act on an unverified request. A fake request could otherwise fulfil orders or grant access. Use the official library with the `Stripe-Signature` header and your endpoint secret (it starts with `whsec_`):

```js
import express from "express";
import Stripe from "stripe";

const stripe = new Stripe(process.env.STRIPE_API_KEY);
const app = express();

// raw body for this route only
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      req.headers["stripe-signature"],
      process.env.STRIPE_WEBHOOK_SECRET // whsec_... from your endpoint settings
    );
  } catch (err) {
    return res.status(400).send("bad signature");
  }
  // steps 2 to 4 go here
});
```

If this fails with a signature error, the usual cause is a JSON body parser running before this route. Each endpoint has its own secret, and test and live secrets differ.

## Step 2: Make the handler idempotent with the event ID

Idempotent means running it twice has the same result as running it once. Stripe's advice is to log processed event IDs and skip repeats. The cleanest way is a table with a unique key, written in the same database transaction as your business change:

```sql
CREATE TABLE processed_events (
  event_id   text PRIMARY KEY,
  event_type text NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);
```

```js
const client = await pool.connect();
try {
  await client.query("BEGIN");
  const ins = await client.query(
    "INSERT INTO processed_events (event_id, event_type) VALUES ($1, $2) ON CONFLICT DO NOTHING",
    [event.id, event.type]
  );
  if (ins.rowCount === 1) {
    await applyEvent(client, event); // your business logic
  }
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  return res.status(500).send("retry me"); // Stripe will retry
} finally {
  client.release();
}
res.status(200).send("ok");
```

If the logic fails, the rollback also removes the event ID, so the retry runs it properly. For the "two separate Event objects" case, the docs suggest identifying duplicates with the ID of `data.object` plus `event.type`. A unique key on that pair in your own domain table (for example one fulfilment per payment intent) is stronger than any event log alone.

## Step 3: Do not depend on order

Do not use the event's `created` time to decide which came first. The docs warn that snapshot events record `created` in seconds, so distinct events can share a timestamp. Instead:

| Problem | Safe approach |
| --- | --- |
| `invoice.paid` arrives before `customer.subscription.created` | On each event, retrieve the current subscription from the API and write that state |
| An old event arrives after a newer one | Write the latest fetched object, never the stale payload |
| A related row does not exist yet | Return 500 so Stripe retries, or fetch and create it |

The docs also note you can retrieve missing objects through the API, for example the invoice, charge and subscription from `invoice.paid`. In short: use the webhook as the trigger and the API as the source of truth.

## Step 4: Answer fast and process off the request

Return the 2xx before slow work such as emailing or updating a third party. The docs recommend handling events through an asynchronous queue, because a spike (for instance when many subscriptions renew at once) can overwhelm a handler that does everything inline. The pattern: verify, record the event ID, put a job on a queue, return 200.

## Test it

Use the Stripe CLI to forward and replay events locally:

```bash
stripe listen --forward-to localhost:4242/webhook
stripe trigger payment_intent.succeeded
stripe events resend <EVENT_ID> --webhook-endpoint=<ENDPOINT_ID>
```

Resend the same event twice and confirm your database changed once. The docs say manual resend works for up to 15 days in the Dashboard and 30 days with the CLI. For your own API calls, such as creating a charge from a worker that might retry, use an [idempotency key](https://docs.stripe.com/api/idempotent_requests) so a retry cannot create a second object. The [payment API guide](https://gitshowcase.com/best/payment-apis/) compares providers. If your handler writes to a serverless database, the connection advice in [Serverless Postgres keeps running out of connections](/forum/discuss/serverless-postgres-keeps-running-out-of-connections-what-should-i/) applies here too.

---
Cite as: GitShowcase Forum, "Stripe webhooks arrive twice or out of order. How do I handle them safely?", https://gitshowcase.com/forum/discuss/stripe-webhooks-arrive-twice-or-out-of-order-how-do-i-handle-them/, accessed 2026-11-17.
