Back to writing

Idempotent billing webhooks: surviving out-of-order RevenueCat events

A payments provider does not promise to call your webhook once, in order, one at a time. RevenueCat does not. Stripe does not. PayPal does not. The contract you actually sign up for is weaker than the one most handlers are written against, and the gap is where premium state quietly rots.

I learned this wiring the RevenueCat webhook for Homies, the bilingual React Native app I build on the side: the subscription edge of a hard paywall. The first version passed for the happy path. It was wrong in four distinct ways the happy path never exercises, plus a fifth way that lived in the part of the code that runs when the other four go wrong. This post is the four (plus one), one section each, with the test I wrote for each one. Then the part I did not expect: once the logic moved into SQL, two of those tests kept passing and stopped guarding anything.

The delivery contract you actually get

Three properties, none of them optional, all of them assumed away by naive handlers:

  • At-least-once. The same event id can arrive twice. A timeout on your end, a retry on theirs, a network blip in between: any of these duplicates a delivery. Your write path must be idempotent, not just your read path.
  • Unordered. A RENEWAL and a CANCELLATION for the same subscription can land in either order. The provider does not serialize them for you. "Newer event" and "later delivery" are not the same thing.
  • Racing. Two deliveries for the same subscription can be in your handler at the same time. If your logic is lookup-then-write, two concurrent lookups both see "no row yet" and both try to insert.

Everything below falls out of taking these three seriously instead of hoping they do not happen.

Failure 1: benign events wiping churn signals

The first handler rebuilt one full row object on every write and set every column from the current event. So a RENEWAL (a perfectly benign, healthy event) would set the cancellation timestamp to null, because this event is not a cancellation. It clobbered a real churn signal with the absence of one.

The flags that matter for dunning and win-back (when did this user cancel, when did billing start failing) are sticky by nature. They are facts that happened, not properties of the current event. A renewal does not un-cancel a prior cancellation. So the write has to be additive: each event type owns exactly the flags it is allowed to touch, and leaves the rest alone. I extracted that decision into a pure function, computeChurnPatch, so it could be tested without a database.

The test I wrote for it: computeChurnPatch: UPDATE preserves churn signals on benign events.

Failure 2: late events rolling back newer state

Because delivery is unordered, a stale RENEWAL can arrive after a fresh CANCELLATION. Apply it blindly and you have just resurrected a subscription the user already canceled. The row goes backwards in time.

The fix is a monotonic guard. Every row carries last_event_at. Before applying an event, compare its timestamp to what is already stored: if the incoming event is older than or equal to the persisted one, it has been superseded, and you drop it. Only strictly newer events write. This is the same idea as a vector clock degraded to a single comparable timestamp, which was all the design needed while each row had one writer. The comparison logic is isStaleEvent, also pure.

The test I wrote for it: isStaleEvent: rejects older-or-equal, accepts newer.

Failure 3: transaction-id collisions across stores

A transaction id is unique within a store. It is not unique across stores. App Store and Play Store mint their own id spaces, and they overlap. The first handler looked up the subscription by transaction id alone, so a Play Store event could match an App Store row and write into the wrong user's subscription.

The real key is the pair: (store, original_transaction_id). Scope every lookup to both. The wrinkle is the null-store branch (some events arrive before the store is known), and standard SQL uniqueness treats two nulls as distinct, which would let duplicates slip through. Postgres 15 added NULLS NOT DISTINCT on unique indexes, which makes the null-store rows dedupe against each other as you would expect. The lookup mirrors the index: an eq on the store when it is known, an is null when it is not.

This branch never had an assertion test of its own. It was enforced by the unique index migration (NULLS NOT DISTINCT) and exercised through the insert-race tests below, which depended on the full scoped key to resolve the winner.

Failure 4: the TOCTOU race between lookup and insert

Lookup-then-insert is a time-of-check-to-time-of-use bug waiting for concurrency. Two deliveries for the same new subscription both look up, both see nothing, both insert. One wins. The other gets a unique-constraint violation: Postgres error 23505.

The naive response is to bubble that up as a 500. But a 23505 here is the normal outcome of a race you designed for. So catch it, re-read the row the winner just inserted, and fold your event into a single UPDATE against it. After the re-read you run the same staleness guard from Failure 2: the winner might be newer than you, in which case you do nothing and return success. The race collapses into the same monotonic-update path everything else uses.

The test I wrote for it: insert race: 23505 then re-read an OLDER winner folds into one UPDATE. Its sibling covered the case where the re-read winner is newer and the stale guard skips the update.

The meta-failure: acking 200 on internal errors

This is the one that scared me most, because it hides inside the code that handles the other failures.

The first handler caught internal errors (a failed lookup, a failed write) and returned 200. The intent was defensive: do not make the provider hammer us. The effect was catastrophic: a 200 tells the provider the event was processed, so it never retries. The event is lost. Worse, the dedupe row had already been written, so every future re-delivery of that event id short-circuits as "already processed." One transient database blip permanently drops a subscription update, and the dedupe machinery guarantees it can never self-heal.

The correct posture is fail closed. On any internal error, return 500 so the provider retries, and release the dedupe row you optimistically claimed, so the retry is allowed to actually re-process instead of being swallowed by the idempotency check. The dedupe row should only persist for deliveries you genuinely finished.

