Back to Blog
·15 min
BI

BreafIO Team

Product & Engineering

B2B Multi-Tenant Boilerplate: Building SaaS for Teams and Organizations

Introduction to the B2B Multi-Tenant Boilerplate

Building a B2B SaaS product means designing for organizations, not individual users. The architecture decisions you make in the first week determine whether your application can scale from ten teams to ten thousand without a rewrite. The B2B Multi-Tenant Boilerplate provides a production-ready foundation for building SaaS products where the customer is a company, not a person. It includes organization-based multi-tenancy from the schema up, role-based access control with Owner, Admin, and Member roles, email invitation workflows with token-based acceptance and automatic seat billing, a super-admin panel for cross-tenant management, and Stripe billing that scales automatically as team members are added or removed. In this guide, we will explore the architecture, implementation, and operational considerations for building multi-tenant applications on the B2B Multi-Tenant Boilerplate. We will cover tenant isolation strategies, the role-based access control system, the invitation and seat billing workflow, the super-admin panel, and deployment considerations for multi-tenant applications.

Multi-Tenancy Architecture

Multi-tenancy is the architectural pattern where a single application instance serves multiple customer organizations, with data isolation between organizations. The B2B Multi-Tenant Boilerplate uses the shared-database, shared-schema approach with row-level tenant isolation, which provides the best balance of operational simplicity and data isolation. Each database table includes an organizationId foreign key, and every query is scoped through the Membership model. This approach ensures that a missed WHERE clause cannot accidentally expose data from another organization. The data model centers on the Organization, Membership, and User models. An Organization represents a customer company with its own billing, settings, and data. A Membership links a User to an Organization with a specific role, and all data access is mediated through this relationship. The architecture also supports personal accounts for single-user scenarios, where a user has a personal organization automatically created at signup. The invitation system creates pending memberships with unique tokens that expire after a configurable period, and seat billing automatically updates the Stripe subscription quantity when an invitation is accepted or a member is removed. The super-admin panel provides a gated view across all organizations for support and billing troubleshooting, accessible only to users with the SuperAdmin role.

Role-Based Access Control

The role-based access control system in the B2B Multi-Tenant Boilerplate is enforced server-side on every org-scoped route, not just in the UI. Three roles are defined: Owner, Admin, and Member. The Owner role has full control over the organization, including billing management, member removal, organization settings, and transferring ownership. There is exactly one Owner per organization. The Admin role can manage members (invite, remove), update organization settings, and access most management features, but cannot delete the organization or transfer ownership. The Member role has access to the shared organization dashboard and features but cannot manage billing, members, or organization settings. The role enforcement is implemented as middleware that extracts the organization ID from the URL or request context, identifies the current user, looks up their membership and role, and returns a 403 if the required role level is not met. This server-side enforcement is critical: client-side role hiding is a UX convenience, not a security measure. The system also supports feature-level permissions beyond the three basic roles, using a permission matrix that can be extended for custom application needs. The role system integrates with the Prisma schema through the Membership model's role enum, ensuring that role assignments are always consistent with the database schema.

Email Invitation and Seat Billing Workflow

The invitation and seat billing workflow is one of the most complex and valuable features of the B2B Multi-Tenant Boilerplate. The flow begins when an Admin or Owner enters an email address in the team management interface. The system creates a PendingMembership record with a unique token, stores the inviter ID and organization ID for audit purposes, and sends an email invitation with a link containing the token. When the recipient clicks the link, they are prompted to sign in or create an account. Upon authentication, the system verifies the token, checks that it has not expired, confirms the email matches the invited email, and activates the membership. At this point, the seat billing update is triggered: a Stripe API call updates the subscription quantity to reflect the new member count. If the subscription has a per-seat price, the next invoice will automatically include the additional seat. When a member is removed, the reverse happens — the subscription quantity decreases. The Stripe webhook handler processes subscription updates and syncs the status back to the local database. The dashboard displays the current member count, pending invitations, and their expiry status. The invitation system includes rate limiting to prevent abuse, email templates that can be customized, and a resend option for expired invitations.

Super-Admin Panel

