Deutsch
Fix libraryMediumStripe · Webhooks

Non-idempotent Stripe webhook: one payment, credits granted twice

Stripe may deliver the same event more than once. A webhook that adds credits on every delivery hands out extras. Record each event id and process it only once.

By Tim GeithnerPublished 4 min read

ShipRely's Payments & Billing audit is in development and will check for this.

Short answer

Stripe retries webhook deliveries and can send the same event more than once, so a handler that adds credits or extends access every time it runs will sometimes do it twice. Store the id of every processed event in a table with a unique key, and record it in the same database transaction as the change it causes. A duplicate then changes nothing, and a failed attempt leaves no trace so Stripe’s retry can finish it.

Ask an AI about this page:ChatGPTClaude

On this page

A non-idempotent webhook does its work again every time the same event arrives. Stripe can deliver one event more than once, so a handler that adds 100 credits on invoice.paid will sometimes add 200 for one payment, or extend a subscription twice. The fix is idempotency: remember which event ids you processed and skip the ones you’ve seen. It is rated medium because nobody needs to attack you for it to happen; it costs you money quietly, and it is easy to trigger on purpose by provoking retries.

Why it matters

Stripe’s webhook docs say it directly: endpoints “might occasionally receive the same event more than once”, and the remedy is to log the event ids you’ve processed and not process logged events again. Duplicates usually follow retries. If your function answers slowly, times out or returns an error, Stripe tries again, in live mode for up to three days. Your first attempt may have succeeded after all, and the retry runs the same code a second time.

The handler that AI tools typically write looks like this:

Vulnerablesupabase/functions/stripe-webhook/index.ts
if (event.type === "invoice.paid") {
  const invoice = event.data.object;
  const customer = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
  // Runs again on every retry or duplicate delivery.
  const { data } = await admin.from("billing_customers").select("credits").eq("stripe_customer_id", customer).single();
  await admin.from("billing_customers").update({ credits: data!.credits + 100 }).eq("stripe_customer_id", customer);
}

It has two problems. Every delivery adds credits, and the read-then-write leaves a gap where two parallel deliveries both read the old value. Stripe adds one more trap: events aren’t guaranteed to arrive in order, and its docs warn against using the created timestamp to detect duplicates.

How to find it in your app

Open your webhook handler and look at every event type it handles. For each, ask: if this exact event arrived twice, would the second run change anything?

Search your repository
grep -rn "invoice.paid\|checkout.session.completed\|payment_intent.succeeded" supabase/functions
grep -rn "event.id\|stripe_events\|processed_events" supabase/functions supabase/migrations

Handlers that add (credits, days, seats, orders, e-mails) and never store event.id are the defect. Then prove it in test mode: in the Stripe dashboard, open a delivered invoice.paid event for a test customer and click Resend. If the test customer’s credits go up a second time, your handler is not idempotent.

How to fix it

Keep a table of processed events with the Stripe event id as primary key, and record the event in the same transaction as the change it causes. This is the setup from our Stripe security guide:

SafeRemember every event you processed
create table public.stripe_events (
  id text primary key,
  type text not null,
  processed_at timestamptz not null default now()
);

alter table public.stripe_events enable row level security;
revoke all on table public.stripe_events from anon, authenticated;
SafeRecord the event and grant the credits in one transaction
create or replace function public.grant_invoice_credits(
  p_event_id text,
  p_event_type text,
  p_customer text,
  p_credits integer
)
returns boolean
language plpgsql
set search_path = ''
as $$
begin
  insert into public.stripe_events (id, type)
  values (p_event_id, p_event_type)
  on conflict (id) do nothing;

  if not found then
    return false; -- duplicate delivery: already processed
  end if;

  update public.billing_customers
  set credits = credits + p_credits
  where stripe_customer_id = p_customer;

  if not found then
    raise exception 'unknown Stripe customer %', p_customer;
  end if;

  return true;
end;
$$;