The test I wrote for it: retry after a failed attempt re-processes.

Before and after

The shape of the bug:

// BEFORE: one row object, rebuilt
// on every write
 
// nulls a valid flag on benign events
unsubscribe_detected_at:
  eventType === 'CANCELLATION'
    ? nowIso
    : null,
billing_issue_detected_at:
  eventType === 'BILLING_ISSUE'
    ? nowIso
    : null,
 
// lookup by transaction id alone:
// wrong store!
const { data: existing } = await supabase
  .from('subscriptions')
  .select('id')
  .eq('original_transaction_id', originalTxn)
  .limit(1)
  .maybeSingle();

And the fix, in TypeScript as it shipped (the write path later moved into SQL, below):

// AFTER: sticky churn, store-scoped
// key, out-of-order guard, TOCTOU
// recovery, fail closed
 
// only the owned flag
update({
  ...baseRow,
  ...computeChurnPatch(
    eventType,
    nowIso,
    false,
  ),
});
 
// the full unique key
lookup =
  store === null
    ? lookup.is("store", null)
    : lookup.eq("store", store);
 
// a late event: ignore it
if (
  existing?.id &&
  isStaleEvent(
    existing.last_event_at,
    eventTimeMs,
  )
)
  return new Response("OK (superseded)", {
    status: 200,
  });
 
// lost the insert race (TOCTOU):
// re-read the winner
if (insErr?.code === "23505") {
  const raced = await reReadExisting();
  writeErr = isStaleEvent(
    raced.last_event_at,
    eventTimeMs,
  )
    ? null
    : (await applyUpdate(raced.id)).error;
}
 
// free the dedupe row so RevenueCat
// retries
if (res.status >= 500)
  await releaseDedupeForRetry();

Note what the after still does on purpose: it returns 200 for a superseded event. A superseded event is a correct no-op, and acking it stops needless retries. The work is knowing which 200s mean processed and which ones hide a failure.

Six properties, and what guards each today

None of this is RevenueCat-specific. The same six properties are worth a test on any billing webhook, Stripe included. The fix shipped with the tests named above, and that design lasted five weeks.

Then one commit moved the whole write path out of TypeScript and into one Postgres function, apply_subscription_webhook_event. No incident drove it. That day I added a reconciliation job, which is a second writer to the same subscription rows, and an earlier migration had serialized it with a table lock, so unrelated users blocked each other. The replacement takes a transaction advisory lock per lineage, keyed on (store, original_transaction_id) with a null store coalesced to a fixed string, then one per user, then re-reads the row for update. Every writer goes through the same function, so they all queue on the same keys. Here is each property after that move:

Six properties, and what guards each today
PropertyFailureGuard todayGuarded
Re-delivery is idempotent: the same event id twice leaves the row identicalThe contractdedupe replay short-circuits all subscription RPCsYes
Benign events never null a churn or dunning flag they do not ownFailure 1Its test still passes, and nothing it tests is calledDead test
An event older than or equal to the stored watermark is droppedFailure 2The same: a passing test with no callerDead test
Lookups use the full provider key, store plus transaction idFailure 3None of its ownNo
Two deliveries for one new subscription end as one rowFailure 4The SQL function serializes writers; the handler test only covers a lock failure, not two concurrent writesNot covered
Internal errors return 500 and release the dedupe claimThe meta-failureThat test, TRANSFER RPC error returns 500 and releases dedupe and transient user lookup error fails retryablyYes

Two rows changed shape in the move. The lookup is now store is not distinct from, the same null handling as the index, and the NULLS NOT DISTINCT migration is unchanged. The insert race stopped being a code path: the second delivery waits on the lock and then finds the first one's row, so the insert race tests were deleted with the code they tested. The lock has a 2.5 second timeout, and the atomic-writer test feeds the handler Postgres error 55P03 (lock not available) and asserts a 500 and one dedupe delete. That is the handler's retry path, not two concurrent transactions: no test runs two deliveries against the SQL function at once, so the one-row property rests on the lock design, not on a test. The three error tests cover the three places the handler can fail after it has claimed the dedupe row.

Two tests that pass and guard nothing

Both rules, the sticky flags and the stale check, are now case expressions and an if inside the SQL function. computeChurnPatch and isStaleEvent still exist, and their tests still pass under the exact names above, but the handler no longer imports either one. The handler tests inject a fake client, so they assert that the function is called and that a superseded result becomes OK (superseded). They never run the SQL. The rule now exists twice: a TypeScript copy with tests and no caller, and a SQL copy with callers and no test. If someone edits the case for RENEWAL and it nulls the cancellation flag again, which is Failure 1 exactly, nothing goes red.

The suite was 20 Deno webhook tests at the last count in September, 13 on the handler and 7 on the pure logic, and it still runs inside npm run ci ahead of every release. The gap surfaced months later, on a re-read of the source. A test name that still exists and still passes reads as a guard in any review.

What would close it: a database test that applies a CANCELLATION, then a RENEWAL, then an older event to a real row and reads the flags back, and deleting the TypeScript copy so a green test stops implying a guard. Neither exists yet.

The original fix history is exhibit 3 in the bug museum.