The High-Performance & Infrastructure Tiers

Multi-Tenant B2B SaaS Architecture

One codebase. Infinite tenants. Zero data leaks.

The complete technical foundation for selling software to businesses — true tenant isolation, RBAC, subdomain routing, and usage metering from day one.

Row-level
RLS isolation
Unlimited
Tenants/instance
Built-in
Subdomain routing
5.0 · Trusted by 50+ developers

Core stack

PostgreSQL RLSNext.jsDockerRedis

What's included

Workspace isolation
subdomain routing
granular RBAC
API usage metering

The Architecture That Separates $10/Month Consumer Apps From $500/Month Enterprise Products

Consumer SaaS and B2B SaaS look similar from the outside — web apps, subscriptions, features. Under the hood, they're fundamentally different products. A consumer app serves individual users who mostly don't care that other users exist. A B2B app sells to a company and must serve dozens of people within that company while ensuring they can never accidentally see data from a competing company that's also using your platform.

Getting this wrong, even once, is catastrophic. A data isolation bug in a B2B SaaS doesn't just upset one user — it's a breach that affects every customer whose data lives on your platform.

The Multi-Tenant B2B SaaS Architecture implements the isolation and access control patterns that enterprise buyers expect and security auditors require — not bolted on after the fact, but built into the database schema, the API layer, and the routing system from the start.

PostgreSQL Row-Level Security: Your Last Line of Defense

Row-Level Security (RLS) is PostgreSQL's built-in mechanism for enforcing access policies at the database level. When correctly configured, it means that even if your application code has a bug that forgets to add a tenant filter to a query, the database itself rejects the result.

This is defense-in-depth. Your API layer should still filter by tenant. Your ORM queries should still include tenant conditions. But RLS means that a forgotten WHERE clause is a bug that returns empty results rather than a security incident that exposes another company's data.

The implementation in this codebase:

  • RLS policies are defined on every data table, tied to a current_tenant_id session variable
  • The session variable is set from the validated JWT at the start of every database transaction
  • All database connections go through the application user (not a superuser — superusers bypass RLS)
  • Background jobs, analytics queries, and admin operations use a separate database connection with explicit tenant context
  • Connection pooling is handled with set_config('app.current_tenant_id', ..., true) — the is_local: true flag ensures the tenant context is scoped to the transaction and doesn't leak to the next query from the connection pool

This is not a naive implementation. The is_local flag issue specifically is one of the most common sources of tenant data leakage in RLS deployments — it's explicitly handled here.

Subdomain Routing: acme.yourapp.com on Day One

Enterprise buyers expect a white-label experience. They want acme.yourapp.com, not yourapp.com/dashboard?org=acme. Subdomain-based routing signals that this is serious software, not a side project.

The Next.js middleware (proxy layer) handles subdomain resolution on every request. It reads the subdomain, looks up the corresponding tenant in a Redis cache (miss falls back to the database), and injects the tenant context into the request. From that point, every subsequent database query is automatically scoped to that tenant via the RLS session variable.

Wildcard SSL certificates are provisioned automatically via AWS Certificate Manager or Let's Encrypt, depending on your deployment target. New customer onboarding automatically creates the subdomain entry — no manual DNS work required.

Role-Based Access Control That Actually Covers Real Enterprise Requirements

Enterprise accounts don't have two roles (Admin and User). They have Billing Administrators who can see invoices but not user data. They have Department Managers who can see their team's activity but not other departments'. They have Read-Only Auditors who need to export reports without being able to modify anything. They have API Service Accounts with narrow, scoped permissions for integrations.

The RBAC system is built on a permissions-based model rather than a roles-based model. Permissions are atomic capabilities (e.g., users.view, users.create, billing.manage, reports.export). Roles are named collections of permissions. This means:

  • Tenant admins can create custom roles that combine exactly the permissions their organization needs
  • Adding a new feature only requires adding a new permission string
  • The permission check is a single function call anywhere in the codebase

The UI reflects permissions in real-time — menu items, action buttons, and data columns that the current user doesn't have access to are hidden entirely, not just disabled.

API Usage Metering for Usage-Based Pricing

The fastest-growing pricing models in B2B SaaS are usage-based — you charge for what customers actually consume rather than a flat seat fee. This requires infrastructure that can accurately count API calls, data processed, seats active, or any other metric you want to bill against.

The metering system logs usage events to a high-throughput write buffer (Redis) and periodically flushes them to PostgreSQL in batches. This prevents the metering layer from adding latency to API responses. The aggregated usage data feeds into Stripe's metered billing API to generate accurate invoices automatically.

Tenant admins can see their current period usage in a dedicated usage dashboard with historical comparisons.

One-time
$1,800USD

Lifetime access · Full source code

Secure checkout via Stripe · No subscription

Instant download after payment
Full, unminified source code
Commercial use license included
Dispute & chargeback protected

Questions before purchasing? Talk to us →

Ready to stop building from scratch?

Get the complete, production-ready codebase today. One payment, lifetime access, instant download.

Multi-Tenant B2B SaaS Architecture | $1,800 One-Time · LaunchStruc | LaunchStruc