Repository navigation
fix(billing): close intake race with per-org advisory lock (#3179) - #3183
Merged
Merged
Conversation
This was referenced Apr 25, 2026
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
force-pushed
the
bokelley/intake-race-lock
branch
from
April 25, 2026 23:46
4a1c258 to
b728578
Compare
- 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]>
3 tasks done
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
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
References
🤖 Generated with Claude Code