Guide · Python backend
Webhook Idempotency in FastAPI: Durable Intake and Safe Retries
Key takeaways
- Common webhook providers retry deliveries; check your provider's success codes and retry policy.
- Store the provider's event ID with a database unique constraint before doing any work.
- A unique ID prevents duplicate intake; worker claims and external actions need separate protection.
- The database, not an in-memory set, is what makes this survive restarts and multiple workers.
By Prasanna Patil · published · updated
Retries are the contract
Providers such as WhatsApp Business API and Stripe retry failed webhook deliveries. The accepted response codes, timeouts and retry windows depend on the provider. A network failure can also leave the sender unsure whether a request succeeded, so duplicate deliveries must be part of the design.
My WhatsApp work at Shivohini TechAI included webhook ingestion and asynchronous message processing; the case study describes that implementation. The database pattern below is a reference design for handling retries, not a claim that this exact code or constraint was shipped in that project. It is not a runnable application or an end-to-end exactly-once guarantee.
The pattern
@router.post("/webhook", status_code=202)
async def webhook(event: IncomingEvent):
# insert_if_new: INSERT with a unique constraint on the provider's event ID.
# Returns the row only if this is the first delivery.
message_id = db.insert_if_new(event.id, event.payload)
if message_id:
handle_message.delay(message_id)
return {"id": event.id} # always 202, even for duplicatesThree details matter. The unique constraint lives in the database, so it holds across restarts and across every worker. The check-and-insert is one statement, so two concurrent deliveries can't both win. And duplicates still get the provider's supported success response after durable receipt. This admission step does not prove that a reply, payment or upload happened only once.
Where the dedup key comes from
The whole pattern rests on one question: what string identifies "this exact delivery" across retries? Pick it in this order of preference.
- The provider's event or message ID. Most providers put a stable ID in the payload or a header, and re-send the same ID on every retry. Use it as-is. Check the provider's documentation for which field is stable across retries, because some distinguish a per-event ID from a per-attempt ID.
- A provider-scoped key. If IDs are only unique per account or per sender, combine them (provider name, account, ID) so two sources can never collide in one table.
- A hash of the stable payload fields. When there is no ID, hash the fields that do not change between retries (sender, timestamp, content). Leave out anything the provider regenerates on each attempt, such as delivery timestamps or attempt counters, or every retry will look new.
import hashlib, json
def dedup_key(provider: str, event: dict) -> str:
if event.get("id"):
return f"{provider}:{event['id']}"
stable = {k: event[k] for k in ("sender", "timestamp", "content")}
digest = hashlib.sha256(json.dumps(stable, sort_keys=True).encode()).hexdigest()
return f"{provider}:hash:{digest}"Insert first, never check then insert
The tempting version reads the table, sees no row for this key, then inserts. Under concurrency that fails: two deliveries of the same event arrive milliseconds apart, both read "not found", and both proceed. The window is small but retries tend to arrive in bursts, which is exactly when it opens.
The fix is to make the database decide. Put a unique constraint on the key and attempt the insert, telling PostgreSQL to do nothing on conflict. Whether a row came back tells you if this delivery was the first.
# The constraint: the database enforces uniqueness, not application code.
# CREATE TABLE webhook_events (
# dedup_key text PRIMARY KEY,
# payload jsonb NOT NULL,
# status text NOT NULL DEFAULT 'received',
# created_at timestamptz NOT NULL DEFAULT now()
# );
from sqlalchemy.dialects.postgresql import insert
def insert_if_new(session, key: str, payload: dict):
stmt = (
insert(WebhookEvent)
.values(dedup_key=key, payload=payload)
.on_conflict_do_nothing(index_elements=["dedup_key"])
.returning(WebhookEvent.dedup_key)
)
event_key = session.execute(stmt).scalar_one_or_none()
session.commit()
return event_key # a serializable key; None means someone stored it alreadyOne statement, one atomic outcome. There is no gap between checking and writing for a second delivery to slip through, and it behaves the same with one worker or twenty.
Acknowledge fast, process asynchronously
Providers set a timeout on your response and treat a slow reply as a failure, which triggers the retry you are defending against. So the receiver should do as little as possible: verify the request, store the event, hand the work to a background queue, and return a 2xx. Slow work such as calling an LLM or another API belongs in a Celery task, not in the request.
Order matters. Commit the row first, then enqueue with the row's ID, and have the task load the row rather than trusting data passed through the queue. If the process dies after the commit but before the enqueue, the row exists with status received and a periodic sweep can pick it up. That is a delay, not a lost event.
@celery.task(bind=True)
def handle_message(self, dedup_key: str):
with session_scope() as s:
# Claim the row atomically; only one task run can move it out of 'received'.
claimed = s.execute(
update(WebhookEvent)
.where(WebhookEvent.dedup_key == dedup_key,
WebhookEvent.status == "received")
.values(status="processing")
.returning(WebhookEvent.dedup_key)
).first()
if not claimed:
return # already handled, or being handled elsewhere
... # do the side effect, then set status = 'done'The status-guarded update makes the database claim atomic, but the sketch leaves transaction boundaries, claim expiry and recovery unspecified. Commit a claim before external work, give it a lease or another recoverable ownership rule, and detect abandoned work. A worker can still send successfully and crash before saving done. Use the downstream API's idempotency key where available; otherwise record the attempt and reconcile an uncertain result before resending. A database status check alone cannot guarantee an external action happens exactly once.
Out-of-order and same-ID-different-payload events
Two cases the basic pattern does not solve on its own, both worth deciding on deliberately.
- Out-of-order delivery. Retries and parallel delivery mean event B can arrive before event A. If your logic depends on order (a status moving from "sent" to "delivered"), do not assume arrival order. Compare against a timestamp or sequence number from the provider and ignore updates older than what you already hold, or model the status so that only forward transitions are allowed.
- Same ID, different payload. A well-behaved provider re-sends identical content under the same ID, so the second copy is safely dropped. If the content differs, something is wrong: a provider bug, a replay with changed data, or a forged request. Store a hash of the payload with the row, and when a duplicate key arrives with a different hash, log it and alert instead of silently discarding it.
Signature verification sits in front of all of this. Dedup stops honest retries; it does not prove a request came from the provider, so verify the provider's signature before you store anything.
Where teams get this wrong
- Deduplicating in memory. A set of seen IDs dies with the process and doesn't exist for the second worker.
- Acknowledging before persisting. If you enqueue before the row commits, a crash between the two loses the event; if you commit after enqueueing, a crash duplicates it.
- Skipping recoverable execution. Use an atomic claim rather than reading the row's status and then acting. Plan for expired claims and for external actions whose outcome is unknown after a crash; see the worker recovery guide.
A test checklist
Idempotency is easy to believe in and easy to get subtly wrong, so test it directly instead of trusting the design.
- Replay the same event N times. Send one payload ten times in a row. Expect ten 2xx responses, one stored row and one side effect.
- Replay concurrently. Fire the same event from several threads or processes at once. This is the test that catches check-then-insert races, which sequential replays never reveal.
- Kill the worker mid-task. Stop the worker after it claims the row but before it finishes. Confirm the event is eventually completed or flagged, and that the side effect does not happen twice.
- Crash between commit and enqueue. Confirm the sweep for rows stuck in received picks the event up.
- Duplicate with a changed payload. Confirm it is flagged rather than silently dropped or reprocessed.
- Out-of-order pair. Send the later event first and check the final state is still correct.
from concurrent.futures import ThreadPoolExecutor
def test_concurrent_replay(client, db):
event = {"id": "evt_123", "content": "hello"}
with ThreadPoolExecutor(max_workers=8) as pool:
responses = list(pool.map(lambda _: client.post("/webhook", json=event), range(20)))
assert all(r.status_code == 202 for r in responses)
assert db.count_events("evt_123") == 1
assert fake_queue.enqueued_count("evt_123") == 1
# This checks intake only. Exercise the worker, recovery sweep and a fake
# downstream API separately, including a crash after the API accepts a call.Limitations of this guide
It covers single-database idempotency. Multi-region writes, exactly-once delivery across systems, and providers that don't send a stable event ID each need more.
Frequently asked questions
What if the provider doesn't send an event ID?
A hash of stable payload fields can be a fallback, but two distinct events with identical fields can collide. Confirm the provider's identity contract first; if events cannot be distinguished reliably, define the acceptable duplicate or loss risk instead of claiming exact deduplication.
Is Redis not simpler for this?
Redis SET with NX can reserve a key atomically, but expiry, eviction and persistence settings determine how long that protection lasts. For this design, keep the durable event ledger and its unique constraint in PostgreSQL next to the state it protects.
Should I still return 202 for duplicates?
Return the success code the provider supports after confirming the event was durably received. This generic sketch uses 202; Meta's receiver in the WhatsApp guide uses 200. Errors can trigger more retries until the provider's retry policy is exhausted.
Why not check whether the event exists and then insert?
Because two deliveries of the same event can both run the check before either inserts, and both then proceed. A unique constraint with an insert that does nothing on conflict lets the database decide atomically, so only one delivery wins.
Should the webhook handler do the work itself?
Usually not. Providers time out slow responses and retry them. Store the event, enqueue a background task, and return a 2xx quickly. The task then needs its own guard so a redelivered task cannot repeat the side effect.
How do I test that my receiver is really idempotent?
Replay one event many times, replay it concurrently, and stop a worker partway through a task. Concurrent replay is the important one, since it exposes races that sequential tests never trigger.
Primary documentation
Use the documentation for the versions you deploy; the examples above are explanatory sketches, not a version-pinned application.
- PostgreSQL: INSERT and ON CONFLICT — Atomic conflict handling for a unique event key.
- Stripe: webhooks — One provider's documented retry, duplicate-event and ordering behavior.
- Celery: tasks and acknowledgements — Idempotency, late acknowledgements and worker-loss behavior.
- FastAPI: background tasks — When a separate queue is appropriate for slow work.
Webhooks misbehaving in production?
Describe the provider, the duplicate behaviour and where it hurts.