revoke execute on function public.grant_invoice_credits(text, text, text, integer)
  from public, anon, authenticated;
grant execute on function public.grant_invoice_credits(text, text, text, integer)
  to service_role;

on conflict (id) do nothing lets the primary key decide: the first delivery inserts the row and grants the credits, every later one inserts nothing and returns false. Because the whole function is one transaction, a failure (here: an unknown customer) rolls back the event row too, so Stripe’s retry can still process it. The billing_customers table comes from the same guide; use whatever table holds your balances.

The webhook calls the function after the signature check:

Safesupabase/functions/stripe-webhook/index.ts
if (event.type === "invoice.paid") {
  const invoice = event.data.object;
  const customer = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;

  // One transaction: records the event id and grants the credits, or does nothing for a duplicate.
  const { error } = await admin.rpc("grant_invoice_credits", {
    p_event_id: event.id,
    p_event_type: event.type,
    p_customer: customer,
    p_credits: 100,
  });
  // Nothing was recorded, so Stripe's retry can process the event later.
  if (error) return new Response("Try again later", { status: 500 });
}
return Response.json({ received: true });

A duplicate gets a normal 200 answer, which tells Stripe to stop retrying. Stripe’s docs also mention rare cases with two separate event objects for one change; if that matters for you, add a unique key on the object id plus event type in the table that holds the result.

Make the Stripe webhook idempotent

Add a new Supabase migration with a table public.stripe_events (id text primary key, type text, processed_at timestamptz default now()) with row level security enabled and all privileges revoked from anon and authenticated. For every Stripe event type our webhook handles that adds something (credits, access days, orders, e-mails), create a plpgsql function that inserts the event id with on conflict (id) do nothing, returns false if nothing was inserted, and otherwise applies the change in the same transaction. Revoke execute from public, anon and authenticated and grant it to service_role.

In the webhook edge function, call these functions with event.id after the signature check, return 500 when the call errors so Stripe retries, and return 200 for duplicates. Do not use the event’s created timestamp to detect duplicates.

Check that the fix works

  1. In Stripe test mode, pay an invoice for a test customer and note the credits.
  2. Click Resend on that invoice.paid event in the dashboard. The delivery must succeed with 200 and the credits must stay the same.
  3. Look into stripe_events: the event id must appear exactly once.
  4. In the SQL Editor, call grant_invoice_credits with a made-up event id and customer id. It must fail with unknown Stripe customer, and that event id must not appear in stripe_events, so a later retry could still succeed.

We ran this SQL against Postgres with Supabase’s roles: without the events table, a second delivery grants the credits twice; with it, repeated calls for the same event return false and change nothing, a failed grant leaves no event row, and visitors and signed-in users can neither call the function nor read the events table.

Frequently asked questions

How often does Stripe send the same event twice?

Stripe doesn’t promise a number; its docs only say endpoints might occasionally receive the same event more than once. Retries after a timeout or a 5xx answer are the common cause, and in live mode Stripe retries for up to three days.

Can I use the event’s created timestamp to detect duplicates?

No. Stripe’s docs say distinct events can share a timestamp and tell you not to use created to decide whether an event was already processed. Use the event id.

My handler only sets status = ‘active’. Does it need this too?

Setting a value is naturally safe to repeat, so a duplicate does no harm there. The risk is in handlers that add something: credits, days of access, e-mails, orders. Note that Stripe also doesn’t guarantee the order of events, so read the current object from the API when order matters.

Should I insert the event id first and process afterwards?

Only if both happen in one transaction. If you record the event and then the processing fails, the retry is skipped and the customer never gets what they paid for. The database function on this page does both atomically.

Sources

  1. 1.Receive Stripe events in your webhook endpoint — Stripe Docs
  2. 2.Manage webhook endpoints — Stripe Docs
  3. 3.INSERT … ON CONFLICT — PostgreSQL Documentation
  4. 4.CWE-837: Improper Enforcement of a Single, Unique Action — MITRE

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt