Jens Danneels, back to home page
NL, Nederlands
← All notes

· 4 min read

Handling duplicate Stripe webhooks with a pending status

Stripe can send the same webhook more than once. Create records as pending, confirm them only from the webhook, and make every handler safe to run twice.

Stripe delivers webhooks at least once. If your endpoint is slow, times out or returns an error, Stripe sends the event again, and it keeps retrying for up to three days. Events can also arrive out of order. A handler that does "add a seat" or "lower the stock" every time an event comes in will sooner or later do it twice.

This is the pattern I used in Dogs in Balance, my bachelor's thesis. It's a dog-training platform where people pay for three things through one Stripe account: a seat in a training session, webshop orders, and a subscription for online courses. The examples come from there, but the pattern works for anything you sell through Stripe Checkout.

Don't trust the success page

After paying, the customer is redirected back to your site. It's tempting to confirm the order on that page, but it's only a redirect: people close the tab, lose their connection, or open the URL without paying. The webhook is the reliable signal. Treat the success page as "thanks, we're checking" and let the webhook do the work.

1. Create the record before the customer pays

Save the booking or order before sending the customer to Stripe, with the status pending. Then put what the payment is for into the Checkout session's metadata:

const booking = await createBooking({ sessionId, email, status: 'pending' })
 
const checkout = await stripe.checkout.sessions.create({
  mode: 'payment',
  line_items: lineItems,
  customer_email: email,
  metadata: {
    type: 'booking',
    bookingId: String(booking.id),
  },
  success_url: `${SITE_URL}/booking/thanks`,
  cancel_url: `${SITE_URL}/booking/cancelled`,
})

Stripe sends the metadata back with every event about that session. That gives you two things: you always know which record a payment belongs to, and every checkout someone starts leaves a trace, even if they never finish.

2. Verify the webhook

Anyone can POST to your endpoint, so check Stripe's signature first. It needs the raw request body. In a Next.js route handler:

// app/api/stripe/webhook/route.ts
import Stripe from 'stripe'
 
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)
 
export async function POST(request: Request) {
  const body = await request.text()
  const signature = request.headers.get('stripe-signature') ?? ''
 
  let event: Stripe.Event
  try {
    event = stripe.webhooks.constructEvent(body, signature, process.env.STRIPE_WEBHOOK_SECRET!)
  } catch {
    return new Response('Invalid signature', { status: 400 })
  }
 
  await handleEvent(event)
  return new Response(null, { status: 200 })
}

In Dogs in Balance, Payload CMS's Stripe plugin did this part and passed verified events to a handler per event type.

3. Only act on records that are still pending

This is the core of it. The webhook moves a record from pending to confirmed, and does the side effects (counting the seat, lowering stock, sending the confirmation email) only when it made that move:

async function confirmBooking(bookingId: string) {
  const booking = await getBooking(bookingId)
  if (booking.status !== 'pending') return // a repeat delivery: already done
 
  await updateBooking(bookingId, { status: 'confirmed', paid: true })
  await addSeatToSession(booking.sessionId)
  await sendConfirmationEmail(booking)
}

The second delivery of the same event finds a confirmed booking and does nothing. Your handler becomes safe to run any number of times. That property is called idempotent, and it's the whole goal.

4. Route by metadata when you sell more than one thing

A completed checkout looks the same whether it was a booking or a webshop order, so the type in the metadata decides what happens:

async function handleEvent(event: Stripe.Event) {
  if (event.type === 'checkout.session.completed') {
    const { type, bookingId, orderId } = event.data.object.metadata ?? {}
    if (type === 'booking' && bookingId) return confirmBooking(bookingId)
    if (type === 'order' && orderId) return confirmOrder(orderId, event.data.object.id)
  }
 
  if (event.type === 'checkout.session.expired') {
    const { type, bookingId } = event.data.object.metadata ?? {}
    if (type === 'booking' && bookingId) return cancelIfPending(bookingId)
  }
}

checkout.session.expired cleans up after people who start a checkout and walk away: the pending booking becomes cancelled, with the same "only if still pending" rule.

For webshop orders there's one extra step. The completed event doesn't include the line items, so fetch them with stripe.checkout.sessions.listLineItems(sessionId, { expand: ['data.price.product'] }). To know which of your products a line is, put your own product ID in price_data.product_data.metadata when you create the session; expanding the product brings it back.

5. Subscriptions: copy the state, don't count events

Access to a subscription isn't something to "add" on each event. It's a state Stripe already knows: active, past due, cancelled. So the subscription handlers copy that state onto the user and the app checks it:

// customer.subscription.created / .updated / .deleted
await updateUser(userIdForCustomer(subscription.customer), {
  subscriptionStatus: subscription.status,
})

Setting the same status twice changes nothing, so these handlers are idempotent by nature. Handle customer.subscription.created as well as updated. Dogs in Balance only listened for updated and deleted, and a new subscription shouldn't depend on an update happening to follow it.

Making it airtight

The status check in step 3 has a gap: read, then write. If Stripe delivers the same event twice at the same moment, both deliveries can read pending before either one writes. Rare, but possible. Two ways to close it:

A conditional update. Let the database do the check and the change in one statement, and only continue if a row actually changed:

UPDATE bookings
SET status = 'confirmed', paid = true
WHERE id = $1 AND status = 'pending'
RETURNING session_id;

No row returned means another delivery got there first.

Remember which events you've handled. Store each event's ID with a unique constraint, and skip events you've already seen:

CREATE TABLE stripe_events (
  id text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);
 
INSERT INTO stripe_events (id) VALUES ($1)
ON CONFLICT DO NOTHING
RETURNING id;

If the insert returns nothing, the event is a repeat.

What I'd still change

One limitation in Dogs in Balance isn't about duplicates. Free seats were checked when a checkout started, but a seat was only counted when the webhook confirmed the payment. Two people paying for the last seat at the same time could both get it. The fix is to hold the seat for as long as the checkout is open, and release it on checkout.session.expired. The data model already had a field for those holds; I didn't get to finish it.

In short

  • Create records as pending before Checkout, and link them through metadata.
  • Verify the signature, then let the webhook be the only thing that confirms.
  • Do side effects only when you move a record out of pending.
  • Copy subscription state instead of counting events.
  • For full safety, use a conditional update or store event IDs.

Written by Jens Danneels, full-stack developer in Ghent.

Get in touch →