Monetizing TeaQL in Public — Day 4: Renewals, Retries, and Out-of-Order Webhooks
A successful first checkout is only the start of a subscription. The next payment has a different transaction ID, arrives without a new user checkout, and may be delivered more than once. An older event can arrive after a newer one.
On Day 3, we connected the shared console to IAM and Billing. Today we add a backend slice: renewing an existing Organization subscription without duplicating access or trusting an Organization ID supplied by the payment payload.
This is local fixture verification, not a real Paddle Sandbox run. Tests use synthetic accounts, signed local HTTP requests, actual TeaQL/SQLite persistence, and a simulated clock. Real Paddle checkout, HTTPS webhook delivery, and payment collection remain unverified. No money was collected.
Start with the journey
Alex's Organization already has Plus from a confirmed initial payment. At the paid period end, access becomes Free unless another confirmed payment extends it. A recurring transaction then arrives. It belongs to the already bound subscription and customer, uses the same configured price, and describes the next paid period. Billing extends the existing entitlement.
If that event is delivered again, nothing is granted twice. If an older period arrives later, Billing records its receipt without changing the current expiry or the most recently applied charge.
This is a backend addition. The existing console can read the updated validity end through its current API; we did not add a cancellation button, a refund flow, or a new billing screen in this entry.
Identify a renewal separately from the first purchase
Paddle describes renewal transactions with the origin subscription_recurring.
Its completed-transaction event includes the transaction's billing period.
See the renewal scenario
and transaction.completed contract.
The first payment still follows our earlier server-created checkout binding. A recurring transaction follows a separate path after the HTTP adapter verifies the original body signature.
That path requires one configured recurring price, quantity one, automatic collection, USD, completed status, the configured billing interval and frequency, and no trial. Price changes, prorations, additional items, and one-off subscription charges are outside this slice.
A renewal does not need another checkout or a trusted custom_data.checkout_key.
Its authority comes from the binding already established by the initial payment.
Let the stored subscription identify the Organization
We reused the existing eight-object Billing model. A fresh semantic evaluation returned zero errors, warnings, and suggestions. There were no domain model changes and no regenerated library files.
The recurring payment locates the stored subscription by its provider ID:
const subscription = await Q.subscriptionRecords()
.withProviderSubscriptionKeyIs(subscriptionId)
.limit(1)
.comment('Resolve existing renewal subscription')
.purpose('Derive Organization from a previously confirmed subscription')
.executeForOne(context);
The complete E expression then reads that subscription's Organization binding:
const accountId = String(
E.subscriptionRecord(subscription).organizationAccountId().eval()
);
Billing checks the saved customer, price, and plan against the recurring event. It reads only the entitlement belonging to that account:
const entitlement = await Q.organizationEntitlements()
.filterByOrganizationAccount(accountId)
.limit(1)
.comment('Read bound renewal entitlement')
.purpose('Extend only this subscription and never shorten paid access')
.executeForOne(context);
The entitlement must reference this subscription and the same plan. Its last transaction must agree with the subscription mirror. A prior durable receipt provides the originating checkout relationship for the new receipt.
An event with a forged Organization ID in custom_data cannot redirect this
write. The tests deliberately supply another Organization's ID and an invalid
checkout key; the recurring payment still updates only the stored subscription's
Organization. A charge already recorded for another Organization is rejected.
If the renewal arrives before the initial subscription has been recorded, Billing returns a retryable failure. It does not acknowledge and discard that payment. A test retries the same event after initial provisioning and verifies that the renewal succeeds.
Advance access by paid period, not delivery order
The event timestamp is retained for traceability. Delivery order does not decide which paid period wins.
const validUntil = E.organizationEntitlement(entitlement).validUntil().eval();
const extendsAccess = end > Date.parse(validUntil);
For this unchanged-plan renewal path, an older or equal period becomes a durable
stale receipt. It does not move the subscription's last transaction backward.
A later period updates both the subscription and entitlement.
This monotonic rule is specific to successful renewals for the same plan and price. A refund, cancellation, or downgrade needs its own business rule; taking the maximum expiry everywhere would mishandle those operations.
A renewal must carry a valid billing period. We deliberately do not fill a missing period from today's subscription snapshot: a late transaction and the provider's current subscription might describe different periods.
The current model has one validity end, not a timeline of future grants. If an extending period has not started, the handler returns a retryable failure rather than granting access across a future gap. An expired period cannot extend access either. There is no local retry queue in this slice; provider retry and operator reconciliation still need real integration verification.
Commit the extension and receipt together
There are two independent deduplication checks:
- An event ID with the same body digest is an exact replay. The same event ID with a different body is a conflict.
- Different events describing an already recorded transaction do not apply that charge twice.
The database's existing unique constraints backstop event and transaction IDs. An advancing renewal performs these writes inside one TeaQL transaction:
subscription.updateLastTransactionKey(transactionId);
await subscription
.auditAs('Record verified recurring Sandbox transaction')
.save(context);
entitlement.updateLastTransactionKey(transactionId);
entitlement.updateValidUntil(period.ends_at as string);
await entitlement
.auditAs('Extend paid Organization access from a verified renewal')
.save(context);
The receipt is saved in the same transaction. The tests inject failures after the subscription save, entitlement save, and receipt save. Each failure leaves the prior business state and committed audit unchanged. Retrying then succeeds.
Queries are bounded and carry explicit comment and purpose. Mutations use the trusted backend context and an audit reason. Current model-aware Assist supplied the Q, E, and write APIs; generated domain source was not edited.
Observe time passing without waiting a month
The local journey uses a simulated clock. These are test dates, not elapsed production billing periods:
| Step | Simulated UTC time | Current access | Paid access until |
|---|---|---|---|
| Initial payment | November 28, 2026, 10:00 | Plus | December 28, 2026, 10:00 |
| Period expires, no renewal yet | December 28, 2026, 10:00 | Free | December 28, 2026, 10:00 |
| Recurring payment confirmed | December 28, 2026, 10:00 | Plus | January 28, 2027, 10:00 |
| Older period delivered afterward | December 28, 2026, 10:00 | Plus | January 28, 2027, 10:00 |
The journey ends with one subscription, one entitlement, and three receipts: initial payment, advancing renewal, and stale recurring payment. Reopening the database preserves the renewed expiry and replay protection.
The fixtures also verify the existing IAM boundary after renewal: Finance can read billing but cannot use the Developer entitlement endpoint; Developers can read access but not financial details. Another Organization stays Free.
Protect the data while retaining useful evidence
The renewal path reuses the existing minimal receipt fields: provider event and transaction IDs, a body digest, event kind, occurrence time, actor, and internal relationships. It does not store raw webhook bodies, card details, or an added copy of the customer's email.
The blog's dates and account identifiers are synthetic. The tests use owned temporary databases and runtime logs, close their resources, and remove the scratch directories on exit. Compact test results and the allowlisted journey report remain as evidence.
What is ready, and what remains
The final local Billing suite contains 47 passing tests, including 14 new renewal tests and the existing 33 Billing/integration regressions. It covers concurrent replay, changed payloads, stale periods, missing bindings, invalid periods, customer/price mismatches, transaction reuse across Organizations, signature rejection, atomic rollback, role separation, and database reopening. The TypeScript build passes as well.
No frontend or IAM implementation changed in Day 4; their earlier results remain Day 3 evidence rather than newly rerun suites. The shared console's existing read endpoints expose the renewed expiry, but this entry does not claim a new browser run.
Real Paddle Sandbox checkout and HTTPS webhook delivery remain pending. We have not implemented cancellation, refunds, proration, plan changes, metering, or provider-state reconciliation for those lifecycle events in this entry.
For other SaaS builders, the reusable pattern is to resolve the tenant through an established provider binding, make the paid period authoritative for this specific renewal operation, and commit receipt plus access update atomically. A renewal should not need another checkout or broader user permissions.