The super-admin panel provides a separate, gated interface for internal support and billing teams to manage all organizations in the application. This is the feature that most single-tenant boilerplates skip entirely, but it is essential for any B2B SaaS that offers customer support. The super-admin panel includes an organization directory with search and filtering, member management across organizations, subscription and billing status overview, impersonation capabilities for troubleshooting, audit log of administrative actions, and support ticket integration. Access to the super-admin panel is controlled by a superAdmin role on the User model, which is separate from organization-level roles. The panel is implemented as a parallel route group that does not interfere with the main application routing. All super-admin actions are logged in an audit trail with actor, timestamp, action type, and details for compliance purposes. The impersonation feature allows support staff to view the application as a specific user, which is invaluable for diagnosing issues without requiring customer credentials. Every impersonation session is logged and time-limited, with automatic termination after a configurable period.

Database Schema for Multi-Tenancy

The Prisma schema for the B2B Multi-Tenant Boilerplate is designed around the organization as the root entity. The Organization model includes fields for name, slug (used in URLs), billing email, subscription status, trial end date, and custom settings stored as JSON. The Membership model links users to organizations with a role enum, joined date, and invitation details for pending memberships. The User model is organization-agnostic at the database level, allowing a user to belong to multiple organizations. All feature-specific models include an organizationId foreign key with a cascading delete relationship. The schema includes proper indexes on organizationId for all feature tables, email for user lookup, token for invitation resolution, and the composite unique constraint on userId and organizationId to enforce one membership per user per organization. Prisma migrations are used for schema versioning, and the seed script creates test organizations with sample users at each role level.

Getting Started with the B2B Multi-Tenant Boilerplate

The B2B Multi-Tenant Boilerplate Starter Kit provides everything you need to start building your multi-tenant SaaS application. Getting started involves cloning the repository, installing dependencies, configuring environment variables for authentication and Stripe, running database migrations, and seeding test data. The starter kit includes comprehensive documentation covering the data model, API routes, component library, and deployment configuration. The setup guide walks through each step with code examples and troubleshooting tips. You can have a working multi-tenant application deployed to production within hours, with organization creation, member invitations, role-based access, and automatic seat billing operational from day one.

Tenant Isolation Strategies

Choosing the right tenant isolation strategy is critical for multi-tenant applications. The B2B Multi-Tenant Boilerplate uses row-level isolation within a shared database, which provides the best operational efficiency for most B2B SaaS products. However, the architecture supports upgrading to database-per-tenant or schema-per-tenant isolation as requirements evolve. Row-level isolation uses an organizationId column on every tenant-scoped table, with all queries automatically filtered through middleware. This approach minimizes operational overhead because there is a single database to manage, backup, and monitor. Connection pooling is efficient because all tenants share the same connection pool. Schema migrations apply once for all tenants simultaneously. The trade-off is that a database outage affects all tenants, and query performance can be impacted by a noisy neighbor tenant with high traffic. The boilerplate includes mitigation strategies for these concerns: query performance monitoring per tenant, connection pool sizing based on aggregate load, and read replica configuration for reporting queries. The middleware layer enforces tenant isolation at the Prisma query level, ensuring that a missing WHERE clause in any query cannot accidentally expose cross-tenant data.

Scaling Multi-Tenant Applications

Scaling a multi-tenant application requires attention to database performance, connection management, and tenant fairness. The B2B Multi-Tenant Boilerplate provides infrastructure for scaling from dozens to thousands of tenants. Database scaling strategies include read replicas for reporting and analytics queries that do not need real-time data, connection pooling with PgBouncer for efficient connection management under high concurrency, query performance monitoring per tenant to identify problematic queries, and query timeout configuration to prevent runaway queries from impacting other tenants. Caching strategies include application-level caching with Redis for frequently accessed data like organization settings and user roles, edge caching with Vercel's Edge Config for global settings, and database query result caching for expensive but infrequently changing queries. Tenant fairness is enforced through per-tenant rate limiting, configurable query timeouts per tenant tier, and resource quotas for API usage and storage. The architecture supports horizontal scaling of the application layer through stateless serverless functions, with session state stored in the database rather than in-memory. Background job processing uses queues for long-running operations like report generation and data export, preventing these tasks from impacting interactive request performance.

