# Stripe webhooks in Node.js: verify, deduplicate and retry without losing events

> How to handle Stripe and GitHub webhooks in Node.js so events are never lost or processed twice: signatures, idempotency, retries, leases and dead letters.

- Published 2026-10-30, updated 2026-10-30
- URL: https://softreuse.com/guides/stripe-webhooks-nodejs-idempotency-retries

**Short answer:** verify the signature over the raw body, insert the event into a table whose primary key is `(provider, event_id)`, answer `2xx`, then process it. Retry failures from a worker with backoff and jitter, use a lease instead of a lock so a crashed worker can't hold an event forever, and move events that can never succeed to a dead-letter state you can replay. Providers deliver **at least once**, so your handler must be idempotent.

## Why the twenty-line handler breaks

The usual handler parses the event, does the work and returns `200`. In production:

- **The same event arrives twice**, sometimes at the same instant. [Stripe](https://docs.stripe.com/webhooks/best-practices) and GitHub both deliver at least once.
- **Your handler is slow**, the provider times out (GitHub expects a response within 10 seconds) and resends while the first copy is still running.
- **Your database blips during a deploy.** If you already answered `200`, the event is gone.
- **The process is killed halfway** (serverless timeout, deploy, OOM). A lock taken by that process is never released.
- **An event can never succeed** (unknown customer, malformed payload) and retries forever.

## The order that works

```
verify signature ─▶ store event (unique key) ─▶ answer 2xx ─▶ process ─▶ processed | retry later | dead
```

1. **Verify** before anything else, over the **raw bytes**. A forged request is rejected with `401` and nothing is stored.
2. **Store** the event. If the insert fails, answer `500`: the provider will retry, which is exactly what you want. This should be the *only* path that returns `5xx`.
3. **Answer `2xx`** once the row exists. From now on, delivery is your job, not the provider's.
4. **Process** inline or in a worker. A failure doesn't change the response: the event is stored and you retry it.

## Signatures: Stripe, GitHub and everyone else

| Provider | Header | Signed content | Replay protection |
|---|---|---|---|
| Stripe | `Stripe-Signature: t=…,v1=…` | `<timestamp>.<raw body>`, HMAC-SHA256 | Reject old timestamps (Stripe's libraries default to 5 minutes) |
| GitHub | `X-Hub-Signature-256: sha256=…` | raw body, HMAC-SHA256, hex | None in the signature: deduplicate on `X-GitHub-Delivery` |
| Generic HMAC | provider-specific | usually body, sometimes timestamp + body | only if a timestamp is signed |

Two mistakes cause most "signature mismatch" bugs: verifying re-serialised JSON instead of the raw body (in Next.js, read `await request.text()` before parsing), and comparing with `===` instead of a constant-time comparison. During secret rotation, accept both the old and the new secret.

## Idempotency belongs in the database

`if (await alreadyProcessed(id)) return;` has a race: two concurrent deliveries both pass the check. Let the database decide:

```sql
create table webhook_events (
  provider        text        not null,
  event_id        text        not null,   -- the provider's id: (provider, event_id) IS the idempotency key
  type            text        not null,
  raw_body        text        not null,   -- exactly as received
  status          text        not null default 'pending', -- pending | processing | processed | dead
  attempts        integer     not null default 0,
  next_attempt_at timestamptz not null default now(),
  locked_until    timestamptz,            -- lease: a crashed worker's event becomes claimable again
  primary key (provider, event_id)
);
```

The second insert of the same event conflicts and becomes a harmless `200 {"status":"duplicate"}`. Ten concurrent copies, one stored row.

That stops duplicate *storage*, not duplicate *side effects*: a handler can finish its work and the process can die before it marks the event processed. So handlers run at least once, and each one needs a key for its own writes, e.g. `stripe:evt_123` as a unique column on the order you create.

## Retries, leases and dead letters

- **Backoff with full jitter.** After an outage, thousands of failed events would otherwise retry at the same second and knock your recovering system over again.
- **Leases, not locks.** Mark a claimed event `processing` with a `locked_until` longer than your handler's timeout. If the worker dies, the lease expires and another worker picks it up. Claim with `FOR UPDATE SKIP LOCKED` so several workers can poll the same table without blocking each other.
- **Count claims, not just failures.** An event that kills its worker every time would otherwise loop forever. After the attempt budget, mark it `dead`.
- **A non-retryable error.** When retrying can't help (unknown customer), go straight to `dead` instead of waiting days.
- **Replay.** After you fix the bug, move dead events back to `pending`.

## Ordering

Webhooks can arrive out of order and retries make it worse. Don't serialise them: make handlers order-independent by comparing the object's version or `updated` timestamp with what you stored, or re-fetch the object from the provider's API inside the handler.

## Implementing it in TypeScript

[Reliable Webhooks](https://softreuse.com/products/reliable-webhooks) is this design as about 780 lines of strict TypeScript with zero runtime dependencies, Stripe, GitHub and generic HMAC providers, and a PostgreSQL store. A Next.js App Router integration:

```ts
import { Pool } from "pg";
import { createWebhookReceiver, PostgresStore, stripeProvider } from "@softreuse/webhook-kit";

export const receiver = createWebhookReceiver({
  provider: stripeProvider({ secret: process.env.STRIPE_WEBHOOK_SECRET! }),
  store: new PostgresStore(new Pool({ connectionString: process.env.DATABASE_URL })),
  handlers: {
    "checkout.session.completed": async ({ event, idempotencyKey }) => {
      await grantAccess(event.payload, idempotencyKey); // idempotencyKey = "stripe:evt_…"
    },
  },
});

// app/api/webhooks/stripe/route.ts
export const POST = (request: Request) => receiver.handle(request);

// app/api/cron/webhooks/route.ts, every minute: retries and crash recovery
await receiver.processDue({ limit: 25 });
```

Its tests include ten concurrent duplicates, a database outage during delivery and a worker killed mid-handler, run against a real PostgreSQL.

## Checklist

- Signature verified over the raw body, constant-time compare, timestamp tolerance where the provider signs one.
- Unique key on `(provider, event id)`; `2xx` only after the insert.
- Handlers idempotent on the event's key.
- A worker on a schedule for retries, with backoff, jitter and leases.
- Dead letters you monitor, and a way to replay them.
- Body size cap before reading, and no secrets or full payloads in logs.

## Sources

- [Stripe: receive events in your webhook endpoint](https://docs.stripe.com/webhooks) and [webhook best practices](https://docs.stripe.com/webhooks/best-practices)
- [GitHub: validating webhook deliveries](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries)
- [PostgreSQL: SELECT … FOR UPDATE SKIP LOCKED](https://www.postgresql.org/docs/current/sql-select.html)

## Frequently asked questions

### Why does my Stripe webhook receive the same event twice?

Stripe and GitHub deliver webhooks at least once. A timeout, a 5xx from your server or a manual resend all produce a second delivery with the same event id. Stripe's documentation tells you to expect duplicates and to make handlers idempotent; the reliable way is a unique key on (provider, event id) in your database.

### Should I return 200 before or after processing a webhook?

After storing it durably, before processing it. Answering after a slow handler makes the provider time out and resend; answering before storing means a crash loses the event. Verify the signature, insert the event, answer 2xx, then process.

### How do I verify a Stripe webhook signature in Node.js?

Compute an HMAC-SHA256 of the timestamp and the raw request body with your endpoint's signing secret and compare it in constant time with the v1 signature in the Stripe-Signature header, rejecting timestamps older than a tolerance (Stripe's libraries use 5 minutes). Use the raw bytes: re-serialised JSON will not match.

### How do I verify a GitHub webhook signature?

GitHub sends X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the raw body with your webhook secret>. Recompute it over the raw bytes and compare in constant time. GitHub's payload has no timestamp in the signature, so deduplicate on the X-GitHub-Delivery id.

### What happens if my database is down when a webhook arrives?

Answer 5xx without acknowledging. The provider will retry later (Stripe retries for up to three days in live mode). Never answer 2xx for an event you have not stored.

### How do I handle webhooks that arrive out of order?

Don't rely on order. Compare the object's version or updated timestamp in the payload with what you have stored, or fetch the current object from the provider's API inside the handler.
