Billing Architecture & Technical Specs
Module license lifecycle, dunning automation, Stripe integration with SCA / 3D Secure, billing queue, and real-time usage-limit enforcement.
Capabilities & Performance
License lifecycle
create → validate → trial (optional) → active → expired / suspended → cancelled
License statuses
`active`, `expired`, `suspended`, `cancelled`, `trial`
Billing cycles
monthly, annual
Dunning retry schedule
1st (+1 day), 2nd (+3 days), 3rd (+7 days)
Dunning max retries
3 before auto-suspend
Billing queue
daily per-tenant cron — trial expiry, invoice auto-charge, nightly Stripe reconciliation
Stripe surface
customers, subscriptions, prices, webhooks, SCA-ready with 3D Secure
Limit enforcement
real-time hard block at 100% of the plan limit, configurable per module; currently wired for users (Auth) and products (Commerce)
Feature flags
per-license boolean map controlling module-level access
Trial periods
configurable per module, auto-convert or auto-cancel at expiry
1. License Engine (Full License Lifecycle)
The license engine manages the complete module license lifecycle from creation to cancellation.
What a license tracks:
- Which tenant and which module it applies to
- License type — perpetual, subscription, or trial
- Tier — free, starter, pro, or enterprise
- Status — active, expired, suspended, cancelled, or trial
- Key dates — created, activated, expires, cancelled
- Trial details, when applicable — trial length, start date, and conversion date
- The linked Stripe subscription, customer, and price, plus billing cycle (monthly or annual) and amount
- A feature-flag map and a usage-limits map, both scoped to that license
- Where the license originated — marketplace signup, admin action, or migration — and, on upgrade or downgrade, a reference back to the previous license so the lineage is never lost
Tenants and integrators can look up the active license for a module, or look one up by its linked Stripe subscription, at any time — see the Quick Start guide for the exact endpoints. A compact "license state" summary is also available for frontend use, covering whether a license exists, its type/tier/status, trial countdown (days remaining, start/expiry dates, whether it will auto-convert), enabled features and limits, and the next billing date and amount.
Trial management: Trial length is configurable per module (14 days by default). The trial start date is recorded when the trial begins, and the license automatically converts to a paid subscription once payment is added, or expires gracefully if it isn't.
Upgrades and downgrades: Changing tiers creates a new license record linked back to the previous one, migrates any data the new tier requires, and — where proration is enabled — charges or credits the price difference either immediately or at the next renewal.
Feature flags per license: Each license carries its own map of enabled features — for example API access, webhooks, multi-user support, SSO, advanced analytics, and custom integrations — alongside usage limits such as max users, max storage, and max API calls. Higher tiers unlock more of the map by default, and individual flags can be overridden per license.
2. Dunning Engine (Failed Payment Automation)
| Stage | Subject | Purpose |
|---|---|---|
| First notice | "Payment Failed - Action Required" | Prompts the customer to update their payment method |
| Second notice | "Second Payment Attempt Scheduled" | Warns that another retry is coming in a few days |
| Final notice | "Final Payment Notice" | Last warning before the account is suspended |
| Suspended | "Service Suspended" | Confirms suspension and explains how to reactivate |
3. Billing Queue (Automated Job Processing)
The billing job queue manages background jobs for all billing operations.
Job Types:
- Retry a failed payment on the dunning schedule
- Generate invoices on each subscription's billing cycle
- Reconcile subscriptions against Stripe on a nightly basis
- Clean up expired trials
Two clocks run per tenant. An hourly renewal sweep is the recurring engine itself: it finds every subscription whose renewal moment has passed (and every trial whose trial has ended), takes a per-subscription lock, re-reads the row inside it, and renews — see section 5. A daily job expires module trials, auto-charges any invoice that is open, due and has a payment method on file (up to 100 per run), and reconciles provider-managed subscriptions against the provider to catch drift.
Both are ordinary events on the platform bus (tenant.cron.hourly, cron.daily), so a missed hour is retried like any other delivery, and an operator can run the renewal sweep on demand for one tenant or one subscription.
4. Limit Enforcer (Usage Limits)
The limit enforcer monitors and enforces module usage limits.
Limit key shape: any maxX key on a license's limits map (e.g. maxUsers, maxProducts, maxContacts) — the mechanism is generic, so any module can call it for any count-based limit. Two call sites are wired in today: max users (Auth, on user creation) and max products (Commerce, on product creation). Other modules — CRM, BI, Marketing, Fleet — aren't wired to this enforcer yet.
How enforcement works: Usage is checked in real time against the tenant's plan limits on the relevant create operation. If a module has no limit configured for that key, usage is unrestricted. Once usage reaches the plan limit, the operation is hard-blocked with an upgrade message. There's no separate warning tier today — a limit either isn't reached (allowed) or is reached (blocked).
5. Subscription Lifecycle Management
Aeion Billing is the recurring engine for everything a tenant's customers subscribe to — a store's subscribe-and-save coffee, a course, a fan tier, a SaaS plan. The module that sells the thing owns what it delivers; billing owns the money and the clock. One vocabulary, one set of announcements, every provider.
Status vocabulary: pending → trialing → active → past_due → paused → canceled → expired. Every transition is timestamped and announced as billing.subscription.<verb> (created, activated, renewed, renewal_invoiced, past_due, paused, resumed, canceled, expired), so other modules react without polling.
Every subscription carries: who it belongs to (a user, a customer record, or the tenant itself for platform plans), where it came from (source and sourceId name the owning module's record), the cadence (interval × intervalCount, or a plan cycle), quantity and unit amount, the saved payment method it renews on, and a billing mode. scheduled renews on the clock. on_request is a membership: the customer is enrolled but never billed or shipped on a timer — they order when they need to. The engine never renews an on_request row, whatever its dates say.
Renewal, every hour:
- The sweep lists rows whose
nextBillingAthas passed (trials: whosetrialEndhas passed) and takes a lock per row; the row is re-read inside the lock, so two workers or a redelivered hour cannot renew the same period twice. - One invoice is raised for the period (source
subscription, the line carrying the period it covers). - With a saved payment method and a charging provider, the method is charged through the payments layer with a key scoped to the subscription and period — a retry of the same period is the same charge, never a second one. Success: the invoice is paid, the period rolls,
billing.subscription.renewedis announced with the invoice, the transaction and the new period. The owning module finishes its side on that announcement — commerce raises the renewal order, already paid. - With no saved method, or a manual provider, the invoice stays open and the period still rolls;
billing.subscription.renewal_invoicedis announced. A customer who pays another way is not a failed customer. When that invoice is collected outside billing — the renewal order confirmed paid by staff, a folio settled at the desk — the owning module's paid announcement names the invoice and billing settles it: marked paid with the transaction on its record, andbilling.invoice.paidannounced so the fulfilment side finishes exactly as it would for a card charge. An invoice billing already collected is left as it is. - A charge that fails goes to dunning (section 2); the subscription is
past_dueandbilling.subscription.past_dueis announced. A retry that later succeeds pays the invoice, andbilling.invoice.paidsettles the renewal exactly as step 3 would have — once.
Provider-managed subscriptions (a subscription object created at Stripe, for example) keep renewing at the provider; the nightly reconciliation keeps the local row in step. The hourly sweep only clocks subscriptions Aeion bills itself.
Lifecycle operations — activate, pause, resume, skip a period, change cadence or quantity, cancel now or at period end, renew now — go through the billing.subscriptions service, which handles provider propagation, the period, and the announcement. Workflow automations and the customer portal use the same operations.
What a renewal costs. The module that sold the subscription prices each period before billing invoices it (a <source>.renewalPricer service; commerce prices with the subscription's own unit price, today's delivery rate for its method, and tax for its current address — the same engines checkout uses). The renewal invoice carries the subscription line, a delivery line and the tax breakdown; the saved card is charged for that total, and the announcement carries subtotal, tax and delivery so the order commerce raises totals to exactly what was invoiced. A pricer that cannot answer skips the renewal for that tick rather than charge the wrong amount; a source with no pricer is invoiced its subscription amount as before.
What a customer keeps. A customer who cancels keeps the period they paid for: the subscription stays active with a cancel scheduled, the storefront says when it ends, and when the period is over the renewal clock — billing's or commerce's, whichever owns the tenant's renewals — ends it instead of raising another invoice or order. Skip and pause are refused once a cancel is scheduled; address and quantity can still change for the remaining deliveries, and the customer can change their mind: _Keep subscription_ undoes the scheduled end on both rows and at the provider, and announces billing.subscription.reinstated. A scheduled cancel is announced as billing.subscription.canceled with the subscription still active, and again with status canceled (and endedAtPeriodEnd) when the clock ends it — the role, the customer tag and the cancellation email act on the first, the revocations on the second, so a consumer must branch on the announced status, never on the event name alone. A membership that only bills on request has no period to honour and ends at once, as does a paused or past-due subscription. Resuming a paused subscription keeps a period that is still running; if the paid period lapsed while paused, a new period starts and is due immediately, so the next tick charges it — there is no free period and no back-charge for the pause. Skipping advances by the subscription's own cadence (every two weeks moves fourteen days) in UTC, and changing cadence takes the product's price for that cadence.
What a plan grants. A billing plan can declare what an active subscription confers beyond the product itself: a workspace role, a customer tag, and entitlements (extension ids for products that gate features per customer). The grants ride on the announcements that confer or revoke them — created (when the subscription is born active or trialing), activated, canceled and expired — so the modules that act need nothing from billing's tables. A subscription born pending grants nothing until it is activated; pausing does not revoke.
- Roles are applied by the auth module, and only to a customer who already holds a membership in the workspace: a subscription never turns a portal customer into staff, and never creates a role — a plan that names a role nobody has created is logged for the operator and skipped. The member's previous role is recorded when the grant is applied and restored when the subscription ends, and only while they still hold the granted role. An operator who changed the role in between keeps their change. A plan that declares no role grants none, in either direction: an admin who cancels a subscription stays an admin.
- Customer tags are applied by commerce to the customer record the subscription belongs to (its commerce customer, or the customer linked to its user) and removed when it ends. Segments, pricing rules and support views key on them.
- Entitlements on a billing plan are for a tenant's own customers. They never touch the tenant's platform entitlements, which come from platform plans.
6. Stripe Integration
Aeion Billing integrates with Stripe for payment processing.
What Aeion manages in Stripe: Aeion creates and manages the corresponding Stripe customer, subscription, and price objects behind the scenes as part of the license lifecycle — you don't need to touch the Stripe dashboard for routine plan changes.
Webhook Handling: Stripe webhooks map directly to license and subscription events:
customer.subscription.created— activates the licensecustomer.subscription.updated— syncs subscription changescustomer.subscription.deleted— deactivates the licensecustomer.subscription.paused/resumed/trial_will_end— keeps the license status in step with the subscription's pause/resume/trial-ending stateinvoice.paid— marks the invoice paid and confirms the licenseinvoice.payment_failed— triggers the dunning flow
Linking a subscription: Once a Stripe subscription is created, Aeion links it to the license record and marks the license active.
6b. Payouts settle the clearing account
A card sale posts to merchant clearing when it is taken. When the provider pays out (Stripe payout.paid), billing records the payout — the net that reached the bank, and from the balance transactions it swept, the gross and the fees the provider kept — in the payouts collection and announces billing.payout.paid. Finance then posts DR cash (net) / DR payment processing fees / CR merchant clearing (gross), once per payout. A failed or canceled payout is recorded as failed and announced as billing.payout.failed. If the provider cannot list the payout's transactions the payout still settles, for its net, with no fee line and feesResolved: false on the row.
7. Disputes and chargebacks
A dispute arrives from the provider's webhook and billing is the one authority for it, whatever module sold the thing. On charge.dispute.created the transaction is marked disputed, a dispute record opens with the provider's evidence deadline, a critical alert is raised, and billing.dispute.created is announced: commerce puts the order's fulfilment on hold, events hold the tickets, hospitality flags the folio — each module answers with a reason when the transaction bought nothing of theirs. Evidence is submitted through billing before the deadline; an unanswered dispute is lost automatically.
charge.dispute.closed settles it. Won: the transaction returns to succeeded and billing.dispute.won releases what was held. Lost: the funds are gone, so billing records a chargeback refund exactly once — a refund row with reason chargeback, the dispute on its record — and announces it like any completed refund, which is what reverses the sale's revenue in the general ledger; billing.dispute.lost marks the order's payment disputed and cancels the tickets. A redelivered close changes nothing.
While the retry count is under the maximum (3), the next action is always another retry on the schedule above. Once retries are exhausted, the next action is to suspend if there's an active subscription or module license attached, or to cancel outright if there isn't.
A license check returns one of the following outcomes:
- No license found → invalid, no access
- License suspended → invalid
- License cancelled → invalid
- License expired (and not a trial) → invalid
- License in trial → valid, with days-remaining reported to the caller
- Otherwise → valid
Feature availability is resolved per license, with sensible tier defaults that any individual license can override:
| Feature | Free | Paid tiers | Enterprise |
| ------------------- | ---- | ---------- | ---------- |
| API access | Off | On | On |
| Webhooks | Off | On | On |
| Multi-user | Off | On | On |
| SSO | Off | Off | On |
| Advanced analytics | Off | Off | On |
| Custom integrations | Off | Off | On |
Every invoice tracks the amount and currency, its status (pending, paid, failed, or past due), a due date, how many dunning attempts have been made against it, and which subscription or license it belongs to.
| Tier | Max Users | Max Storage | Max API Calls |
| ------------ | --------- | ----------- | ------------- |
| Free | 5 | 1 GB | 10,000 |
| Starter | 25 | 10 GB | 100,000 |
| Professional | 100 | 100 GB | 1,000,000 |
| Enterprise | Unlimited | Unlimited | Unlimited |
Saved payment methods (the vault)
| Endpoint | What it does |
|---|---|
| `GET /api/v1/billing/payment-methods` | The signed-in customer's active methods, default first |
| `POST /api/v1/billing/payment-methods/setup-intent` | Starts saving a card: creates the processor-side customer if needed and returns the client secret the browser confirms |
| `POST /api/v1/billing/payment-methods` | Attaches the confirmed method to the customer and records it; the same card attached twice is one method |
| `POST /api/v1/billing/payment-methods/:id/default` | Makes it the default and clears the previous default |
| `DELETE /api/v1/billing/payment-methods/:id` | Detaches it at the processor and marks the record removed; the next method becomes default |