Migration from Single-Tenant to Multi-Tenant

Migrating an existing single-tenant application to multi-tenancy is a common challenge. The B2B Multi-Tenant Boilerplate provides a migration path that minimizes disruption. The recommended approach is to run the single-tenant and multi-tenant versions in parallel during a transition period. The migration process involves adding an organizationId column to existing tables with a default value representing the legacy single tenant, backfilling existing data with the legacy organization ID, creating Membership records for existing users, updating all queries to include organization scoping, testing thoroughly in a staging environment, and switching traffic to the multi-tenant version. The boilerplate includes a migration guide with SQL scripts for common migration scenarios, a validation suite that verifies tenant isolation after migration, and rollback procedures in case issues are discovered. The key risk in migration is accidentally exposing data during the transition. The boilerplate's middleware-based isolation ensures that even if some queries are missed during the initial migration, the middleware layer provides a safety net. The super-admin panel is particularly valuable during migration because it allows support staff to verify data integrity across all tenants.

Authentication in Multi-Tenant Applications

Authentication in a multi-tenant application requires careful design to support both organization-scoped and personal authentication flows. The B2B Multi-Tenant Boilerplate implements a dual authentication system where users authenticate at the application level and then select or are assigned to an organization. The signup flow creates a user account and optionally creates a personal organization for single-user scenarios. Users can belong to multiple organizations and switch between them without re-authenticating. The login flow is organization-agnostic at the authentication layer, with organization context established after authentication. The session includes both the user identity and the active organization ID, with the organization context persisted in a cookie or URL parameter. Organization switching is a fast client-side operation that updates the session context without a full page reload. The middleware layer reads the organization context from the session and scopes all database queries accordingly. The authentication system integrates with Auth.js with support for multiple providers. Multi-factor authentication is supported through TOTP and WebAuthn for organizations that require additional security. Session management allows organizations to enforce session policies like idle timeout and concurrent session limits for their members.

Billing and Subscription Management

The billing system in the B2B Multi-Tenant Boilerplate is designed specifically for the per-seat pricing model common in B2B SaaS. The Stripe integration supports seat-based subscriptions where the subscription quantity represents the number of active members in the organization. When a new member accepts an invitation, a Stripe API call updates the subscription quantity, and the next invoice reflects the additional seat. When a member is removed, the quantity decreases automatically. The billing system supports multiple pricing models: flat per-seat pricing where all members cost the same, tiered per-seat pricing where the per-seat cost decreases as the organization grows, and mixed pricing with a base platform fee plus per-seat charges. The checkout flow creates a subscription with the initial member count and sets up the billing webhook endpoint. The customer portal allows organization owners to view and manage their subscription, update payment methods, and download invoices. The billing dashboard in the application shows the current plan, member count, next billing date, and invoice history. Usage-based add-ons can be billed through Stripe's metered usage API on top of the base per-seat subscription. The billing system handles proration for mid-cycle member additions or removals, trial periods for new organizations, and dunning for failed payments.

API and Webhook Architecture

The B2B Multi-Tenant Boilerplate includes a comprehensive API layer designed for both internal use and external integration. The API is organized around resources that are scoped to organizations. Every API endpoint validates organization membership and role permissions before processing requests. The API supports RESTful patterns with consistent URL structures, pagination for list endpoints with cursor-based and offset-based pagination options, sorting and filtering parameters that mirror the data table component, and field selection to minimize response payload size. The API documentation is generated from OpenAPI annotations and is available at the /api/docs route. Webhooks allow external services to receive real-time notifications about events like member invited, member joined, member removed, organization settings updated, and subscription changed. The webhook system supports multiple endpoints per organization with secret-based signature verification. Webhook delivery is retried with exponential backoff for up to three days, with a webhook dashboard showing delivery status and logs. Rate limiting is applied per organization to prevent abuse, with configurable limits based on subscription tier. API keys can be generated for programmatic access with scoped permissions, and key rotation is supported through the admin panel.

Customization and Extension Points

