2026-11-03 · 4 min read

A SaaS template granted credits again every time a payment webhook was redelivered, and every provider it supports redelivers.

The bug report in Wasp's Open SaaS template, issue #735, opened on October 1, starts from a fact about the providers: "Stripe, Polar, and Lemon Squeezy all deliver webhook events at least once." Most of the template's handlers didn't care. "The subscription handlers set absolute values, so running them twice is harmless." The credits purchase did care: updateUserCredits "runs credits: { increment: ... }", so a redelivered invoice.paid, order.paid or order_created "grants the credits again." The fix, PR #732 ("Dedupe payment webhook events by processor event id"), was merged on October 6. It adds a ProcessedWebhookEvent table whose paymentProcessorEventId is @unique, and the patch records that row before the handler runs and deletes it if the handler throws, so a failed attempt can still be retried.

A week later, Open Mercato fixed the version where the dedupe was already written and still didn't work. Its issue #7155 opens with "Payment gateway webhook deduplication is not enforced by the database." An older migration had its up and down swapped, so the unique idempotency index on migrated databases became a plain one. The code that claims each webhook by inserting a row kept running, and a provider "that redelivers a notification with the same idempotency key gets it claimed and processed a second time." PR #7159, merged on October 13, puts the unique constraint back. Its description says why that one index matters so much: "Every payment gateway (Stripe, Tpay, mock, …) relies on claimWebhookProcessing to drop redeliveries".

None of this is a provider bug. Stripe's webhook docs say "Webhook endpoints might occasionally receive the same event more than once" and tell you to guard against it "by logging the event IDs you've processed, and then not processing already-logged events." In live mode Stripe retries a failed delivery "for up to three days with an exponential back off", and a slow handler counts as failed: the docs list "The destination server took too long to respond" as a delivery error.

Credits granted when one 10-credit Stripe event is delivered three times: a handler that only increments grants 30 either way; checking for the event id with a SELECT and then inserting grants 10 when retries arrive after the first run and 30 when they overlap it; inserting the event id under a unique key first grants 10 in both cases.

Why it survives review

A webhook handler usually looks careful. It verifies the signature, checks the event type, and returns 200, and a reviewer reads the signature check as the security part done. But the check doesn't stop a duplicate: Stripe's docs say that when it retries an event, "we generate a new signature and timestamp for the new delivery attempt", so every redelivery is a perfectly valid request. The tests send each event once. The duplicate only shows up in production, for example when the handler was slow and the provider gave up waiting and sent the event again. The tell in a diff is the side effect itself: anything that adds (credits + n, a new row, an email, a transfer) runs once per delivery, not once per event. And a dedupe that reads first and writes later has the same gap as any check-then-act: in the table above it holds when retries come after the first run finishes and fails when they overlap it.

Spot it in a small diff

An agent wires Stripe Checkout to the app's credit balance:

ai-agent wants to merge · app/billing/webhooks.py +14
1+ import stripe
2+ from fastapi import APIRouter, Header, Request
3+ from app.deps import WEBHOOK_SECRET, db
4+
5+ router = APIRouter()
6+
7+ @router.post("/webhooks/stripe")
8+ async def stripe_webhook(request: Request, stripe_signature: str = Header()):
9+ event = stripe.Webhook.construct_event(await request.body(), stripe_signature, WEBHOOK_SECRET)
10+ if event["type"] == "checkout.session.completed":
11+ session = event["data"]["object"]
12+ await db.execute("UPDATE accounts SET credits = credits + :n WHERE id = :id",
13+ {"n": int(session["metadata"]["credits"]), "id": session["client_reference_id"]})
14+ return {"received": True}

It verifies the signature with Stripe's own library on the raw body, filters on one event type, does the update in SQL, and the test that posts a signed checkout event passes.

What a trained eye flags here

Line 12 runs once per delivery, and nothing in the handler remembers that this event was already handled. Stripe sends the same event again whenever a delivery fails or times out, each time with a fresh signature, so line 9 accepts it and the customer gets the credits a second and a third time. Credits are the cheap case. Put a transfer or a shipment on line 12 and the same handler pays twice.

The comment that earns full marks: "line 12 adds credits on every delivery of this event, and Stripe delivers events more than once (retries re-sign them, so line 9 doesn't stop it). Insert event["id"] into a processed_events table with a unique key in the same transaction as the update, and return 200 without crediting when that insert conflicts." Both fixes rest on the same thing, a unique key per event: Open SaaS on the processor's event id, Open Mercato on its idempotency key. A SELECT for the id before the update doesn't count as the fix, because two overlapping deliveries both see nothing and both credit; the unique key has to decide. A test that posts the same signed event twice and checks the balance keeps it from coming back.

Practise on the same bug class

A PR in the DiffDojo library has this bug class: Kick the payout batch from the provider webhook (Python). Try it before you read the answer.

Try a review

Ask what happens when the provider sends it again before you approve.

Leave inline comments and a verdict, then see what you caught. A free account unlocks 1 PR of your choice. The pass opens the full library.

Review the payout webhook PR →
Read next React race condition: a code review exercise with solution
← All posts