Stripe webhook idempotency: fulfil a paid order only once

Stripe webhook idempotency for paid orders: why a status flag failed, how an advisory lock and a fulfilled_at timestamp stop repeat emails and double counts.

By

On a photo marketplace I work on, a redelivered checkout.session.completed re-ran everything: a second purchase email, a second purchase event and a second $add on the buyer's analytics profile. I found it reading the handler during other work. Stripe webhook idempotency looks like a one-line guard, and the obvious guard on this code could not work. This post covers why, the Postgres advisory lock and timestamp that replaced it, the status codes that keep Stripe retrying when it should, and how I test it by replaying signed events.

What a redelivered event did to a paid order

The handler ran as one long list of steps. Find or create the buyer, mark the order complete, build the invoice and licence documents, send the emails, then report the sale to analytics. Nothing in that list remembered it had already finished, so a second delivery of the same event walked the whole list again.

A second email is annoying. The analytics side is worse, because $add increments a number on the buyer's profile and has no dedupe of its own. Every replay inflates purchases and revenue for that buyer.

The same handler had the opposite bug. The purchase email caught its own errors and logged them. So when the email provider failed, the handler carried on and answered 200, Stripe saw a success and never retried, and a paid buyer got nothing. One path did the work too often, and the other could stop doing it with no second chance.

What is Stripe webhook idempotency?

Stripe webhook idempotency means that handling the same event twice has the same effect as handling it once. The Stripe webhook docs say an endpoint might occasionally receive the same event more than once, and that live mode retries delivery for up to three days. They suggest logging the event IDs you have processed. They also warn that two separate Event objects are sometimes generated, which you match on the data.object ID plus the event type.

Hanging the guard on the checkout session covers that case too. The session is the thing being fulfilled, so two events about one session land on the same row.

Why the completed flag could not be the guard

The order already had a completed flag, and if (order.completed) return is the line everyone would write first. It fails for two reasons.

Something else sets it. The status poll marks the order complete as well. If the poll gets there first, the webhook would see the flag, stop, and skip the emails for an order that was never delivered.

It is saved too early. The flag is written before the email goes out. If the email fails and Stripe retries, the retry sees the flag and quits, which is the "paid buyer gets nothing" bug again.

A guard has to mean "all of this finished", and only the last step of the work can say that. So I added a nullable fulfilled_at timestamp, written once everything else has succeeded.

The new column had a trap of its own. Both completion paths load the order and save the whole entity later, so a stale null could overwrite the timestamp and undo the guard. In TypeORM, select: false keeps the column off loaded entities, and the only write to it is a direct UPDATE.

The helper: an advisory lock plus a timestamp

A timestamp alone leaves a gap, because two deliveries at the same moment can both read an empty column. A lock closes that gap. The shape of it, with neutral names:

async function fulfilOnce<T>(order: Order, fulfil: () => Promise<T | null>) {
  return db.transaction(async (tx) => {
    const [{ locked }] = await tx.query(
      `SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS locked`,
      [order.sessionId],
    );
    if (!locked) return 'busy';

    const [row] = await tx.query(`SELECT fulfilled_at FROM orders WHERE id = $1`, [order.id]);
    if (row.fulfilled_at) return null;

    const result = await fulfil();
    if (result !== null) {
      await tx.query(`UPDATE orders SET fulfilled_at = now() WHERE id = $1`, [order.id]);
    }
    return result;
  });
}

The Postgres docs on advisory locks describe the behaviour this relies on. A transaction-level lock is released automatically when the transaction ends, so there is nothing to release by hand. The try form returns false at once instead of waiting, so a second delivery never sits in a queue. If the process dies mid-email, the connection goes, the lock goes with it, and a paid order is left free for Stripe's retry.

If fulfil throws, the transaction rolls back, fulfilled_at stays empty and the next delivery runs the work again. Once it commits, every retry hits the early return and does nothing.

The honest cost is a pooled connection held open for the length of the emails. That is fine at this sales volume. If fulfilment ever started to queue, I would move to a lease column.

Status codes decide what Stripe does next

Your response is the only thing Stripe learns, so each one has to be true. Three decisions came from that.

The email rethrows. Failing loudly turns a provider outage into a 500, and a 500 gets retried. The email service was hiding the single signal that could have recovered the order.

A held lock answers 409. A delivery that finds the lock taken might look harmless, and 200 might seem like the polite reply. But a 200 ends the retries, and the delivery holding the lock could still fail after that. Any non-2xx keeps the event alive until the outcome is known.

The login email goes first. New buyers get a temp password, and it exists only on the first attempt. If the purchase email ran first and failed, the retry would find an existing account and have no password left to send. Ordering the steps by what cannot be recreated solved that with no extra code.

Stripe's docs also say to return a 2xx quickly, before complex logic. This handler doesn't, on purpose: its reply reports whether fulfilment worked. At higher volume my default would be to store the event, answer at once and run the work from a queue, as in replying first and fanning out later. Retries then become your job.

Analytics runs after the commit

Tracking moved outside the lock and only runs once fulfilled_at has committed. With $add having no dedupe, it has to run exactly when the work is known to be done, and a failed attempt must leave no trace.

The purchase event also takes its time from the Stripe event, for a reason that is easy to miss. Mixpanel only treats two events as duplicates when the event name, time, distinct id and insert id all match. A stable insert id with Date.now() beside it doesn't match, so the dedupe never fires. The wider setup, including how the event joins guest browsing to the account, is in server-side conversion tracking from a Stripe webhook.

Testing by replaying signed events

A unit test with a mocked database would not prove any of this, because the behaviour lives in Postgres locks and real commits. So the test runs the real handler over HTTP against a throwaway database, sending events signed with Stripe's generateTestHeaderString. The email provider, Stripe API, storage and analytics are stubbed, and the test refuses to run unless it is connected to the test database. It covers six cases:

  • Redelivery. Three deliveries give one email, one event and one $add.
  • Failed email. The first delivery answers 500 with nothing tracked. The retry delivers once, and the login email is not lost.
  • Status poll first. The completed flag is already true, and fulfilment still runs.
  • Stale save after. A poll that loaded the row earlier saves it late, and fulfilled_at survives.
  • Two at once. The codes come back as 200 and 409, with one email.
  • Crash with the lock held. A connection takes the lock and is killed. Deliveries get 409 until then, and the retry fulfils.

The stale save and crash cases are the ones I'd keep if I could only have two, since neither shows up by reading the happy path.

Idempotency also has a sibling in the database. Where the rule is "this row exists once", a constraint beats a lock, which I covered in fixing race condition duplicates with a unique index. And if your purchases come through an app store provider, webhook security for in-app purchases covers proving who sent the request in the first place.

The short version

Assume every event arrives twice, sometimes at the same moment. Pick a guard that means "everything finished", and write it last. Put a transaction-level advisory lock around the work, answer 409 when it is held, and let real failures surface as a 500 so Stripe retries. Send anything that can't be recreated first, and run non-idempotent tracking only after the commit. Then replay signed events at the real handler to prove it. If you do one thing today, check whether any email or side effect in your webhook catches its own errors.

More of my backend work is on the projects page.

Want this kind of work on your product?

Get in touch