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 Same event ID, two executions. Stripe's documentation describes webhook delivery as at-least-once and says events can arrive out of order. If your endpoint doesn't return a 2xx quickly, Stripe retries with backoff (in live mode, for up to a few days as of late 2026; check the current docs for specifics). The classic trigger: your handler does slow work, such as sending email or calling another API, before responding. It takes longer than Stripe's timeout, Stripe records a failure and retries, and meanwhile your first run finished successfully.
Two dead ends I see developers try first:
- Respond faster. Worth doing, but it reduces duplicates rather than eliminating them. Network failures after you've processed but before Stripe sees the 200 still cause retries.
- An in-memory set or Redis key "seen events." It works until you have two workers, a restart, or a key that expires before the retry window ends. It also has a gap between "check" and "set" unless you use an atomic operation.
Takeaway: duplicates are a property of the delivery model, so deduplication has to live in your durable storage, not in your handler's memory.
What is the simplest correct way to deduplicate?
Let the database enforce it. Create a table keyed by the provider's event ID:
create table processed_events ( event_id text primary key, event_type text not null, processed_at timestamptz not null default now() ); Then, inside one transaction:
insert ... on conflict (event_id) do nothing- If zero rows were inserted, someone already handled it. Return 200 and stop.
- Otherwise run your side effects in the same transaction and commit.
The "same transaction" part is the important one. If you insert the ID first and commit, then crash before the side effects run, the retry sees "already processed" and your customer never gets their credits. With one transaction, a crash rolls back both the marker and the work, so the retry starts clean.
Takeaway: the dedup marker and the business write must commit or roll back together, otherwise you've traded duplicate processing for lost processing.
What does the handler look like?
import os import psycopg import stripe from fastapi import FastAPI, HTTPException, Request app = FastAPI() WEBHOOK_SECRET = os.environ["STRIPE_WEBHOOK_SECRET"] DSN = os.environ["DATABASE_URL"] async def handle_event(conn: psycopg.AsyncConnection, event: dict) -> None: if event["type"] == "checkout.session.completed": session = event["data"]["object"] user_id = int(session["client_reference_id"]) await conn.execute( "update accounts set credits = credits + 500 where user_id = %s", (user_id,), ) # Unknown event types fall through: we still record them as processed. @app.post("/webhooks/stripe") async def stripe_webhook(request: Request): payload = await request.body() # raw bytes, needed for signature check sig = request.headers.get("stripe-signature", "") try: event = stripe.Webhook.construct_event(payload, sig, WEBHOOK_SECRET) except (ValueError, stripe.SignatureVerificationError): raise HTTPException(status_code=400, detail="bad signature") async with await psycopg.AsyncConnection.connect(DSN) as conn: async with conn.transaction(): cur = await conn.execute( """ insert into processed_events (event_id, event_type) values (%s, %s) on conflict (event_id) do nothing """, (event["id"], event["type"]), ) if cur.rowcount == 0: return {"status": "duplicate"} await handle_event(conn, event) return {"status": "ok"} A few details worth knowing:
- Concurrent duplicates are handled by Postgres. If two workers receive the same event at once, the second
insertwaits on the first's uncommitted row. If the first commits, the second gets a conflict and does nothing. If the first rolls back, the second proceeds. No application-level locking needed. - Always return 2xx for duplicates. A 4xx or 5xx tells Stripe to keep retrying.
- Return non-2xx on real failures. If
handle_eventraises, the transaction rolls back, FastAPI returns a 500, and Stripe retries. That's the behavior you want. - Connect-per-request is for brevity. In production, use a pool (psycopg_pool).
Takeaway: a primary key plus on conflict do nothing gives you correct deduplication under concurrency with no locks, caches, or retry logic of your own.
What if my side effect isn't in the database?
Sending an email or calling a third-party API can't be rolled back. Options, from most to least robust:
| Approach | How it works | Drawback |
|---|---|---|
| Outbox table | Write the "send email" job into a table inside the same transaction; a separate worker sends it | An extra moving part to build and monitor |
| Provider idempotency key | Pass event["id"] as the idempotency key to the downstream API call | Only works if the downstream API supports it, and keys usually expire |
| Do it after commit | Send after the transaction commits | A crash in between loses the email silently |
| Naive "just call it" | Call inside the transaction | A rollback after the email leaves a sent email with no record |
For most small apps, the outbox is the right default: it reuses the Postgres you already have, and if you already run a Postgres-backed job queue the outbox is just another job type. If you want the managed version of that idea, a hosted queue service is the alternative, but it won't give you the atomic commit with your business data, which is the whole point here.
Takeaway: if a side effect can't join your transaction, record the intent inside it and perform the effect afterward.
How do I test the duplicate path?
Don't trust it until you've replayed an event. The Stripe CLI can resend a real event, and a direct test is simple enough:
def test_duplicate_event_is_a_noop(client, db): event = signed_checkout_event(event_id="evt_test_1", user_id=42) assert client.post("/webhooks/stripe", **event).json() == {"status": "ok"} assert client.post("/webhooks/stripe", **event).json() == {"status": "duplicate"} assert db.scalar("select credits from accounts where user_id = 42") == 500 The assertion that matters is the last one: credits are 500, not 1000.
One limitation: processed_events grows forever. A small app can ignore that for a long time. When it matters, delete rows older than your provider's maximum retry window, plus a generous margin.
FAQ
Does Stripe send webhooks more than once?
Yes. Stripe's delivery is at-least-once, and it retries failed deliveries, so your endpoint must tolerate receiving the same event ID multiple times.
How do I make a webhook handler idempotent?
Store each event ID under a unique constraint in the same database transaction as your side effects, and skip processing when the insert conflicts.
Should I return 200 for a duplicate webhook?
Yes. Return a 2xx so the provider stops retrying; a 4xx or 5xx makes it send the event again.
Bottom line
If you take payments through Stripe and your webhook does anything that must happen exactly once, add a processed_events table today; it is about ten lines of SQL and Python. Keep the marker and the business write in one transaction, return 2xx for duplicates, and use an outbox for side effects that can't be rolled back. Skip Redis-based dedup unless you already depend on it for correctness elsewhere.
