Menu

1 / 2

Stripe Webhook Handler Processes the Same Event Twice: Idempotency With a Postgres Unique Constraint

DEV Community: postgres·Libme·3 days ago
#lpaC4OLr
#devtopostgresql#devto#dev#event#stripe
Long article (1481 words) — no AI summary yet.
Reading 0:00
15s threshold

TL;DR: Stripe delivers webhooks at least once, not exactly once, so your handler will eventually see the same event.id twice (a retry after a slow response, a manual resend, a race between two workers). The fix is not a cache or an if already_processed check. Insert the event ID into a table with a primary key, in the same transaction as your side effects, and treat a conflict as "already done."

The same pattern works for any webhook provider that retries. I'm using Stripe because its behavior is well documented, and Python with FastAPI and psycopg 3 because the code is short.

Why does my webhook handler run twice?

The symptom usually shows up as a customer getting two welcome emails, a credit balance incremented twice, or a log like this:

INFO handling checkout.session.completed evt_1Abc... INFO granted 500 credits to user 42 INFO handling checkout.session.completed evt_1Abc... INFO granted 500 credits to user 42

Enter fullscreen mode

Exit fullscreen mode

Same event ID, two executions.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.