No. 66SaaS9 min read2,295 words
How to build a multi-tenant SaaS: architecture and cost
A founder's guide to building a multi-tenant SaaS: tenant isolation, org-based auth, per-tenant billing, the stack we use, realistic timelines and traps.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways · 05
The short version
- 01Build a multi-tenant SaaS on one shared Postgres database with a tenant_id on every business table, and enforce it with row-level security so a forgotten filter returns nothing instead of another customer's data.
- 02The tenant (the customer organization) is the unit of billing, permissions and configuration, not the individual user. Model organizations, memberships and roles from day one.
- 03A sellable multi-tenant MVP needs only tenants, org-scoped auth, three roles, invites, billing per organization and one real feature. SSO, custom roles and white-labeling can wait for paying customers.
- 04Choose database-per-tenant only when a contract or regulator requires it. It multiplies migrations, backups and monitoring by the number of customers.
- 05The expensive failures are cross-tenant leaks in caches, background jobs and admin tools, not in the main request path. Give each of them the same tenant discipline.
On this page · 10
To build a multi-tenant SaaS, you run one codebase and one shared database for all your customers, tag every row of customer data with a tenant ID, and make the database itself refuse to return rows that belong to another tenant. On top of that sit organization-based login, roles, invites and billing per organization. That is the whole architecture. The hard part is keeping the isolation true through years of new features, new engineers and late-night deploys.
This guide is the version we would give a founder over coffee: what to build first, what to skip, where the real work hides, which stack we use and roughly what it takes. If you want the plain-English background first, start with what multi-tenancy actually is.
What a multi-tenant SaaS is, and when you need one
A multi-tenant SaaS serves many customer organizations from shared infrastructure. Each organization is a tenant. Its users, data and settings live alongside everyone else's, separated by software rather than by running a separate copy of the app per customer. This shared, pooled model is so central to cloud software that NIST's definition of cloud computing names it explicitly under resource pooling.
The job is simple to say and brutal to get wrong: isolate tenants completely while sharing infrastructure efficiently. Get isolation wrong and you have a data breach. Get sharing wrong and your hosting bill grows in step with your customer count, which erodes the margins that make SaaS attractive.
You need this if you sell to businesses and each customer is a company with several people logging in. If you are building a consumer app where every user is an island, most of this is overkill. You need it the day a buyer asks "can my whole team get in?" and "can I see who changed this?"
The core data model: tenants, users and memberships
Everything else hangs off three tables. Get these right and the rest of the build is ordinary product work.
- Tenants (organizations): the customer company. It owns the subscription, the settings and all business data.
- Users: a person with a login. A user is not owned by a tenant.
- Memberships: the link between a user and a tenant, carrying the role. One user can belong to several organizations, which matters more than founders expect: consultants, agencies and anyone who uses your product at two jobs will need it.
Every table that holds customer data gets a non-null tenant_id. Not just the top-level tables: comments, attachments, audit entries and join tables too. When a table "obviously" belongs to a tenant through a parent row, add the column anyway. It makes isolation enforceable, indexing simple and data export trivial.
The MVP feature set: what to build first
Build first:
- Tenant model and isolation. The foundation. Everything below depends on it.
- Auth scoped to a tenant. Logging in establishes who you are; selecting an organization establishes which tenant you are acting inside.
- Basic roles. Owner, admin and member is enough to start. Owners handle billing, admins manage people, members do the work.
- Invites. How a tenant grows its team: email an invite, the person accepts, they land in the right organization with the right role.
- Billing per tenant. The organization pays, not the individual user, whether you charge per seat, per plan or per unit of usage.
- One real feature. The thing customers will pay for, built properly.
Build later:
- Custom roles and fine-grained permissions. Real, but most early customers are fine with three roles.
- SSO (SAML or OIDC). Enterprise buyers will ask for it. Your first ten customers will not.
- Custom domains, white-labeling and theming per tenant.
- Audit logs and self-serve data export. Cheap to add later if every row already carries
tenant_id. - Dedicated databases for specific tenants.
The mistake we see most often is a team building a configurable permission system and white-label theming before a single tenant pays. Ship the isolated core, sell it, then earn the rest.
Choosing a tenant isolation model
There are three broad models, and they trade simplicity for blast radius. AWS's SaaS tenant isolation guidance and Microsoft's tenancy models guide describe the same spectrum in more depth.
| Model | How it works | Best for | Main cost |
|---|---|---|---|
| Shared database, shared schema | One set of tables, a tenant_id column on every row | Most B2B SaaS, from first customer to thousands | Isolation depends on discipline, so enforce it in the database |
| Schema per tenant | One Postgres schema per tenant in the same database | Tens to low hundreds of larger accounts | Every migration runs once per schema; pooling gets fiddly |
| Database per tenant | A separate database (sometimes a separate cluster) per tenant | Regulated data, contractual isolation, very large accounts | Provisioning, migrations, backups and monitoring multiplied by tenant count |
Our default is the shared model, enforced in one place rather than trusted to every developer. Start shared, and isolate harder only when a real customer or regulator forces it. Because every row carries a tenant_id, promoting one tenant to its own database later is a data move, not a redesign. We go deeper on the trade-offs, connection pooling and edge cases in multi-tenant architecture without the headaches.
Enforce isolation in the database with row-level security
Hoping every query includes WHERE tenant_id = ... is how leaks happen. Broken access control still sits at the top of the 2025 OWASP Top 10 for a reason. Postgres has a real answer: row-level security (RLS). You set the current tenant at the start of each transaction, and the database refuses to return or write rows for any other tenant.
-- Every tenant-owned table carries the tenant id
create table projects (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null references tenants(id),
name text not null,
created_at timestamptz not null default now()
);
create index on projects (tenant_id);
-- Turn on row-level security, and force it for the table owner too
alter table projects enable row level security;
alter table projects force row level security;
-- Rows are visible and writable only for the current request's tenant.
-- If no tenant is set, the comparison is NULL and nothing matches.
create policy tenant_isolation on projects
using (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid)
with check (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);Your app opens a transaction per request and sets the tenant before touching data:
begin;
select set_config('app.tenant_id', '4b1c2d3e-0000-4000-8000-000000000000', true);
-- ...queries for this request...
commit;The third argument true scopes the setting to the transaction, so it cannot leak into the next request that reuses the pooled connection. Two details matter: force row level security stops the table owner (often your app's database user) from silently bypassing the policy, and your application must connect as a role without the BYPASSRLS attribute or superuser rights, because those always skip policies.
Now a forgotten filter returns zero rows instead of someone else's data. The database is the backstop, not code review. If you only take one decision from this post, take this one.
Org-scoped auth, roles and invites
Authentication answers "who are you?" Multi-tenancy adds "which organization are you acting for, and what may you do there?" Keep the active tenant in the session, verify the membership on the server for every request, and pass the tenant ID into the database transaction above. Never take a tenant ID from a URL or form field and trust it without checking the membership.
We use a managed auth provider that understands organizations natively (Clerk, WorkOS and Auth0 all do) rather than building org-based auth ourselves. Invites, role changes, removing a user who belongs to two orgs, and SSO each have edge cases that will eat months. Keep the check close to the data, not only in routing.
Keep authorization checks in one module (can(user, action, resource)) rather than scattered if (role === "admin") lines. The OWASP authorization cheat sheet is a good checklist: deny by default, check on every request, and validate permissions on the server even when the UI already hides the button.
Billing per organization
The billing provider bills the tenant, not the logged-in user. That breaks a lot of naive assumptions:
- Map one billing customer to one tenant. Store the provider's customer ID on the tenant row.
- Derive seats from active memberships. When people are invited or removed, sync the billed quantity from the real count rather than incrementing a number by hand.
- Decide what a failed payment means. Read-only mode, a grace period or a lockout. Make it a product decision written down before anyone codes it.
- Mirror subscription state into your own database from webhooks, and make the handlers idempotent, because providers deliver events more than once and out of order.
- Gate features by plan in one place, from a per-tenant entitlements object rather than plan names scattered through the code.
We cover the details in implementing subscription billing, and if you charge per unit of usage, in usage-based billing for SaaS.
The per-tenant config surface
Plans, limits (maximum projects, seats, API rate), feature flags, branding and early-access toggles all vary per tenant. Put them behind a single settings and entitlements object per tenant from day one, with defaults coming from the plan and explicit overrides on top. Scatter them across fifteen boolean columns and you will regret it by customer fifty.
The stack we reach for, and the timeline
Our default stack
Nothing exotic. The exotic choice is the one that hurts at scale.
| Layer | Our default | Why |
|---|---|---|
| App framework | Next.js 16 with TypeScript | One framework for marketing pages, the app and the API; types catch "wrong tenant" bugs before they ship |
| Database | Postgres | Row-level security, solid transactions and room to grow before you need anything else |
| Auth | Managed provider with organizations (Clerk, WorkOS, Auth0) | Invites, roles and SSO without months of edge cases |
| Billing | Stripe, with webhooks driving internal state | Mature subscriptions, proration, retries and a hosted customer portal |
| Background work | A job queue | Provisioning, exports, invite emails and billing sync stay out of the request path |
Our SaaS platforms work is built on this stack, and we keep it boring on purpose: every team member can work across all of it.
Rough timeline and cost
These are our planning ranges for a small senior team, not quotes. Every "it depends" applies.
| Phase | What is in it | Rough duration |
|---|---|---|
| Isolated core | Tenants, memberships, auth, three roles, invites, one real feature | 4 to 7 weeks |
| Commercial layer | Billing per tenant, settings and entitlements, a polished dashboard | 4 to 8 weeks |
| Sellable v1 | Both of the above, hardened and in front of paying customers | 2 to 4 months |
In money, a serious v1 from a senior team tends to land in the mid five figures and up, depending on how much of the "later" list creeps into "now." Enterprise requirements push it higher. The cheapest version is rarely the cheapest over two years, because rework on a leaky tenant model is among the most expensive fixes there is. Our breakdown of what it costs to build a SaaS shows where the rest of the budget goes.
Common mistakes and how to avoid them
- Caches without the tenant in the key. A memoized
getSettings()keyed on"settings"will serve tenant A's config to tenant B. Prefix every key with the tenant ID. - Background jobs with no tenant context. Queue consumers run outside any request. Put the tenant ID in every job payload and run the job through the same tenant-scoped transaction.
- Admin tools that disable isolation. Internal dashboards need cross-tenant reads. Give them a separate, clearly named database role that can bypass RLS, and keep it out of the customer-facing path.
- The noisy neighbor. One tenant runs a giant export and everyone slows down. Watch slow queries per tenant and rate-limit expensive operations early, as Microsoft's noisy neighbor antipattern describes.
- Seat drift. Invites, deactivations and billed seats fall out of sync. Reconcile them on a schedule.
- No tenant-aware tests. Write an automated test that logs in as tenant A and tries to read tenant B's records through every API route. It is the cheapest insurance you will ever buy.
What to do first
- Write down your tenant model: what a tenant is, how users join one, and the three roles.
- Create the tenants, users and memberships tables, and put
tenant_idon every business table. - Turn on row-level security with forced policies, and connect your app as a role that cannot bypass them.
- Wire auth so every request carries a verified tenant and membership.
- Build one real feature end to end, then billing per tenant.
- Add the cross-tenant leak test to CI before the second engineer joins.
A multi-tenant SaaS is not hard because of any one feature. It is hard because isolation has to stay true forever, billing lives at the organization level, and the config surface grows behind your back. Get the tenant model and database guardrails right early, keep the MVP boring, and earn the fancy parts once a customer is paying. For how to scope that first version tightly, see how to ship a SaaS MVP in weeks.
This is squarely the kind of system we build and take over through our SaaS development practice: products that have to be correct on day one and still correct after two years of features. If you are starting one, or untangling one that grew faster than its foundations, tell us what you are building and we will give you the honest version.
Two early decisions shape everything here: the database and the authentication provider. Our roundups compare the main options.
FAQ · 05 questions
Frequently asked questions
What is the best database design for a multi-tenant SaaS?
For most B2B products, a single shared database with a tenant_id column on every tenant-owned table is the best starting point. It is the cheapest to run and the simplest to migrate. Enforce isolation with Postgres row-level security, and move individual large or regulated customers to dedicated databases later if a contract requires it.
Should each customer get their own database?
Usually not at the start. A database per tenant gives the strongest isolation, but every migration, backup, connection pool and alert has to be managed once per customer. It makes sense for a small number of high-value or regulated accounts, and a well-designed shared system can promote those customers to their own database when needed.
How long does it take to build a multi-tenant SaaS?
As a rough planning range, an isolated core with tenants, auth, roles, invites and one real feature takes about four to seven weeks for a small senior team. A sellable first version with billing, settings and a polished dashboard usually lands at two to four months. Enterprise features such as SSO and audit logs add to that.
Can I add multi-tenancy to an existing single-tenant app later?
Yes, but it is one of the most expensive retrofits in software. Every table, query, cache key, background job and permission check has to learn about tenants while the product is live. If you expect to sell to more than one company, design the tenant model in from the first sprint.
Do I need SSO for a B2B SaaS MVP?
Rarely. Early customers are usually happy with email or social login plus organization invites. SSO through SAML or OIDC becomes important when you sell to larger companies with IT departments, and a managed auth provider that supports organizations lets you add it without rebuilding your user model.