The B2B Multi-Tenant Boilerplate is designed to be extended for specific business requirements. Key extension points include custom roles beyond Owner, Admin, and Member, which can be defined through a permissions matrix in the database. Custom invitation flows can implement approval workflows where an Admin must approve new member invitations before they are sent. The organization settings can be extended with custom fields stored as JSON in the Organization model, with custom validation rules and UI components for each field type. The billing system can be extended with usage-based add-ons on top of the per-seat pricing, custom trial periods per organization tier, and promotional discounts applied to specific organizations. The super-admin panel can be extended with custom dashboards per organization type, custom reports for specific verticals, and integration with external systems through webhooks or API. The authentication system can be extended with SAML or OpenID Connect for enterprise SSO, custom authentication flows for specific organization requirements, and organization-specific authentication policies. The UI can be customized per organization with custom branding, custom navigation items, and custom dashboard widgets. The boilerplate includes documentation for each extension point with code examples and best practices for maintaining backward compatibility when extending the core functionality.

Multi-Tenant Data Migration and Backup

Data management at scale requires robust migration and backup strategies for multi-tenant applications. The B2B Multi-Tenant Boilerplate provides infrastructure for schema migrations that apply to all tenants simultaneously through Prisma migrations, with deployment procedures that minimize downtime. Data migrations for specific tenants can be run through admin panel tools that execute tenant-scoped data transformation scripts. Backup strategies include automated daily backups of the shared database with point-in-time recovery capability, and tenant-level exports for customer data portability requests. The backup system supports selective restoration where a single tenant's data can be restored without affecting other tenants. The migration toolkit includes dry-run mode for testing migrations before execution, rollback procedures for reverting failed migrations, and validation scripts that verify data integrity before and after migration. Performance monitoring during migrations tracks query performance per tenant and identifies any migration that degrades performance. The super-admin panel includes migration status dashboards showing pending migrations, in-progress migrations with progress indicators, completed migrations with validation results, and failed migrations with error details and retry options.

Common Use Cases and Examples

The B2B Multi-Tenant Boilerplate is designed for a wide range of B2B SaaS applications. Common use cases include project management platforms where each organization has its own projects, tasks, and team members with role-based access controls. Customer relationship management systems where each organization manages their own contacts, deals, and pipelines with sales team collaboration. Human resources platforms where companies manage employee onboarding, time-off requests, and performance reviews with department-level organization. Educational technology platforms where schools manage classes, students, and assignments with teacher and administrator roles. Healthcare practice management where clinics manage patients, appointments, and billing with provider and staff roles. Each of these use cases benefits from the multi-tenant architecture, role-based access control, invitation workflow, and seat-based billing that the boilerplate provides. The extension points allow customizing the data model and business logic for each vertical while maintaining the shared infrastructure for authentication, billing, and organization management. The boilerplate has been used as the foundation for applications serving from a handful of organizations to thousands of tenants, demonstrating its scalability across different deployment sizes.

Performance and Scalability Considerations

Performance is critical for multi-tenant applications where a single slow tenant should not impact others. The B2B Multi-Tenant Boilerplate includes query analysis tools that identify expensive queries per tenant, connection pooling configuration for PostgreSQL that manages concurrent connections efficiently, and query timeout settings that prevent runaway queries from consuming database resources. Database indexing strategies include composite indexes on (organizationId, createdAt) for time-series queries, partial indexes for filtered queries, and covering indexes for frequently accessed query patterns. Caching strategies include Redis-based caching for frequently accessed organization settings and user permissions, with cache invalidation triggered by data changes. The application layer is stateless and can be horizontally scaled across multiple serverless function instances. Background job processing uses queues for operations like sending invitation emails, processing webhooks, and generating reports. The monitoring infrastructure tracks key metrics per organization including request latency, database query performance, error rates, and API usage. Alerting is configured for metrics that exceed thresholds, with notifications sent to the operations team. The super-admin panel includes performance dashboards that show the top tenants by resource consumption, enabling proactive capacity planning and tenant-level troubleshooting.

Ready to Build?

Get started with our production-ready starter kits and ship your project faster.

Browse Starter Kits