Skip to content

fix(billing): close intake race with per-org advisory lock (#3179) - #3183

Merged
bokelley merged 3 commits into
mainfrom
bokelley/intake-race-lock
Apr 25, 2026
Merged

bokelley merged 3 commits into
mainfrom
bokelley/intake-race-lock

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Closes #3179. PR #3171 introduced `blockIfActiveSubscription` to refuse minting a duplicate sub when one already exists, but the guard is a non-transactional read followed by a non-transactional Stripe write. Two concurrent intakes can both pass the read and both create a subscription — the millisecond version of the months-apart Triton bug.

This PR wraps the (re-guard + Stripe write) section of `POST /api/invoice-request` and `POST /api/invite/:token/accept` in a Postgres advisory lock keyed on `hashtext(orgId)`. `getSubscriptionInfo` queries Stripe live, so by the time a second caller acquires the lock and re-runs the guard, the first caller's subscription is already visible and the guard correctly blocks.

What changed

  • `server/src/billing/org-intake-lock.ts` (new) — `withOrgIntakeLock(orgId, fn)` helper. Opens a transaction, takes `pg_advisory_xact_lock(hashtext(orgId))`, runs fn, commits on success / rolls back on error. Lock release is automatic on transaction end.
  • `server/src/routes/billing-public.ts` — invoice-request now does (re-guard + createAndSendInvoice) inside the lock. The original fast-path guard call early in the handler is preserved as a short-circuit for the common case.
  • `server/src/routes/invites.ts` — same pattern on invite-accept.
  • `server/tests/unit/org-intake-lock.test.ts` (new) — 5 tests covering BEGIN/lock/COMMIT ordering, ROLLBACK on fn error, ROLLBACK on lock-acquisition error, connection release on rollback failure, typed return passthrough.

What's deliberately not in scope

`POST /api/checkout-session` is not wrapped in the lock. Stripe Checkout sessions are URLs, not subscriptions — the actual sub gets created only when the user completes the hosted page. Two concurrent calls just produce two session URLs; the user would have to pay on both for it to matter. That race lives at the `customer.subscription.created` webhook layer and will be closed in a separate follow-up issue.

Test plan

  • `npm run typecheck` — clean
  • `npm run test:server-unit` — 2211/2211 (5 new)
  • Manual concurrency test: open two browser tabs to the dashboard's "Pay by invoice" flow, click both at once, confirm only one invoice issues and the second returns 409 with the existing sub's details

References

🤖 Generated with Claude Code

bokelley and others added 2 commits April 25, 2026 19:45
POST /api/invoice-request and POST /api/invite/:token/accept now wrap
their blockIfActiveSubscription re-check + Stripe write in a transaction
that holds pg_advisory_xact_lock(hashtext(orgId)). Two concurrent intakes
for the same org serialize: the first mints the sub and commits; the
second's re-check sees the live sub and returns 409.

The early fast-path guard call is preserved — it short-circuits the
common case without locking. The lock window is the smallest one that
closes the read-then-write race (re-guard + createAndSendInvoice).

Tests: 5 new for the lock helper covering BEGIN/lock/COMMIT ordering,
ROLLBACK on fn error, ROLLBACK on lock-acquisition error, connection
release on rollback failure, typed return passthrough.

POST /api/checkout-session is intentionally NOT wrapped — Stripe
Checkout sessions are session URLs, not subscriptions. Two concurrent
session-create calls produce two URLs; the duplicate-sub case requires
the user to actually pay on both. That race lives at the
customer.subscription.created webhook layer and will be closed
separately.

Closes #3179.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Add SET LOCAL lock_timeout (10s) and statement_timeout (30s) inside
  the locked transaction. Prevents a stuck Stripe call from parking
  the pool connection indefinitely (security M3).
- Log a warning when ROLLBACK itself fails (was silently swallowed).
  Indicates connection drop mid-write — pool auto-discards the dead
  connection so no leak, but operators should know it happened
  (security L1).
- Make invite-accept's outcome handling shape match billing-public's:
  explicit `if (intake.kind === 'invoiceFailed')` branch instead of
  ternary + null check (code-reviewer 1).
- Document at the markMembershipInviteAccepted call that running it
  outside the lock is safe ONLY because the in-lock guard re-check
  catches duplicate-sub attempts. Locks the invariant in code so a
  future refactor can't silently re-open the window (code-reviewer 2).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley force-pushed the bokelley/intake-race-lock branch from 4a1c258 to b728578 Compare April 25, 2026 23:46
- Match discriminated-union order between billing-public.ts and
  invites.ts (block | invoiceFailed | success in both). Aids future
  grep / refactor.
- Add INVARIANT name to the markMembershipInviteAccepted comment so a
  future Ctrl-F for "in-lock-guard-re-check" lands on the load-bearing
  reasoning.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@bokelley
bokelley merged commit b3c1960 into main Apr 25, 2026
10 of 11 checks passed
@bokelley
bokelley deleted the bokelley/intake-race-lock branch April 25, 2026 23:57
bokelley added a commit that referenced this pull request Apr 26, 2026
* feat(billing): webhook-side dedup on customer.subscription.created (#3184)

Closes the cross-path race that the intake-side guards (#3171
blockIfActiveSubscription, #3179/#3183 advisory lock) leave open.
Stripe Checkout creates a session URL, not a subscription — the sub
gets minted only when the user completes the hosted page. So two
concurrent intake paths (e.g., admin invite + member checkout) can
both pass their guards before either mints a sub, and the user can
complete both within seconds. Triton hit this in April 2026.

On customer.subscription.created we re-check the customer's full
live-sub inventory. If another live sub (active/trialing/past_due)
exists, we cancel the new one with proration refund, alert ops via
notifySystemError, and skip the org-row UPDATE so the surviving sub's
state stays intact.

Lookup or cancel failures fall through to "don't know" — a missed
duplicate is caught by the periodic integrity audit
(one-active-stripe-sub-per-org). Failing closed during a Stripe blip
would block legitimate first-time subscriptions.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(billing): address reviewer feedback on webhook dedup

Three concrete reviewer-flagged fixes:

1. (BLOCKER) The follow-up customer.subscription.{updated,deleted}
   events for the canceled duplicate sub were clobbering the surviving
   sub's row state — exactly the bug this PR was meant to prevent. The
   suppressOrgUpdate flag only gates the .created event. Added a
   structural guard at the top of the .updated/.deleted branches: if
   the event's sub id isn't the one we currently track AND the event's
   status is non-live, ignore the event. .created is exempt because
   that's how we *learn* about a new sub.

2. Stripe webhook retries of customer.subscription.created would
   re-invoke the helper after we already canceled. Stripe's cancel on
   an already-canceled sub returns 400, not a silent no-op, which
   threw and re-fired the ops alert. Added an early-return when the
   incoming subscription.status is already non-live.

3. subscriptions.list({ status: 'all', limit: 20 }) could miss the
   live sub on customers with many canceled experiments. Bumped to
   limit: 100 (Stripe max) and warn when has_more.

Also addressed:
- Alert message correctly reflects cancel failure ("COULD NOT be
  canceled — cancel manually") instead of unconditional
  "was canceled with proration".
- Enriched the alert with new sub amount, lookup_key, and
  collection_method so ops can triage without clicking into Stripe.

Test coverage extended to: retry-of-canceled, page overflow, alert
content on cancel-success and cancel-failure, alert payload fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrent intake race: two simultaneous billing intakes can both pass the duplicate-sub guard

1 participant