SaaS Product Development Agency Guide: How to Architect, Build, and Scale B2B SaaS in 2026
Comprehensive guide from an elite SaaS product development agency: how to evaluate custom SaaS development services, architect multi-tenant ...
Read Article →Full-Stack · 13 min read · Sep 08, 2024
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.
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.
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.
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
-- 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);
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.
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();
}
}
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.
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.
Next.js & React web platforms engineered for sub-1.5s load times and 98+ Lighthouse scores.
View Practice Blueprint & Capabilities →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) →Comprehensive guide from an elite SaaS product development agency: how to evaluate custom SaaS development services, architect multi-tenant ...
Read Article →Architectural comparison: PostgreSQL Row-Level Security (RLS) vs Schema-per-Tenant vs Database-per-Tenant. Benchmark query performance, conn...
Read Article →Production PostgreSQL schema design for double-entry bookkeeping ledgers: debit/credit constraints, immutable append-only triggers, snapshot...
Read Article →What is the best tech stack for SaaS startups in 2027? Complete guide covering Next.js and React, Node.js vs Python FastAPI, PostgreSQL with...
Read Article →Explore all technical guides in our Articles & Guides Index → or discuss your architecture with our engineers via Technical Discovery →