usage-meteringcapstone

Usage Metering & Billing Engine

A usage-billing backend built around retry-safe event recording, explicit quota decisions, and integer-based cost rollups.

Node.jsExpress 5Prisma 7PostgreSQLStripeZod
0
stored event for same-key retries
0
plans: Free and Pro
0
metered usage types
0
Stripe webhook event types handled

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.

01

Context & problem

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:

  • Usage is recorded reliably, and retries never create duplicate billable events.
  • Quota boundaries are enforced clearly: a request at the limit is treated differently from one that exceeds it.
  • Small per-event costs are aggregated without being rounded away.
02

Solution

01Service architecture

An Express API with Zod validation at the request boundary, organised in layers — routes, middleware, services, repositories — on top of PostgreSQL.

02Idempotent metering

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.

03Quota enforcement

Every metered request is checked in a fixed order:

  • Subscription standing first — a subscription that isn't in good standing gets 402.
  • Plan limit second — a request that would exceed the monthly allowance gets 429.

04Cost calculation

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.

05Stripe billing

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.

06Usage alerts

A scheduled job checks usage-alert thresholds and records each run, retrying failures up to three attempts with backoff.

07Scope & known trade-offs

  • Tenants are identified by a trusted x-tenant-id header rather than real authentication.
  • Billing periods are UTC calendar months, not Stripe billing periods.
  • Quota checks and event insertion are separate operations, so concurrent requests with different keys can still overshoot a quota.
// how POST /generate is validated, metered, and priced
client
tenant + idempotency key
Express routesHTTP endpoints
middlewaretenant resolution + Zod validation
meter + quota servicesidempotency · 402 / 429
cost serviceinteger micro-cent pricing
repositoriestenant-scoped database access
PostgreSQL
usage events · unique tenant/key
// how Stripe collects the Pro subscription payment and the app syncs it
customer
starts Pro checkout
billing routePOST /billing/checkout
Stripe Checkout$29/month subscription · test mode
customer paysStripe-hosted subscription checkout
signed Stripe webhookcheckout.session.completed
webhook routeverify signature + deduplicate event
webhook service
save subscription · set tenant plan to Pro
03

Measurable impact

◆

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.

$ ./say-hello.sh

Let's talk about your backend.

Open to backend and platform engineering roles, and to interesting infrastructure problems. Fastest reply is by email.

© 2026 Elyas BromandBuilt with ♥ by Elyas Bromand↑ back to top