A usage-billing backend built around retry-safe event recording, explicit quota decisions, and integer-based cost rollups.
A backend service that records API-call and AI-token usage, enforces Free and Pro plan limits, calculates usage costs, and syncs subscriptions through Stripe test-mode billing.
Charging every customer the same monthly amount is a poor fit when usage varies widely. Heavy users can cost more to serve than their subscription covers, while light users pay for capacity they barely use.
Usage-based pricing makes cost proportional to consumption — but only if the system underneath gets a few things right:
An Express API with Zod validation at the request boundary, organised in layers — routes, middleware, services, repositories — on top of PostgreSQL.
The metering service looks up an existing event by tenant and idempotency key before recording a new one.
A database uniqueness constraint plus conflict recovery means concurrent retries of the same key always resolve to the single stored event.
Every metered request is checked in a fixed order:
402.429.Costs are calculated in integer micro-cents. Totals are summed per period before converting to cents, so many tiny events aren't each rounded down to zero.
The usage endpoint returns the resulting cost totals.
Customers upgrade to the fixed-price Pro plan through Stripe-hosted Checkout ($29/month in the documented test setup). Stripe processes the subscription payment.
Signed, deduplicated webhooks report checkout and subscription events, so the service keeps subscription status and the tenant's plan in sync.
Measured usage cost is reported by the API but isn't separately charged through Stripe.
A scheduled job checks usage-alert thresholds and records each run, retrying failures up to three attempts with backoff.
x-tenant-id header rather than real authentication.Verified same-key retries return the original response and create one usage row, including when two requests race on a new key.
Verified quota boundaries: a Free tenant can reach exactly 1,000 API calls for the month, while the next call is rejected with 429; a past-due subscription is rejected with 402 before quota evaluation.
Kept token pricing in integer micro-cents and verified period-level rounding: three 345,000-micro-cent events roll up to one cent instead of rounding individually to zero.
Implemented Stripe Checkout and handlers for checkout completion, subscription updates, and subscription deletion, with signature verification and event deduplication.
Added a scheduled usage-alert job that checks 80% and 100% thresholds, retries failures up to three attempts, and records successful or failed runs.