All guidesDeep-dive articles

PostgreSQL and webhooks

How do I prevent double spends from concurrent webhooks in Postgres?

By Ohad Krispin, founder of VibeRaven · LinkedIn

Short answer

Concurrent Stripe deliveries can each read the same eligible state before either commits, so both perform the side effect. Let Postgres claim the business action or reserve capacity atomically before doing the work.

On this page

Why is my Stripe webhook processed twice concurrently?

Stripe can retry a delivery while the original handler is still working. Separate Event objects can also refer to the same business action. Dedupe deliveries by event ID and give fulfillment its own unique business key, such as the Checkout Session ID when each session should be fulfilled once.

How do I stop a discount code from being used twice in Postgres?

For a shared usage cap, make the eligibility check part of the UPDATE and proceed only when RETURNING gives you a row. Keep redemption and the counter update in the same transaction so they roll back together.

For a per-customer limit of one use, make (discount_id, user_id) unique on redemptions. If deciding eligibility requires several steps on an existing row, SELECT it FOR UPDATE and hold the lock in the same transaction through the check and write.

SQL
update public.discounts
set uses = uses + 1
where id = $1 and uses < max_uses
returning id;

How do I prevent a double payout from a duplicate webhook?

Make payout_id unique on payout_claims. Insert the claim before the side effect and proceed only if RETURNING gives you the ID. For effects written to Postgres, commit the claim and the effect in the same transaction.

For an external payout, commit the claim and a durable work item together. Have the worker send the payout with the same provider idempotency key on each retry, when the provider supports it.

SQL
insert into public.payout_claims (payout_id) values ($1)
on conflict (payout_id) do nothing
returning payout_id;

How does VibeRaven find duplicate webhook work?

  1. 1
    Replay supported Stripe webhook handlers from your project folder. VibeRaven loads the migrations into local Postgres and runs simulated sequences, including concurrent duplicates, then reports where the replay broke. It uses test events and local stubs.
    Terminal
    npx viberaven check --replay
  2. 2
    Read the results for the handler and sequence exercised. The general concurrency explorer for finding races across application flows is experimental and has yet to ship in the CLI.

Official docs behind this checklist

FAQ for builders before launch