Guide · November 26, 2026 · 3 min read
Idempotent Stripe webhooks in Django: what actually matters
Signature checks, event dedupe, out-of-order delivery, Celery retries and replaying lost events — the Stripe webhook patterns a Django SaaS needs in production.
Stripe’s documentation says it plainly: webhooks can arrive more than once, out of order, or late. A handler that works in testing can still double-grant credits, resurrect a cancelled subscription or silently drop a payment in production. These are the patterns that prevent that, in the order a request meets them.
1. Verify the signature, and refuse to run without a secret
event = stripe.Webhook.construct_event(request.body, sig_header, webhook_secret)
Use the raw body (request.body), not parsed JSON, or the signature will not match. One subtle trap: if STRIPE_WEBHOOK_SECRET is empty, some setups “work” because the signature becomes an HMAC with an empty key — which anyone can forge. Answer 503 until the secret is configured instead of accepting events.
Exempt the endpoint from authentication, CSRF and rate limiting: a burst of renewals or a replay from the Stripe dashboard can easily exceed a per-IP throttle, and a 429 makes Stripe retry later, out of order.
2. Store the event before doing anything else
class StripeEvent(BaseModelUUID):
stripe_id = models.CharField(max_length=100, unique=True)
type = models.CharField(max_length=100, db_index=True)
data = models.JSONField()
processed = models.BooleanField(default=False, db_index=True)
stripe_event, created = StripeEvent.objects.get_or_create(
stripe_id=event.id, defaults={"type": event.type, "data": json.loads(payload)}
)
if not created and stripe_event.processed:
return Response({"received": True})
The unique constraint on stripe_id is what makes a duplicate delivery harmless even when two arrive at the same moment. Mark unhandled event types as processed right away so they are not kept, or replayed, forever.
3. Process in a background task
Answer Stripe in milliseconds and hand the event to Celery. The handler can then retry on its own schedule when Stripe’s API or your database is briefly unavailable, without Stripe’s retries piling on top.
4. Branch on your database, not on the payload
Events arrive out of order. A delayed customer.subscription.updated saying active can land after the customer.subscription.deleted that cancelled it. If the handler copies the payload’s status, the subscription comes back to life.
Instead, load your own record, decide from its state and the event’s timestamp, and refresh_from_db() after writing. A cancellation should not be undone by an older event.
5. Make anything that grants value unique
Checking .exists() and then calling .create() is not atomic — two concurrent deliveries both see “not there” and both grant the credits. For anything that adds money, credits or seats, make the dedupe atomic in one of two ways:
- a
UniqueConstrainton the identifier that represents the purchase (thepayment_intentor checkoutsessionid), catchingIntegrityErroras “already done”; or - lock the row with
select_for_update()insidetransaction.atomic()and re-check whether the purchase was already applied before changing the balance.
And only grant when the money is actually there: checkout.session.completed fires for delayed payment methods (bank debits) before the funds settle. Check payment_status == "paid" and handle checkout.session.async_payment_succeeded for the rest.
6. Grace periods are for payment problems only
past_due and unpaid deserve a grace period while Stripe retries the card. A cancelled subscription or an ended trial does not — expire it immediately, or customers keep a paid plan for free during the “grace” window.
7. Replay what never finished
Once you answered 200, Stripe will never redeliver the event. If the Celery task then exhausts its retries (a deploy mid-task, an outage), the event is lost: a customer charged and still on trial. A periodic job fixes this:
@app.task(name="replay_unprocessed_stripe_events")
def replay_unprocessed_stripe_events():
now = timezone.now()
events = StripeEvent.objects.filter(
processed=False,
type__in=HANDLED_EVENT_TYPES,
created_at__lt=now - timedelta(minutes=settings.STRIPE_EVENT_REPLAY_AFTER_MINUTES),
created_at__gt=now - timedelta(hours=settings.STRIPE_EVENT_REPLAY_WINDOW_HOURS),
).order_by("created_at")[: settings.STRIPE_EVENT_REPLAY_BATCH_SIZE]
return sum(1 for event in events if dispatch_stripe_event(event))
Because every handler is idempotent, replaying is always safe. Purge processed events after a retention window so the table does not grow forever.
8. Watch for API version changes
Stripe moves fields between API versions. For example, recent versions moved invoice.subscription under invoice.parent.subscription_details.subscription. Read both shapes while your account’s version and your SDK’s may differ.
9. Test the ugly cases
Unit tests should send the same event twice, deliver events out of order, run two deliveries concurrently and simulate a handler that fails mid-way. If those pass, the happy path will too.
Checklist
- Signature verified on the raw body; no secret means
503 - Endpoint exempt from auth, CSRF and throttling
- Events stored with a unique Stripe id before processing
- Processing in a background task with retries
- Decisions based on persisted state; cancellations are final
- Atomic dedupe (unique constraint or row lock + re-check) on anything that grants value
- Grant credits only when
payment_status == "paid" - Grace period only for
past_due/unpaid - Periodic replay of unprocessed events; purge of old ones
SaaS Dock’s billing app implements every item on this list, with tests for duplicate, concurrent and out-of-order delivery. See the billing section or how it compares to other Django boilerplates.
Frequently asked questions
- How do I make Stripe webhooks idempotent in Django?
- Store every event by its Stripe id in a table with a unique constraint, skip events already marked processed, and make each handler safe to run twice: base decisions on the state saved in your database, use unique constraints for anything that grants money or credits, and wrap balance changes in transaction.atomic() with select_for_update().
- Should a Stripe webhook be processed synchronously?
- No. Verify the signature, store the event, answer 200 quickly and process it in a background job such as a Celery task. Add a periodic job that re-queues events whose processing never finished, because Stripe will not redeliver an event you already acknowledged.
Keep reading
- 2FA recovery codes and session management in DjangoAdd one-time recovery codes to TOTP two-factor auth and an active-sessions screen that really signs devices out — access tokens included — in a Django REST API.
- Multi-tenant SaaS with Django and Next.js: a practical guideHow to model tenants, resolve the active workspace, scope every query and switch workspaces safely in a Django REST Framework API with a Next.js frontend.
- NextAuth + Django JWT: refresh tokens without session leaksHow to store Django REST Framework JWTs in NextAuth, refresh them safely from server and client, avoid handing one user another user's tokens, and sign out cleanly.