# Keep Stripe subscription state current when webhooks arrive out of order

Treat each verified webhook as a signal to fetch the current Stripe subscription. Serialize the fetch and database write by subscription ID so an earlier worker cannot overwrite a newer result. Track event IDs separately to handle duplicate deliveries.

## From the research

3 of 388 payment and webhook repair commits were labeled event order or state.

- [Payment repair counts](https://github.com/ohad6k/viberaven-research/blob/2d45c586d8d73b8913651894f4451b8071086daf/data/fixcommits-subclasses.csv)

## Apply the fix

### Store the verified delivery

Verify the signature against the raw request body. Persist the work item with a unique key for the Stripe account and event ID, and acknowledge delivery after that write succeeds.

### Reconcile per subscription

Have the worker take the subscription's serialized slot before it calls `stripe.subscriptions.retrieve`. Fetch in the account that owns the subscription, then write the state and mark the work item complete. Keep the slot through the commit, and retry failed reads or writes. Distinct Stripe events can share the same `created` timestamp, so use the current subscription for reconciliation.

### Keep side effects idempotent

Use a business key for each invoice-driven side effect, such as recording a payment or sending a receipt. Run a periodic reconciliation for subscriptions with delayed or missing deliveries.

## Verify the change

In a Stripe test environment, run the subscription change and cancellation cases in both delivery orders and with a repeat delivery. The stored state should match Stripe's current state and each invoice side effect should be recorded once.

## Research and sources

We classified 3 of 388 payment and webhook repair commits as event order or state. These are Git history labels across payment providers. They give a count of repairs found in the sample and leave the frequency of out-of-order Stripe deliveries unmeasured.

- [Fix commit study and counting rules](https://github.com/ohad6k/viberaven-research/blob/2d45c586d8d73b8913651894f4451b8071086daf/studies/fix-commits/README.md)
- [Stripe webhook event ordering](https://docs.stripe.com/webhooks#event-ordering)
- [Stripe Retrieve a subscription](https://docs.stripe.com/api/subscriptions/retrieve)

## Related guide

- [Deduplicate Stripe webhook deliveries](https://viberaven.dev/stripe-webhook-duplicate-events)

Source: https://viberaven.dev/answers/stripe-webhook-events-out-of-order

Site index: https://viberaven.dev/llms.txt
