Triamorph Systems

Full-Stack · 13 min read · Sep 08, 2024

B2B SaaS Billing Architecture: How to Implement Multi-Tier Subscriptions, Usage Metering, and Stripe Webhook Idempotency

Deep-dive architectural guide on building enterprise B2B SaaS billing engines: handling seat-based and metered billing, Stripe webhook signature validation, idempotency tables, and PostgreSQL financial schemas.

By Hammad Haider

Core Engineering Takeaways

  • Store customer billing state as an immutable state machine in PostgreSQL, treating Stripe as a payment processor rather than the single source of truth for access entitlement.
  • Enforce atomic idempotency using a dedicated `stripe_webhook_events` PostgreSQL table with advisory row locks to prevent duplicate credit provisioning during network retries.
  • Decouple real-time API request ingestion from Stripe Metering API calls using TimescaleDB hyper-tables and asynchronous batch workers.

Building a robust billing engine for B2B SaaS is notoriously prone to edge cases: double billing from duplicate webhook deliveries, race conditions during mid-cycle plan upgrades, prorated seat expansions, and dropped usage metrics. As software enterprises scale from seat-based pricing to hybrid consumption-based billing models, relying solely on basic Stripe client-side SDKs is insufficient. This architectural guide demonstrates how to design an enterprise-grade billing state machine, persist an immutable audit ledger in PostgreSQL, and enforce guaranteed exactly-once webhook processing.

1. Relational Billing Data Model & Subscription State Machine

Separating entitlement authorization from payment gateway synchronization

Many SaaS startups make the critical architectural mistake of querying Stripe directly on every protected API call to check if an organization has an active plan. This introduces external network latency (300ms+ per request) and causes complete application outages whenever Stripe encounters degraded performance.

An enterprise billing architecture stores customer subscription states, feature quotas, and seat limits in local PostgreSQL tables with Row-Level Security (RLS). Stripe customer IDs and subscription IDs are stored as foreign keys. When a user authenticates, their tenant permissions are resolved locally in under 1ms.

Entitlement Check Latency
< 1.2ms
Local PostgreSQL indexed lookup
Stripe Direct API Latency
280-650ms
External round-trip network hop
Uptime Decoupling
99.999%
Zero SaaS downtime during Stripe outages

Entitlements must always be evaluated against local database records. Never block hot customer API paths on external HTTP calls to third-party billing providers.

— Triamorph SaaS Architecture Practice
db/schema/saas_billing_entitlements.sql (sql)
-- PostgreSQL Enterprise Subscription & Entitlements Schema
CREATE TYPE subscription_status_enum AS ENUM (
    'trialing', 'active', 'past_due', 'canceled', 'unpaid', 'paused'
);

CREATE TABLE tenant_subscriptions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
    stripe_customer_id VARCHAR(255) NOT NULL UNIQUE,
    stripe_subscription_id VARCHAR(255) UNIQUE,
    plan_tier VARCHAR(64) NOT NULL, -- 'starter', 'growth', 'enterprise'
    status subscription_status_enum NOT NULL DEFAULT 'trialing',
    current_period_start TIMESTAMPTZ NOT NULL,
    current_period_end TIMESTAMPTZ NOT NULL,
    cancel_at_period_end BOOLEAN NOT NULL DEFAULT FALSE,
    allocated_seats INT NOT NULL DEFAULT 5,
    monthly_compute_credit_limit BIGINT NOT NULL DEFAULT 1000000,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_tenant_subscriptions_lookup ON tenant_subscriptions(tenant_id, status);

2. Zero-Loss Stripe Webhook Processing with Idempotency Keys

Eliminating duplicate billing events using PostgreSQL transaction-level locks

Stripe webhooks use an "at-least-once" delivery guarantee. If your server takes more than a few seconds to respond with a 200 OK, or if a temporary network blip occurs, Stripe will retry sending the exact same webhook payload up to dozens of times over 72 hours.

