HomeCase studiesIdempotent SaaS Subscription Billing, Metered Usage, and...

Case study · Seattle, United States

Idempotent SaaS Subscription Billing, Metered Usage, and Automated Dunning Platform

SaaS Billing & Revenue Retention

Growing B2B SaaS products outgrow basic checkout links as soon as customers demand mid-cycle seat upgrades, metered API usage tiers, and automated recovery for failed card renewals. We engineered a dedicated subscription management platform built with Node.js, TypeScript, Stripe API, PostgreSQL, and Redis/BullMQ to govern plan lifecycles, entitlement synchronization, and revenue-preserving dunning workflows. Idempotent webhook ingestion and an internal double-entry billing ledger keep customer access accurate even during payment retries and Stripe API rate spikes.

Industry
SaaS Billing & Revenue Retention
Solution
A B2B subscription billing, metered usage rating, entitlement, and dunning orchestration platform built with Node.js, Stripe API, PostgreSQL, Redis, and React.
Platforms
Web & API
Stack
Node.js · TypeScript · Stripe API · PostgreSQL · Redis · BullMQ
Location
Seattle, United States · delivered remotely
Role
Engineering, with the team behind for mobile and QA

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.

01 — Questions

asked about this kind of project

Why maintain a local PostgreSQL subscription ledger alongside the Stripe API instead of querying Stripe directly?

Querying Stripe on every authenticated product request adds latency and risks hitting rate limits. Maintaining a synchronized PostgreSQL state machine paired with Redis entitlement caches gives the host SaaS application fast, deterministic feature gating while preserving full historical auditability for finance exports.

How do you prevent out-of-order or duplicate Stripe webhooks from corrupting subscription status?

Every incoming webhook verifies the Stripe signature, persists its raw `event.id` into a unique-constrained PostgreSQL inbox table, and enqueues processing onto BullMQ. Workers check event timestamps and fetch canonical subscription state when necessary so duplicate or delayed events never regress an active plan to past-due.

How does metered usage rating handle high-volume API calls without overloading PostgreSQL?

Product services stream raw usage increments into Redis counters or partitioned ingestion buffers keyed by `(tenant_id, metric, hour_bucket)`. A scheduled BullMQ aggregator rolls hourly totals into PostgreSQL and submits idempotent Stripe usage records before invoice finalization.

How are mid-cycle upgrades, downgrades, and seat proration handled without confusing customers?

Before confirming any plan change in the React billing portal, the Node.js service requests a Stripe invoice preview showing exact prorated line items and immediate charge amounts. Upgrades apply entitlements immediately; downgrades schedule cleanly for the end of the current billing period by default.

What makes the dunning workflow more effective than default fixed-interval card retries?

When an invoice payment fails, the platform classifies the Stripe decline code (soft insufficient funds vs expired card vs hard fraud block). Soft declines enter a configurable smart-retry schedule aligned to business banking days alongside progressive in-app banners and tokenized one-click card-update links, while hard declines skip pointless retries and alert billing owners immediately.

How are grandfathered pricing plans supported when new customers move to updated tiers?

Plans and prices carry immutable version identifiers in PostgreSQL mapped to Stripe Price IDs. Existing tenants remain pinned to their contracted price version until an operator or customer explicitly triggers a migration, eliminating accidental price shocks.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.