ADR-139: A cancel prices before its transaction, then proves the plan on it
Date: 2026-11-10 Status: Accepted (amended 2026-11-25; amended 2026-11-29: no relief is planned; amended 2026-11-30: no threshold watermark is read, see the amendment; amended 2026-11-30 (later): the cancel proves the billing intervals, see the amendment)
Summary
Section titled “Summary”Amended 2026-11-30: billing thresholds are removed (migration 00259). The cancel neither reads nor re-reads a threshold watermark, and a second move is returned as ErrPeriodMoved, the new name of ErrWatermarkMoved. The rest is kept as the record of what was decided.
An immediate cancel, a scheduled mid-period cancel and dunning’s cancel now price their final invoice and plan their relief with no transaction open: the usage reads, the tax call (a network call for a Stripe Tax tenant) and the reads of the funding invoices all run first. Then one transaction writes the plan. Its first statement is a compare-and-set on the period the plan was priced from. Next it compares the items and the billing-interval rows with the ones planned, and reads the threshold watermark again. If anything moved, nothing is written and the cancel plans again once; a second move is returned as ErrWatermarkMoved, which the cancel API answers 409 concurrent_. Before, the pricing ran inside the transaction, so a slow tax call held the subscription row and a pool connection for its whole length. The cross-interval plan swap still prices inside its transaction (P1-23 PR-2).
Context
Section titled “Context”- The stall. The cancel’s transaction locked the subscription row with its first statement (
UPDATE subscriptions SET status = 'canceled'), then priced the final invoice. The pricing read plans, settings, intervals, meters, floors and usage on other pool connections, and calledprovider.. The Stripe client allows 30 seconds, with 2 retries. For that whole time the row, the sealed interval rows and the threshold invoice (Calculate FOR KEY SHARE) were held. - The pool.
DB_is 20 by default. Each cancel held one connection in its transaction and asked for a second one to price. With about 20 cancels at once, every connection was held by a transaction waiting for another connection: none could proceed until its request timed out, and every other request and background job waited too.MAX_ OPEN_ CONNS - The session kill. Postgres must kill a session idle in a transaction for 30 seconds (Postgres requirements). A tax call that long killed the cancel’s session, and a scheduled cancel recorded a counted billing failure.
- The target shape exists. The cycle close already prices before its transaction and proves its snapshot as the first statement (
commitPeriodClose, ADR-115).
Decision
Section titled “Decision”-
Plan.
billing.pricesEngine. PlanCancelBill(ctx, sub, at) subas canceled atat: the guards, the threshold watermark (read on its own connection), the lines, the tax call. Then, last, it plans the relief (planRelief): which funding invoices to void and the credit-note share of each other one, with each invoice’s room read on its own connection. It writes nothing and returns asubscription..BillWriter -
Prove.
subscription.opens the transaction through the store (Service CancelAtomicWithBill,FireScheduledCancellationWithBill), which take the plannedPeriodSnapshotandat:Read before the transaction Proof inside it Status, period start, next_(andbilling_ at cancel_for the scheduled cancel)at The first statement is the compare-and-set: UPDATE … WHERE status … AND current_. Zero rows resolve to not found, already terminated, superseded (scheduled), orbilling_ period_ start IS NOT DISTINCT FROM … AND next_ billing_ at IS NOT DISTINCT FROM … ErrWatermarkMoved. The status alone catches a trial the activation scan converted after the cancel read the row and before it read the billing intervals: the conversion moves no period column and no itemItems (id, plan, quantity) sameItemson the items read on the transaction. Every item writer locks the row firstBilling intervals ListItemIntervalsTxon the transaction must give the same rows on item, plan, quantity and start (sameIntervals). It catches an item added then removed, and a change made and undone, whichsameItemsmisses.ends_atis left out: the cancel’s own seal writes itThreshold watermark Read again on the transaction FOR KEY SHAREand compared with the planned instant (writePlanned), as the cycle close doesCollection pause Not proved. The final invoice takes its status from the locked row Funding invoices, credit-note room The existing checks: VoidUnchangedTxrefuses a changed invoice (invoice_), and each draft re-checks its room under the invoice’s credit-note lockchanged Usage, plans, prices, settings, billing profile None, as for the cycle close -
Write. On the same transaction,
writePlannedwrites the relief (voids, then the credit-note locks of every invoice it credits, then the drafts), then numbers and inserts the final invoice, its finalize audit row and its usage-below-zero row; the service writes the cancel’s audit row; the store retires the row and queuessubscription.. Nothing in the transaction reads on another connection or calls a provider: credit-note create reads its invoice on the caller’s transaction (canceled invoice.,GetTx ListLineItemsTx), and the void’s credit return binds no clock. -
The instant
at. Each attempt of the immediate cancel binds its instant from the caller’s context: on the API’s unbound context the second attempt reads a new wall-clock instant; dunning’s context arrives bound, so both attempts use dunning’s instant, as do both on a test clock. An active row whose period starts afteratis not planned: priced from it, the final invoice bills nothing and the relief skips the new period’s prebill, while the compare-and-set passes. The attempt answersErrWatermarkMoved. A trialing or draft row is planned (a cancel before the first paid period is the free trial cancel, ADR-069). The scheduled cancel’satis itscancel_, the contracted instant, and it is not checked against the period start (ADR-097).at -
Planning again. The immediate cancel runs at most two attempts. After the second
ErrWatermarkMovedit returns the error: the cancel handler answers409concurrent_(not stored by the idempotency layer); dunning labels its runchange action_and runs it again 24 hours later. The scheduled cancel returnsfailed ErrWatermarkMovedtobillSubscription, which reads the row again and fires again once, as it does for a moved period close; a second miss leaves the subscription due, and the drain counts it (errStillDue).
Why this design
Section titled “Why this design”- The lock is held only while writing. Nothing slower than a statement runs between the first statement and the commit. A cancel holds one connection, briefly; the tax call holds none.
- One rule for every period closer. The cancel proves its snapshot exactly as the cycle close does, so a reader learns one mechanism.
- A moved snapshot is not a failure. A race that used to wait on the row lock now plans again, so dunning and the billing run do not record a failure for it.
Alternatives considered
Section titled “Alternatives considered”- A. No second plan. A moved snapshot always answers
409or returns the error. About 40 lines less, but dunning’s cancel would wait 24 hours, and a scheduled cancel would count a billing failure, for a race that today only waits on the row lock. - B. The engine owns the transaction, as
commitPeriodClosedoes. The cancel’s audit row, thecanceled_provenance and the swap’s item write would move behind engine callbacks. About twice the change, with no lock or pool gain over the chosen shape.by
Consequences
Section titled “Consequences”Positive
Section titled “Positive”- A slow Stripe Tax call no longer blocks other writers of the subscription, and no number of concurrent cancels can hold every connection.
- The 30-second idle-in-transaction kill no longer applies to the tax call.
- An immediate cancel that read a row whose period started after its instant no longer cancels with the new period unrelieved: it plans from the new period, or answers the error.
Risks / open items
Section titled “Risks / open items”- A discarded plan costs one tax calculation. It is paid for and never committed, so no liability is reported. Its
tax_row stays with no invoice; nothing reads unlinked rows, and a cancel that rolls back after pricing left the same row before. The scope key carriescalculations canceled_, so the API cancel’s second plan is a second calculation; dunning’s, a test clock’s and the scheduled cancel’s reuse the first while the lines are unchanged.at - A relief refusal still comes after the tax call, as since P1-08:
funding_andinvoice_ tax_ pending invoice_leave one discarded calculation.changed - Dunning’s time budget. Dunning’s cancel runs under a 5-minute charge hold. Two plans during a Stripe Tax brownout can outlast it; the relief’s void then refuses, the cancel rolls back, and the run is labelled
action_and runs again after 24 hours. Nothing is lost.failed - The cross-interval plan swap is unchanged until P1-23 PR-2: it still prices and plans its relief inside its transaction (
BillOnPlanSwapDraftsTxplans and writes in one call). - The teardown deadlock (ADR-136, D2) stays possible at the watermark re-read; the cancel handler still converts it.
References
Section titled “References”- ADR-056, ADR-115, ADR-118, ADR-066, ADR-097, ADR-136
internal/:billing/ engine. go PlanCancelBill,writePlanned,planRelief,writeReliefTxinternal/:subscription/ service. go cancel,cancelOnce,FireDueScheduledCancel,sameIntervalsinternal/:subscription/ postgres. go CancelAtomicWithBill,FireScheduledCancellationWithBill- Tests:
internal/,billing/ cancel_ plans_ before_ tx_ integration_ test. go internal/api/ cancel_ replan_ e2e_ test. go
Amendment 2026-11-25: no scheduled cancel is priced here
Section titled “Amendment 2026-11-25: no scheduled cancel is priced here”A cancel on a chosen date is removed, so the scheduled cancel this record
prices beside the immediate cancel (its at at cancel_, and its
compare-and-set on cancel_) no longer exists. The immediate cancel and
dunning’s cancel are the only callers of this planning.
Amendment 2026-11-29: no relief is planned
Section titled “Amendment 2026-11-29: no relief is planned”A cancel writes no relief
(ADR-118 amendment),
so PlanCancelBill prices only the final invoice, and its writer re-reads
the threshold watermark and writes that invoice. The funding reads, the
funding_ refusal, and the proof rows for the funding
invoices (invoice_, each draft’s room) are gone.
The cancel’s transaction takes its locks in the period close’s order: the
subscription row (the compare-and-set), the threshold invoice FOR KEY SHARE, then the tenant’s invoice number row. It takes no credit-note lock,
so it never waits for one while it holds the number row. Dunning’s cancel
no longer runs as the owner of the invoice’s charge hold: nothing in it
voids that invoice.
Amendment 2026-11-29: an item has no quantity
Section titled “Amendment 2026-11-29: an item has no quantity”Items have no quantity, so the cancel compares less: the live items on item
and plan (sameItems), and the billing-interval rows on item, plan and start
(sameIntervals). Both checks stay, as neither implies the other: a removed
item only ends its interval, which sameIntervals leaves out, and an item
added then removed leaves the live items as they were.
Amendment 2026-11-30: no threshold watermark
Section titled “Amendment 2026-11-30: no threshold watermark”Billing thresholds are removed (migration 00259), so no invoice bills part
of an open period. The cancel’s plan no longer reads the threshold
watermark, and its transaction no longer reads it again FOR KEY SHARE:
the table row “Threshold watermark” and the watermark steps in the
amendments of 2026-11-29 are gone. The transaction takes the subscription
row (the compare-and-set), then the tenant’s invoice number row. The
compare-and-set and the comparisons of the items and the billing-interval
rows stay. ErrWatermarkMoved is renamed ErrPeriodMoved, and the cancel
API still answers it with 409 concurrent_. The risk of the
teardown deadlock at the watermark re-read goes with the re-read.
Amendment 2026-11-30: the cancel proves the billing intervals
Section titled “Amendment 2026-11-30: the cancel proves the billing intervals”A subscription holds one plan, in place of items (migration 00260). The
cancel’s transaction compares the billing-interval rows on plan and start
(sameIntervals); the comparison of the live items (sameItems) is gone.
The plan changes only when the close applies a scheduled change at a period
boundary, and that apply ends the open row and opens a new one, so a changed
plan shows in the rows. A cancel seals the subscription’s one open row.
Stuck, or found a bug? Ask in Discussions · Open an issue