Without strict idempotency guards, handling an `invoice.payment_succeeded` or `checkout.session.completed` event multiple times will provision duplicate seats, send repetitive email receipts, or grant double balance credits. We implement atomic lock tables with cryptographic signature verification.

services/billing/stripeWebhookHandler.ts (typescript)
import Stripe from 'stripe';
import { pool } from '../database';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: '2024-06-20' });

export async function processStripeWebhook(rawBody: Buffer, signature: string): Promise<void> {
  const event = stripe.webhooks.constructEvent(
    rawBody,
    signature,
    process.env.STRIPE_WEBHOOK_SIGNING_SECRET!
  );

  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // 1. Check & Insert Idempotency Record (Atomic Dedup)
    const insertResult = await client.query(
      `INSERT INTO stripe_webhook_events (event_id, event_type, status, created_at)
       VALUES ($1, $2, 'processing', NOW())
       ON CONFLICT (event_id) DO NOTHING
       RETURNING id;`,
      [event.id, event.type]
    );

    if (insertResult.rowCount === 0) {
      // Event has already been processed or is currently in flight
      await client.query('ROLLBACK');
      return;
    }

    // 2. Dispatch state updates based on verified event type
    switch (event.type) {
      case 'invoice.payment_succeeded': {
        const invoice = event.data.object as Stripe.Invoice;
        await handleInvoicePaymentSucceeded(client, invoice);
        break;
      }
      case 'customer.subscription.updated': {
        const sub = event.data.object as Stripe.Subscription;
        await handleSubscriptionUpdated(client, sub);
        break;
      }
      case 'customer.subscription.deleted': {
        const sub = event.data.object as Stripe.Subscription;
        await handleSubscriptionCanceled(client, sub);
        break;
      }
    }

    await client.query(
      'UPDATE stripe_webhook_events SET status = $1, processed_at = NOW() WHERE event_id = $2',
      ['completed', event.id]
    );
    await client.query('COMMIT');
  } catch (error) {
    await client.query('ROLLBACK');
    throw error;
  } finally {
    client.release();
  }
}

3. Real-Time Consumption Metering & Aggregation Engine

Ingesting millions of API events without overwhelming billing APIs

In usage-based software (such as AI token consumption, compute hours, or active data storage), piping every single event synchronously to Stripe’s Metering API creates rate-limiting bottlenecks and high egress costs.

The optimal architecture ingests usage events into high-throughput Redis stream buffers, aggregates them periodically into TimescaleDB or clickstream tables, and dispatches summarized hourly or daily usage records to Stripe using the Stripe Metered Billing API.

4. Handling Mid-Cycle Upgrades, Prorations & Grace Periods

Automated invoice calculation and payment retry grace period handling

When an enterprise client adds 20 team members midway through their annual subscription, Stripe automatically calculates line-item prorations. Your backend must reliably and smoothly update the `allocated_seats` constraint and trigger immediate seat provisioning without disrupting active user sessions.

Similarly, when payment attempts fail, transitioning subscriptions to `past_due` and initiating a 7-day dunning sequence with automated banner warnings preserves revenue while avoiding abrupt tenant churn.

Tags: b2b saas billing architecturestripe webhook idempotency postgresqlmetered usage billing architecturesaas subscription tier database schemahow to architect saas billing stripe

Related Engineering Practice & Case Studies

Engineering Practice Blueprint

Custom Web Development & SaaS Platforms →

Next.js & React web platforms engineered for sub-1.5s load times and 98+ Lighthouse scores.

View Practice Blueprint & Capabilities →
Production Client System

Portfolix Developer Portfolio Builder →

Modern developer portfolio builder platform delivering sub-5 minute deployments with 98+ Lighthouse scores and 100% clean code export.

Read Deployed Case Study (Sub-5 minute edge deployment with 100% clean code export) →

Related Engineering Articles & Guides

Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →