Delivered remotely for a business based in Seattle, United States. Names withheld by agreement.
Project Overview
Industry: SaaS Billing & Revenue Retention
Solution scope: A subscription lifecycle, metered usage rating, and automated dunning orchestration platform engineered with Node.js, TypeScript, Stripe API, PostgreSQL, Redis, BullMQ, and React.
Context: B2B software platforms selling hybrid seat-plus-usage plans outgrow basic checkout callbacks as customers swap annual and monthly terms mid-cycle, add contractor seats, exceed API quotas, or let corporate cards expire. Without a dedicated billing layer between the Stripe API and product feature gates, finance teams untangle mismatched spreadsheets while involuntary churn erodes revenue. We built a subscription orchestration platform keeping Stripe financial state, PostgreSQL ledgers, and Redis entitlements synchronized.
Revenue & Billing Bottlenecks
Webhook race conditions desynchronized customer access. Out-of-order invoice.paid and customer.subscription.updated events caused upgraded workspaces to lose features or stall in trial states.
High-frequency usage telemetry strained transactional tables. Writing one database row per billable API call threatened checkout latency and complicated month-end reconciliation.
Generic retry schedules missed recoverable renewals. Treating hard declines and temporary bank holds identically wasted retry attempts without alerting owners before grace periods elapsed.
Rigid plan definitions blocked deal-desk flexibility. Customer success teams lacked clean controls to grant trial extensions, pause accounts, or grandfather legacy cohorts safely.
Architectural Strategy
Treat Stripe as the payment rail and PostgreSQL as the state machine. Stripe remains authoritative for payment methods, tax calculation, and invoice collection, while PostgreSQL owns versioned plan metadata, webhook inbox deduplication, grace-period policies, and a local accounting ledger.
Process all external events through an idempotent outbox/inbox pipeline. Raw webhooks verify signatures, persist once into PostgreSQL, and hand off to BullMQ workers that serialize mutations per customer_id, preventing concurrent webhooks from racing against each other.
Aggregate metered usage off the critical path. Usage events accumulate in fast time-bucketed structures before BullMQ batch jobs rate them against tiered pricing schedules and push consolidated summaries to the Stripe API.
Project entitlements into Redis for instant runtime checks. Host SaaS microservices read seat limits, feature flags, and grace-period banners from Redis without coupling request latency to Stripe API availability.
Core Capabilities
- Versioned plan & add-on catalog: Supports flat tiers, per-seat licensing, tiered volume/graduated usage meters, and grandfathered cohort pricing.
- Previewed mid-cycle proration: Interactive React billing portal displaying exact prorated credits, taxes, and immediate net charges prior to plan or seat changes.
- Metered usage ingestion & rating: Idempotent usage event API aggregating hourly and daily consumption buckets against included plan allowances and overage blocks.
- Decline-aware dunning orchestration: Customizable grace periods, smart retry cadences based on Stripe failure codes, tokenized card-update emails, and progressive in-app lockouts.
- Self-serve B2B billing portal: Allows workspace owners to download PDF invoices, update VAT/tax IDs, manage payment methods, and review live quota burn.
- Finance operations console: Enables authorized staff to issue partial credits, extend trials, pause subscriptions, and inspect raw webhook timelines.
Technical Architecture
Node.js & TypeScript orchestration layer. Structured around clean service boundaries—Catalog, Subscription Lifecycle, Usage Aggregator, Webhook Processor, and Dunning Engine—the Node.js backend enforces strict TypeScript schemas on every Stripe API response and internal REST call.
PostgreSQL durable ledger & inbox. PostgreSQL stores plans, price_versions, subscriptions, webhook_events (keyed by unique stripe_event_id), usage_rollups, and ledger_entries. Per-customer advisory locks or BullMQ group concurrency ensure two mutations for the same account never interleave out of order.
Redis & BullMQ job pipelines. BullMQ manages scheduled trial expirations, dunning retry timers, hourly usage rollup jobs, and daily Stripe payout reconciliation. A separate Redis keyspace caches compiled tenant entitlement payloads (plan, seat_limit, quota_remaining, dunning_state) updated atomically after each billing state change.
Stripe API & React portal. The billing service integrates directly with Stripe Subscriptions, PaymentIntents, Customer Portal sessions, and Stripe Tax, while a React and TypeScript interface serves both self-serve customer billing pages and internal RevOps diagnostics.
Flow: Product usage / React portal → Node.js billing API → PostgreSQL state & webhook inbox → BullMQ workers & Redis entitlement cache → Stripe API & dunning notifications
Technology Stack
| Category | Technology |
|---|---|
| Backend runtime | Node.js 22 LTS with TypeScript powering billing APIs, webhook consumers, and entitlement services |
| Payment & tax gateway | Stripe API (Subscriptions, PaymentIntents, SetupIntents, Invoices, and Tax calculation webhooks) |
| Primary database | PostgreSQL storing plan catalogs, versioned subscriptions, usage events, webhook logs, and billing ledgers |
| Job orchestration | BullMQ backed by Redis executing usage aggregation, smart dunning retries, and invoice PDF dispatch |
| Entitlement cache | Redis storing sub-millisecond workspace feature flags and quota balances synced on every state transition |
| Self-serve & ops UI | React and TypeScript portal for plan switches, seat management, payment method updates, and ops recovery |
| API contracts | OpenAPI-typed REST endpoints with HMAC-signed customer portal sessions and idempotency headers |
| Audit & reconciliation | Automated daily Stripe balance-transaction reconciliation comparing local PostgreSQL ledger vs Stripe payouts |
| Observability | Structured correlation IDs linking incoming Stripe event IDs, BullMQ jobs, and entitlement updates |
Engineering Trade-offs & Solutions
| Challenge | Solution |
|---|---|
| Out-of-order Stripe webhooks could downgrade a workspace right after a successful retry | Persisted every webhook by unique stripe_event_id in PostgreSQL and processed per-customer queues sequentially, verifying latest invoice status before changing access. |
| High-throughput API metering risked creating table bloat in PostgreSQL | Buffered raw metering ticks into hourly Redis buckets with idempotency keys, flushing aggregated period totals into PostgreSQL and Stripe asynchronously. |
| Double-clicks or network timeouts during plan upgrades risked duplicate Stripe calls | Required client-supplied idempotency keys on all mutation endpoints and forwarded deterministic keys directly to Stripe API requests. |
| Hard card declines wasted automated retry cycles and delayed customer outreach | Branched dunning workflows by Stripe decline reason—routing soft declines through timed retries while immediately escalating expired or blocked cards to billing owners. |
| Changing pricing tiers risked accidentally billing legacy customers under new rates | Pinned every active subscription to an immutable price_version_id in PostgreSQL so catalog edits affect only new signups or explicit migrations. |
| Silent drift between Stripe payouts and internal SaaS revenue reports undermined finance closes | Scheduled a nightly BullMQ reconciliation job comparing Stripe Balance Transactions against local PostgreSQL ledger entries and flagging discrepancies. |
Security & Reliability
Cryptographic webhook & portal verification. Every Stripe webhook endpoint validates Stripe-Signature headers against raw request buffers prior to JSON parsing, rejecting spoofed payloads. Customer portal deep-links use short-lived signed tokens scoped strictly to a single workspace billing entity.
Zero raw card exposure. Payment collection uses tokenized Stripe Elements and SetupIntents in the React frontend so sensitive PAN and CVV data never touches Node.js servers or application logs.
Controlled failure isolation. If Stripe experiences transient latency, core product authorization continues uninterrupted against cached Redis entitlements while outbound billing mutations queue safely in BullMQ for automatic retry.
Performance & Scale
Sub-millisecond entitlement reads. Decoupling runtime feature checks from billing writes ensures tens of thousands of authenticated product requests resolve workspace limits from Redis without contending with invoice generation or database transactions.
Partitioned usage tables. Monthly partitioning on PostgreSQL usage history and webhook archive tables keeps active indexes compact and guarantees fast billing-history queries across multi-year tenant lifespans.
Operational Outcomes
- Accurate, drift-free entitlements: Product access reflects upgrades, seat changes, and recovered payments immediately without manual support intervention.
- Reduced involuntary churn: Decline-aware retry schedules and frictionless one-click card updates recover failed renewals before subscriptions cancel.
- Clean month-end finance closes: Versioned price catalogs, prorated ledger records, and automated Stripe reconciliation eliminate spreadsheet guesswork.
- Faster commercial experimentation: Revenue teams launch new usage tiers, trial lengths, and enterprise overrides cleanly through configuration rather than engineering deploys.