Multi-Tenant SaaS Architecture: Databases, Organisations, Permissions and SSO
By Obaid Tariq, Founder & Lead Engineer · Published
Disclosure: AI Dev Planner builds B2B SaaS products, including their tenancy and permission models, so we have an interest in this question. We say where another option is better. See our disclosure policy.
The short answer
For most new B2B products, the best multi-tenant SaaS architecture is a shared database and schema where every tenant-owned row carries a tenant_id, enforced by both application code and PostgreSQL row-level security, with the option to move large or regulated customers to their own database later. For identity, buy authentication from a provider, keep organisations, memberships and roles in your own database, start with simple role-based access control checked on the server for every request, and add SAML or OIDC single sign-on, SCIM provisioning and audit logs when enterprise customers ask for them.
What is the best multi-tenant database architecture for a B2B SaaS?
For most B2B SaaS products, start with a shared database and shared schema: every tenant-owned table has a tenant_id column, every query filters on it, and PostgreSQL row-level security acts as a second line of defence. Schema-per-tenant and database-per-tenant give stronger isolation but cost more to operate and migrate. A hybrid, where most tenants share and a few large or regulated customers get dedicated databases, is the usual end state.
The three models and the hybrid
AWS's Well-Architected SaaS Lens names three broad isolation models: silo, where a tenant gets dedicated resources; pool, where tenants share resources; and bridge, a mix where some parts of the system are pooled and others siloed. It also describes tier-based isolation, where premium tiers get dedicated environments. Applied to the database, these map to the options below.
| Model | How it works | Strengths | Costs and risks | Fits |
|---|---|---|---|---|
| Shared schema (pool) | One database, one set of tables; every row has tenant_id | Cheapest; one migration path; easy cross-tenant analytics for you | A missed filter leaks data; noisy neighbours; harder per-tenant restore | Most new B2B SaaS, from first customer to many thousands of tenants |
| Schema per tenant | One database, a Postgres schema per tenant with identical tables | Clearer separation; per-tenant backup and drop are simpler | Migrations run once per schema; catalogue bloat at high tenant counts; pooling gets harder | Tens to low hundreds of larger tenants |
| Database per tenant (silo) | Separate database or instance per tenant | Strongest isolation; per-tenant region, keys and scaling | Highest cost; fleet-wide migrations, monitoring and connections to manage | Enterprise, regulated or data-residency customers |
| Hybrid (bridge or tiered) | Shared by default, dedicated databases for chosen tenants | Matches cost to customer value | Two code paths for provisioning and routing if not designed in | The common end state for growing B2B SaaS |
Why we default to a shared schema
Early on, the biggest risks are shipping slowly and running migrations across many databases, not a lack of isolation. A shared schema keeps one migration path and one connection pool. The real risk is a query that forgets the tenant filter, which is why we pair application-level scoping with database-level enforcement. Our blog post on SaaS architecture patterns gives a short introduction to row-level security; the essentials are below.
Row-level security as a second line of defence
PostgreSQL's row security documentation (version 18 at the time of writing) sets out the behaviours you need to design around:
- Once RLS is enabled on a table, if no policy exists the default is deny: no rows are visible or modifiable.
- Superusers and roles with
BYPASSRLSalways bypass RLS, and table owners bypass it too unless you runALTER TABLE ... FORCE ROW LEVEL SECURITY. If your app connects as the table owner, your policies may silently do nothing. USINGcontrols which existing rows are visible;WITH CHECKcontrols which new or updated rows are allowed. WithoutWITH CHECK, theUSINGexpression is reused.- Permissive policies combine with OR; restrictive policies combine with AND. A restrictive tenant policy is a useful backstop.
- Referential integrity checks such as unique and foreign key constraints bypass RLS, so the docs warn about covert channels that can reveal whether a value exists in another tenant.
A common pattern is to set the current tenant per transaction (for example with SET LOCAL on a custom setting) and write policies that compare tenant_id with it. On Supabase, policies typically use auth.uid() with a membership lookup, and Supabase's RLS guide recommends indexing the columns policies filter on and wrapping helper calls as (select auth.uid()) so Postgres evaluates them once per statement.
Beyond the database
Tenant isolation also applies to file storage (prefix object keys by tenant and check access server-side), caches (include the tenant in every key), search indexes, background jobs (carry the tenant ID in the job payload and re-check it) and logs. The OWASP Authorization Cheat Sheet specifically calls out static resources and cloud storage as places where access control is often forgotten.
When a different approach makes sense
Start with database-per-tenant if your first customers contractually require it, for example a bank that requires a dedicated database in its region, or if each tenant's data set is large and independent, such as analytics on each customer's own warehouse. Schema-per-tenant can suit a product with a small number of large tenants who need per-tenant customisation. For growth beyond this, see scalable web application architecture.
How do I handle authentication, organizations, permissions and single sign-on in a modern SaaS?
Buy authentication from a provider rather than building it, but keep organisations, memberships and roles in your own database so your authorisation logic is yours. Start with a small set of roles checked on the server on every request, and move towards attribute- or relationship-based rules as permissions get finer. Add SAML or OIDC single sign-on, SCIM provisioning and audit logs when your first enterprise customers ask, and design the data model so adding them later is not a rewrite.
Authentication: build or buy?
Authentication is security-critical, full of edge cases (password resets, email verification, MFA, session revocation, account linking) and rarely a differentiator. In our view almost every SaaS should buy it. The question is which kind of provider: Our guide to what not to build in a SaaS applies the same build-or-buy test to email, billing and analytics.
| Option | Examples | Good for | Consider |
|---|---|---|---|
| Platform auth bundled with your database | Supabase Auth, Neon Auth (managed Better Auth) | Fast start; users live in your Postgres; integrates with RLS | Supabase documents SAML 2.0 SSO on Pro plans and above; check SCIM needs separately |
| B2B identity providers | WorkOS, Clerk | Organisations, enterprise SSO, directory sync, admin onboarding flows | Pricing varies by vendor, so check current pricing pages; another vendor in your trust chain |
| Open-source library in your app | Better Auth, or your framework's own auth such as the Rails 8 authentication generator | Full control, no per-user fees | You own security updates, SSO integration and operations |
WorkOS, for example, documents SSO over SAML and OIDC, Directory Sync over SCIM, audit logs, RBAC and an admin portal that customer IT teams use to set up their own connections. Clerk documents organisations with default admin and member roles, custom roles and permissions, invitations, verified domains and enterprise connections over SAML or OIDC. Compare them on the enterprise features you will need in a year, not just sign-up screens.
The organisation data model
Even if your auth provider has an organisations feature, mirror the core of it in your own database so you can join against it, enforce it in RLS and migrate providers later. A minimal model:
- users: your user ID plus the provider's user ID and email.
- organizations: the tenant;
id, name, plan, billing customer ID, data region, SSO settings. - memberships:
organization_id,user_id,role, status. A user can belong to several organisations; the active one is chosen per session. - invitations: email, organisation, role, token, expiry, inviter.
- domains: verified email domains for auto-join or SSO enforcement.
- audit_events: who did what, to which resource, in which organisation, when and from where.
Permissions: RBAC, then finer rules
Role-based access control (RBAC) maps users to roles such as owner, admin, member and viewer, and roles to permissions. It is easy to explain to customers and enough for most products at launch. Its limits appear when rules depend on attributes ("editors can publish only in their own department") or relationships ("anyone the document is shared with can comment"). The OWASP Authorization Cheat Sheet goes further than many teams expect: it says attribute-based and relationship-based access control (ABAC and ReBAC) should typically be preferred over RBAC for application development, because they handle fine-grained and contextual rules better.
A pragmatic path is to define permissions as named actions (invoice.read, project.delete) from day one, map roles to them, and check permissions, not role names, in code. That lets you add resource-level or attribute rules later without touching every check. Whatever model you choose, OWASP's core rules apply:
- Deny by default: access needs an explicit grant.
- Check on every request, on the server: OWASP says developers must never rely on client-side access control checks; hiding a button is not authorisation.
- Check the specific object: confirm the record belongs to the caller's organisation, not just that the caller is logged in, to prevent insecure direct object references.
- Apply least privilege and review role assignments over time.
- Test authorisation with automated tests that try cross-tenant access.
Single sign-on and SCIM
Enterprise buyers usually ask for SSO so their staff sign in through the company identity provider. The two protocols you will meet are SAML 2.0 and OpenID Connect (OIDC); supporting both through your auth provider covers most identity providers. Implementation points that save support time:
- Model SSO connections per organisation, linked to verified domains.
- Decide whether SSO is optional or enforced for an organisation, and what happens to existing password users.
- Map identity-provider groups or attributes to your roles, with a safe default role.
- Give customer admins a self-serve setup flow; vendor admin portals exist for this reason.
- Add SCIM when customers want automatic provisioning and, more importantly, deprovisioning. SCIM is defined by IETF RFC 7644 as a protocol for creating, reading, updating and deleting identity records across organisational boundaries. When someone leaves the customer's company, SCIM removes their access to your product without anyone remembering to do it.
Audit logs
Security questionnaires almost always ask for audit logs, and OWASP describes logging as one of the most important detective controls. Record sign-ins, failed sign-ins, role and membership changes, SSO configuration changes, data exports, deletions and billing changes, with actor, organisation, target, timestamp and IP. Make the log append-only, keep it for a defined period, and let organisation admins view or export their own events. Our guide to security questionnaires and SOC 2 explains what buyers typically ask for.
What to build when
| Stage | Build |
|---|---|
| MVP | Provider-based sign-in, organisations, memberships, invitations, three or four roles, server-side permission checks, tenant-scoped queries with RLS |
| First paying teams | MFA option, owner transfer, basic audit log, per-organisation settings |
| First enterprise deal | SAML/OIDC SSO, domain verification, SSO enforcement, audit log export |
| Larger enterprise base | SCIM provisioning, custom roles, resource-level permissions, dedicated-database option |
If you want help designing or implementing this, our B2B SaaS development service covers tenancy, permissions and SSO. If your product is early and your provider already handles organisations and roles well, you may not need custom work yet; follow the MVP row above and revisit at the first enterprise deal.
Frequently asked questions
Is row-level security enough to isolate tenants?
It is a strong second line of defence, not a complete answer. Your application should still scope every query by tenant, connect as a role that does not bypass RLS, and apply the same isolation to file storage, caches, search indexes and background jobs.
What is the difference between authentication and authorisation?
Authentication establishes who a user is, for example by password, passkey or single sign-on. Authorisation decides what that user may do, such as which organisation's data they can read and which actions their role allows. Most SaaS security incidents involving other tenants' data are authorisation failures.
When should a SaaS add SAML single sign-on?
Usually when the first larger customer asks for it, often during a security review. Choosing an auth provider that supports SAML and OIDC from the start makes this a configuration task rather than a project.
What is SCIM and do I need it?
SCIM is a standard protocol, defined in IETF RFC 7644, that lets a customer's identity provider create, update and remove user accounts in your product automatically. You need it when enterprise customers want joiners and leavers handled without manual steps, which typically comes after SSO.
Sources
- PostgreSQL 18 Documentation: Row Security Policies — Default deny, BYPASSRLS and table-owner bypass, FORCE ROW LEVEL SECURITY, USING vs WITH CHECK, permissive vs restrictive policies, referential integrity covert channels. Accessed 19 October 2026.
- AWS Well-Architected SaaS Lens: Silo, pool and bridge models — Definitions of silo, pool and bridge isolation models. Accessed 19 October 2026.
- AWS Well-Architected SaaS Lens: Tier-based isolation — Dedicated environments for premium tiers. Accessed 19 October 2026.
- AWS Whitepaper: SaaS Tenant Isolation Strategies — Background on tenant isolation as a foundational SaaS concern (published 2020; AWS marks it as historical reference). Accessed 19 October 2026.
- OWASP Authorization Cheat Sheet — Least privilege, deny by default, validate on every request, prefer ABAC/ReBAC over RBAC, IDOR, static resources, server-side checks, logging, testing. Accessed 19 October 2026.
- Supabase Docs: Row Level Security — auth.uid() policies, indexing policy columns, wrapping helper calls in select. Accessed 19 October 2026.
- Supabase Docs: SAML SSO — SAML 2.0 SSO available on Pro plans and above. Accessed 19 October 2026.
- Neon Docs: Managed Better Auth — Neon Auth as managed Better Auth stored in the database. Accessed 19 October 2026.
- WorkOS Documentation — SSO (SAML/OIDC), Directory Sync (SCIM), Audit Logs, RBAC, FGA and Admin Portal. Accessed 19 October 2026.
- Clerk Docs: Organizations — Default and custom roles and permissions, invitations, verified domains, enterprise connections over SAML or OIDC. Accessed 19 October 2026.
- Ruby on Rails 8.0 Release Notes — Rails 8 authentication generator. Accessed 19 October 2026.
- IETF RFC 7644: SCIM Protocol — Definition of the SCIM protocol for managing identities across domains. Accessed 19 October 2026.
Recommendations without a source are AI Dev Planner’s own engineering opinion. Platform features and prices change; check the linked pages for the current position. Found an error? See our corrections policy.
Related guides
- Tech Stack & ArchitectureSupabase vs Neon, and Drizzle vs Prisma: Choosing Your PostgreSQL LayersPlatform, database host and ORM are different layers. How Supabase, Neon, Drizzle and Prisma compare, and sensible pairings.
- Operations, Security & ComplianceThe SaaS Security Questionnaire: How Small Teams Handle SOC 2, SIG and Buyer ReviewsAnswer libraries, evidence, trust pages and when SOC 2 is worth starting, explained for small SaaS teams.
- Building & Shipping ProductsScalable Web Application Architecture: From Maintainable MVP to GrowthModular monolith first, clear module boundaries, tests at the seams, and a stage-by-stage path to scale.
- Tech Stack & ArchitectureChoosing a SaaS Tech Stack in 2026: Is Next.js, Supabase and Stripe Still the Default?When the Next.js, Supabase and Stripe default is right, when Rails, Laravel, Django or .NET fit better, and how to decide.
Browse all 50 questions in the SaaS & web development guide.
Designing tenancy and permissions for a B2B product?
Share your customer profile and compliance needs, and we will recommend an isolation model and identity setup you can grow into without a rewrite.