Skip to main content
Tech Stack & Architecture

Multi-Tenant SaaS Architecture: Databases, Organisations, Permissions and SSO

By Obaid Tariq, Founder & Lead Engineer · Published · Updated

Obaid founded AI Dev Planner in 2022 and leads engineering on its client projects from Islamabad, Pakistan.

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 business software products without contractual or regulatory requirements for dedicated infrastructure, we recommend starting with one shared database for all customers. Each company's information is clearly identified and protected so that customers can only access their own data, with multiple layers of security — including database rules that restrict which records each customer can access (row-level security, or RLS) — to prevent one company from seeing another company's information, and if larger customers eventually need separate databases, the software can be designed to support that change. For most teams, using an established sign-in service is a better starting point than building a login system from scratch. You can choose a managed provider or an open-source solution that you host and maintain yourself, while keeping control of your customer accounts, team members and permissions. Start with simple role-based access control (giving users clear job titles like admin or viewer tied to specific actions), 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 new business software products, we recommend starting with one shared database for all customers, with each company's information clearly identified and protected so customers can only access their own data. Multiple layers of security — including database rules that restrict which records each customer can access (row-level security, or RLS) — prevent one company from seeing another company's information. Giving every customer a separate data structure or an entirely separate database provides additional separation but costs more to maintain. Another option is to share resources among most customers while giving larger businesses their own databases when necessary — one possible growth strategy, not the only destination.

Multi-tenant SaaS architecture means one software product shared by multiple companies — each company is a tenant — while keeping each tenant's data and settings separate and private. All customers use the same underlying software, which makes updates and maintenance easier, because the team does not need to build and maintain a completely different product for every customer. The important requirement is that each customer's information remains private. This describes the shared model; a hybrid setup may need separate infrastructure for some customers.

The three models and the hybrid

There are three common ways to organise customer information and infrastructure. In the first, every customer gets separate resources. In the second, customers share resources while their information remains separated. In the third, the software combines both approaches. AWS describes these as silo, pool and bridge models. AWS also describes tier-based isolation, where higher-paying customers receive separate infrastructure. Applied to the database, these map to the options below.

Multi-tenant database models compared
ModelHow it worksStrengthsCosts and risksFits
Shared schema (pool)One database, one set of tables; every record carries a customer ID tag (tenant_id)Lowest cost; updates to the database structure need to be managed in one place; easier to create reports across customer accountsA missed customer check can expose another customer's data; one customer's heavy usage can affect another customer's performance; harder to restore one customer's information on its ownMost new B2B SaaS, from first customer to many thousands of tenants
Schema per tenantOne database, a separate schema (the layout of tables and rules) for each customer, with identical tablesClearer separation between customers; backing up or removing one customer's data is simplerDatabase structure updates must run once per customer; the database's internal list of structures becomes slow or heavy with many customers (catalogue bloat); sharing database connections gets harderTens to low hundreds of larger customers (as a guide only — workload, operations, security needs and contracts matter as much as customer count)
Database per tenant (silo)A separate database for each customerStrongest separation at the database level; each customer can have separate hosting locations, security settings and capacityHighest cost; database updates, monitoring and connections must be managed across all customer databasesLarge companies, regulated industries, or customers who need their data kept in a specific country or region (data residency)
Hybrid (bridge or tiered)Shared by default, with separate databases for selected customersMatches cost to customer valueThe software needs additional processes to set up and direct customers to their separate databases if this is not designed in from the startA common growth path for growing B2B SaaS — one possible end state, not the only destination
  1. Step 1

    Start shared

    One database and schema; every record carries a customer ID tag

  2. Step 2

    Enforce with RLS

    Application scoping plus PostgreSQL row-level security

  3. Step 3

    Move out when needed

    Move selected customers to separate databases when their security, regulatory or operational requirements justify it. The application must be designed to identify and connect to the correct database.

How a tenant moves from shared to dedicated when the move is designed in from day one

Why we default to a shared schema

When a SaaS product is new, maintaining many separate databases can slow development and increase costs. A shared database structure is usually simpler to manage. However, the software must always identify which customer a request belongs to. Otherwise, a mistake could expose another customer's information — a common failure is a lookup that forgets to filter by customer. That's why we recommend checking customer access in both the application and the database. Security requirements exist from the first customer, even with a shared database. Our blog post on SaaS architecture patterns gives a short introduction to row-level security; the essentials are below. To design the database structure, generate a multi-tenant Postgres schema with row-level security built in. For how we enforce and test this in practice, see tenant isolation with PostgreSQL RLS.

Row-level security as a second line of defence

Once you turn on row-level security (database rules that control which customer records someone can see or change) for a table, nobody can view or change data there until you add clear rules. However, top-level database accounts and table owners can skip those rules by default unless you explicitly force rules onto table owners too — so your app should not connect with unrestricted owner privileges. In your rules, one check (USING) determines which existing records a user can access or change. A second check (WITH CHECK) determines which new or updated records they are allowed to save. When you leave WITH CHECK out of a policy that defines USING, PostgreSQL reuses the USING expression as the check for permitted changes.

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

Protecting customer information is not just about the database. The same separation must apply to uploaded documents, temporary stored information, search results, automated background tasks and activity records. Every part of the software must know which customer it is working for and check that the customer has permission to access the information. The OWASP Authorization Cheat Sheet specifically calls out stored files and online storage as places where permission checks are often forgotten.

When a different approach makes sense

Start with a separate database for each customer (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 customer's data set is large and independent, such as analytics on each customer's own warehouse. A separate data structure for each customer (schema-per-tenant) can suit a product with a small number of large customers who need customisation for each customer. A separate database alone does not make the application secure: permissions, application logic, backups, administrator access, file storage and integrations still need protection. For growth beyond this, see scalable web application architecture.

How do I handle authentication, organizations, permissions and single sign-on in a modern SaaS?

Use an established sign-in service instead of building your own login system, but keep control of your customer accounts, team members and permissions, so your permission rules stay yours. Start with a few simple roles, such as owner, administrator and team member, and check permissions on the server whenever someone performs an action — adding more detailed rules later, such as access only for specific departments or shared documents, when you need them. Add single sign-on through SAML or OIDC (letting employees sign in using their company's existing account), SCIM provisioning (automatically creating and removing employee accounts) and audit logs (a history of who did what, and when) when your first enterprise customers ask. Design the data model so adding them later is not a rebuild.

Authentication: build or buy?

Building a secure login system requires handling many situations, including forgotten passwords, email verification, additional security checks (multi-factor authentication, or MFA), ending someone's existing sign-in access, and connecting multiple sign-in methods to one account. These features are essential, but they usually do not make your product unique. For most new SaaS products, using an established login service is a more practical choice — though there are exceptions: per-user pricing can grow steeply as a customer company grows, and some teams need control that a provider does not offer. 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.

Types of authentication provider and when each fits
OptionExamplesGood forConsider
Login functionality included with your database serviceSupabase Auth, Neon Auth (managed Better Auth)Fast start; user information is stored in your database (Postgres); works with database-level access restrictions (RLS)Supabase documents SAML 2.0 SSO on Pro plans and above; check SCIM needs separately
Business login services (B2B identity providers)WorkOS, ClerkCompany accounts, enterprise single sign-on, automatic employee account syncing, and admin setup flowsPricing varies by vendor, so check current pricing pages; another vendor in your trust chain
A freely available software component you can use and customise (open-source library) in your appBetter Auth, or your framework's own auth such as the Rails 8 authentication generatorFull control, with no per-user fee for the open-source software itself. You still pay for hosting and are responsible for maintenance, security and ongoing operations.You are responsible for keeping the login system secure and maintained, including single sign-on integration and operations

WorkOS, for example, documents single sign-on over SAML and OIDC, Directory Sync over SCIM, audit logs, role-based access control (RBAC) and an admin portal that customer IT teams use to set up their own connections. Clerk documents company accounts (organisations) with default admin and member roles, custom roles and permissions, invitations, verified domains and enterprise connections over SAML or OIDC. Features, availability and pricing depend on the specific product and subscription — check the current documentation before deciding. Compare them on the enterprise features you will need in a year, not just sign-up screens.

The organisation data model

Even if your login service manages company accounts, keep a copy of the important account information in your own database. This gives you more control over customer relationships and permissions and makes it easier to change login providers later. A minimal model:

  • Users: people who can sign in — your user ID plus the login provider's user ID and email.
  • Organisations: customer companies — the company account, with its name, plan, billing customer ID, data region and sign-in settings.
  • Memberships: records showing which people belong to which company accounts — which person, which company, which role, and whether the membership is active. A person can belong to several companies; the company they are currently working in is chosen per sign-in session.
  • Invitations: invitations for new team members — email, company, role, and expiry.
  • Domains: verified company email domains (such as acme.com), used for automatic joining or to enforce company sign-in.
  • Audit events: a record of important actions performed in the software — who did what, which record was affected, which company it belonged to, when the action happened and where it came from.

Organizations, workspaces and teams: one tenant model, different names

Decide what customers will see in your product: company, organisation, workspace or team. Use one consistent name throughout the application. Products call the customer company different things, but the data model underneath is the same: Clerk's organizations documentation says organizations let you build multi-tenant B2B apps "like Slack (workspaces), Linear (teams), or Vercel (projects)", that users can belong to multiple organizations, and that the organization a user is currently viewing is the Active Organization, which determines their data access and role. Keep company accounts and memberships as the records underneath, and decide early whether a user can also have a personal workspace that is not shared, because that changes sign-up, billing and invitations. Also decide whether users can have a private personal account alongside their company account — this affects how registration, payments and team invitations work.

  • One active company account per sign-in session or tab: the software must remember which company the user is currently working in, and verify their membership every time they access information rather than relying only on previously stored sign-in information.
  • Workspaces inside a company account (for example projects inside a company account) are a second level: keep them as their own record linked to the company, and decide whether roles are granted per company, per workspace or both.
  • Billing attaches to the company account, not the person, so someone who belongs to two customers never mixes their invoices.

Permissions: RBAC, then finer rules

Role-based access control (RBAC) means giving people access according to their responsibilities. For example, an owner can manage the entire account, an administrator can manage team members, and a regular member can use the features they need for their work. It is easy to explain to customers and enough for most products at launch. Simple roles are not always enough. Some products need more detailed rules. For example, an employee might only be allowed to publish content for their own department, or a person might be allowed to comment on a document only when someone has shared it with them. 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. That is a practical trade-off: role-based access is easier to set up and manage for straightforward products, while attribute- and relationship-based rules fit when permissions depend on finer details — which one fits depends on what your product needs.

A good approach is to define what people can actually do, such as viewing invoices or deleting projects. Then assign those abilities to the appropriate roles. Have your code check whether the user has the action rather than hardcoding role names everywhere. This makes it easier to introduce more detailed permissions as the product grows. Whatever model you choose, OWASP's core rules apply:

  • Deny by default: nobody gets access unless permission is explicitly granted.
  • Check permissions on every request, on the secure server: OWASP says developers must never rely on checks performed in the user's browser; hiding a button is not authorisation.
  • Check the specific record: confirm the record belongs to the caller's company, not just that the caller is signed in — this prevents a security weakness where someone accesses another person's information by changing an item reference or address.
  • Give each person only the access they actually need (least privilege) and review role assignments over time.
  • Test permissions with software checks that run automatically and try to access another customer's data.

Multi-tenant organization routing patterns

When someone opens your software, it must identify which company account they belong to before showing any information. There are three common ways to do this.

Multi-tenant organization routing patterns compared
PatternURL ExampleHow Tenant Context ResolvesTrade-offs
Subdomain routingacme.yourapp.comThe software checks the website address to identify the company, then checks that the person belongs to that companyClean enterprise branding and separate sign-in per company address; needs additional website and security configuration to support multiple company addresses, and sign-in must work across them
Path-prefix routingapp.yourapp.com/org/acme/billingThe company is identified through the website address, such as yourapp.com/org/acme, after verifying the person belongs to that companyOne shared website address and sign-in; ideal when people switch between different company accounts in one session
Session/token-scoped routingapp.yourapp.com/dashboardThe software remembers the selected company after the user signs in, changed through a company switcherSimplest website addresses; a shared link might open under the wrong company account if the company is not checked

Single sign-on (SAML/OIDC), Home Realm Discovery and SCIM

Larger companies often want their employees to sign in through the login system they already use at work (single sign-on, or SSO). The two standards you will meet are SAML 2.0 and OpenID Connect (OIDC); supporting both through your login service covers most company sign-in systems. For domain-based SAML/OIDC enterprise federation, use Home Realm Discovery (HRD): the user enters their work email (alice@acme.com), the software checks acme.com against the company's verified email domains and redirects the user to the company's identity provider (the service that handles employee sign-in) instead of showing the usual password form. Map verified company sign-in groups to your internal RBAC roles, and add SCIM (a standard for automatically creating, updating and deactivating or removing employee accounts across systems) when customers want employee access managed automatically. Enterprise single sign-on can still require integration, testing, customer-specific configuration and security review — supporting SAML and OIDC makes it simpler, not automatic.

  1. Keep a record of each company's single sign-on connection, linked to its verified email domains.
  2. Decide whether SSO is optional or enforced for an organisation, and what happens to existing password users.
  3. Map company sign-in groups or details to your roles, with a safe default role.
  4. Give customer admins a setup flow they can complete themselves without contacting support; vendor admin portals exist for this reason.
  5. 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 (a history of who did what in the software and when), and OWASP describes logging as one of the most important ways to detect problems. Keep an accurate history of important actions, including who signed in, changed permissions, downloaded information or deleted records. Keep the history append-only, meaning new events can be added but existing records cannot be silently changed or deleted. Restrict access to the logs and let company administrators review and download their own activity records. Keep it for a defined period. Our guide to security questionnaires and SOC 2 explains what buyers typically ask for.

What to build when

A staged plan for identity and access in a B2B SaaS
StageBuild
MVPProvider-based sign-in, organisations, memberships, invitations, three or four roles, server-side permission checks, tenant-scoped queries with RLS
First paying teamsMFA option, owner transfer, basic audit log, per-organisation settings
First enterprise dealSAML/OIDC SSO, domain verification, SSO enforcement, audit log export
Larger enterprise baseSCIM 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. For client-facing platforms where external organizations need self-service access to documents, billing and order status, our detailed guide to customer portal development explores multi-tenant permissions, database isolation and ERP integration in depth. If your product is early and your provider already handles organisations and roles well, you may not need custom work yet — but buying a login service does not automatically secure every customer record: the application must still verify access to each specific record. Follow the MVP row above and revisit at the first enterprise deal.

Which RBAC providers should I use for a multi-tenant B2B SaaS instead of building from scratch?

If your needs are role-based access (giving users clear job titles like admin or viewer tied to specific actions) plus enterprise single sign-on and SCIM (automatically creating and removing employee accounts), use a business login service with built-in company accounts and RBAC, such as WorkOS, Clerk, or Auth0 Organizations. Use Supabase Auth or Better Auth when you want users inside your own Postgres database. If your product needs more advanced permission rules than standard user roles can provide, you can add a specialist permissions service — such as OpenFGA (Auth0 FGA), Permit.io, Cerbos, or Oso — while keeping your own company accounts and membership records in your database. This is useful for products with shared documents, department-specific access or complicated team structures.

RBAC and B2B authorization provider categories for multi-tenant SaaS
CategoryRepresentative ProvidersBest FitWhat to Keep in Your Own DB
Turnkey B2B Auth + Orgs + RBAC + SSOWorkOS, Clerk, Auth0 OrganizationsB2B SaaS needing org switching, custom roles, SAML/OIDC SSO, SCIM and admin portals quicklyMirror organizations, memberships and roles so SQL joins and RLS work locally
Postgres-native / Open-source AuthSupabase Auth + RLS, Better Auth (or Neon Auth)Teams wanting user and session tables inside their own PostgreSQL with minimal vendor lock-inDefine explicit permissions mappings and server-side guards alongside RLS
Dedicated Fine-Grained AuthZ (RBAC/ABAC/ReBAC)OpenFGA / Auth0 FGA, Permit.io, Cerbos, OsoProducts with document sharing, folder hierarchies, team-scoped resources, or compliance audit policiesKeep canonical resource ownership and tenant IDs in Postgres; sync tuples/policies via events

Whichever provider you pick, never treat role information stored in the user's browser, or checks that only hide buttons, as permission checks. Enforce permissions on every server route and every operation that changes information, and backstop customer boundaries with PostgreSQL row-level security (RLS).

How much does multi-tenant architecture add to SaaS build cost?

On our published US bands, shared-database tenancy with row-level security fits a focused SaaS MVP ($25,000–$65,000, 8–12 weeks); detailed permission controls and usage-based billing point to the standard tier ($45,000–$75,000); single sign-on, audit logs and dedicated databases for chosen customers point to the enterprise tier ($75,000–$120,000+). Adding customer separation and permissions while building your product is usually more straightforward than trying to add them after the software is already in use. Planning for these requirements early can help avoid additional development work later.

Which published tier each tenancy and identity choice usually belongs to
Choice in this guideUsual tier on our US bands
One shared database with separate customer records and database-level security, company accounts, memberships, invitations, and three or four rolesFocused SaaS MVP ($25,000–$65,000)
More detailed controls over what each employee can access, charging customers according to how much they use the product, and a customer portal customers can use themselvesStandard multi-tenant SaaS ($45,000–$75,000)
Company-managed employee sign-in (SAML/OIDC SSO), confirming that a company owns its email domain, downloadable records of important account activity, and separate databases for customers who need additional separationEnterprise SaaS & AI ($75,000–$120,000+)

These figures are estimates to help with planning, not fixed project quotes. They do not include monthly hosting charges or additional fees from external services, such as login providers that charge according to the number of users or connections. The full breakdown of every cost driver, including billing, AI usage, testing and meeting applicable requirements, lives in our guide to how much it costs to build a SaaS; put your own scope through the SaaS MVP cost calculator for an indicative range.

Frequently asked questions

Are Clerk organizations the same as workspaces in a B2B SaaS?
Yes. A Clerk organisation and a workspace serve a similar purpose: they represent a company or group of people working together inside your software. A user can belong to multiple companies and switch between them. The software must then show information and permissions belonging to the selected company only.
How much does multi-tenancy add to the cost of building a SaaS?
Shared-database multi-tenancy with row-level security fits inside our focused SaaS MVP band of $25,000 to $65,000 if it is designed in from the start. More detailed permission controls and usage-based billing move a build to the $45,000 to $75,000 tier, and SAML single sign-on, audit logs or dedicated databases for some customers to the $75,000 to $120,000+ tier. Adding tenancy to a single-tenant app later usually costs more than building it in.
Should a multi-tenant SaaS use subdomain routing or path-based organization routing?
Use a separate website address for each company when customers expect their own branded login page or website address. Use a company-specific section of one shared website when employees frequently switch between different company accounts.
How does domain-based SAML/OIDC enterprise federation work in a multi-tenant SaaS?
When an employee enters their company email address, your software checks which company owns that email domain. It then sends the employee to that company's sign-in system and applies the correct permissions after they sign in.
Which RBAC providers should I use instead of building from scratch?
For standard business roles paired with SAML/OIDC single sign-on and SCIM, WorkOS, Clerk, or Auth0 Organizations cover company accounts and permissions out of the box (while Better Auth and Supabase Auth fit teams who keep users in their own Postgres database). For more detailed resource-level permissions (ABAC/ReBAC), add a dedicated engine such as OpenFGA, Permit.io, Cerbos, or Oso.
Is row-level security enough to isolate tenants?
Row-level security adds an important layer of protection, but it is not enough on its own. The application must also check which customer the user belongs to. The same protection must apply to uploaded files, search results, temporary stored information and automatic background tasks.
What is the difference between authentication and authorisation?
Authentication answers: 'Who are you?' For example, it checks your password or company sign-in. Authorisation answers: 'What are you allowed to do?' For example, it decides whether you can view invoices, manage employees or access a particular company's information. When one customer can see another customer's data, the cause is often a permission check that was missing or wrong, rather than a login failure.
When should a SaaS add SAML single sign-on?
Usually when the first larger customer asks for it, often during a security review. Choosing a login service that supports SAML and OIDC from the start makes this much simpler — usually a configuration task rather than a full project — though it can still need integration, testing, customer-specific configuration and security review.
What is SCIM and do I need it?
SCIM is a standard that helps businesses manage employee accounts automatically across different software products. When someone joins a company, their account can be created automatically. When they leave, their access can be removed without requiring an administrator to update every application manually.

Sources

  1. 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 (Clerk organizations: 2 December 2026).
  2. AWS Well-Architected SaaS Lens: Silo, pool and bridge models — Definitions of silo, pool and bridge isolation models. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  3. AWS Well-Architected SaaS Lens: Tier-based isolation — Dedicated environments for premium tiers. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  4. 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 (Clerk organizations: 2 December 2026).
  5. 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 (Clerk organizations: 2 December 2026).
  6. Supabase Docs: Row Level Security — auth.uid() policies, indexing policy columns, wrapping helper calls in select. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  7. Supabase Docs: SAML SSO — SAML 2.0 SSO available on Pro plans and above. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  8. Neon Docs: Managed Better Auth — Neon Auth as managed Better Auth stored in the database. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  9. WorkOS Documentation — SSO (SAML/OIDC), Directory Sync (SCIM), Audit Logs, RBAC, FGA and Admin Portal. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  10. Clerk Docs: Organizations — Default and custom roles and permissions, invitations, verified domains, enterprise connections over SAML or OIDC; organizations as the model for apps like Slack (workspaces), Linear (teams) or Vercel (projects); membership of multiple organizations and the Active Organization (accessed 2 December 2026). Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  11. Ruby on Rails 8.0 Release Notes — Rails 8 authentication generator. Accessed 19 October 2026 (Clerk organizations: 2 December 2026).
  12. IETF RFC 7644: SCIM Protocol — Definition of the SCIM protocol for managing identities across domains. Accessed 19 October 2026 (Clerk organizations: 2 December 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.

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.