Engineering

Multi-tenant SaaS: the architecture decisions that matter

Isolation models, tenant resolution, scoping below the application, per-tenant roles and SSO, metering, and how to test that tenants cannot see each other.

By Udeels Engineering · · 7 min read

Most of the work in a multi-tenant SaaS product is ordinary application work. A small number of decisions, made early, determine whether the product stays safe and cheap to run as the customer count grows. Get them wrong and the fix is a migration across every customer's data. This article covers the decisions we make on day one of a multi-tenant build and the reasoning behind each.

Choosing an isolation model

There are three common ways to separate tenant data. All three are in production use at serious companies; the right one depends on your customers, not on fashion.

Shared schema, tenant_id columnSchema per tenantDatabase per tenant
IsolationLogical; relies on every query being scopedNamespace per tenant in one databasePhysical; separate database or cluster
Cost per tenantLowestLow to mediumHighest
Onboarding a tenantInsert a rowCreate schema, run migrationsProvision database, run migrations
MigrationsOnceOnce per tenantOnce per tenant, across servers
Cross-tenant reportingSimpleHarderNeeds a separate pipeline
Noisy-neighbour riskHighestMediumLowest
FitsMany small and mid-size tenantsTens to low hundreds of tenantsFew large or regulated tenants, data residency

Our default is a shared schema with a tenant identifier on every tenant-owned row, enforced by the database (more on that below). We add a database-per-tenant option when a customer contract requires physical separation or a specific region. Designing for the shared model with a clean tenant boundary makes it straightforward to move a single large tenant to its own database later; going the other way is much harder.

Resolving the tenant on every request

Every request has to answer "which tenant is this?" before it touches data. The usual sources are a subdomain (acme.example.com), a custom domain mapped to a tenant, a path prefix, or a claim in the user's token. We resolve the tenant once, at the edge of the application, and carry it in the request context. Everything downstream reads it from there.

Two rules keep this safe. First, the tenant comes from something the server trusts: a verified token claim or a domain mapping, never a header or body field the client can set freely. Second, the user's membership in that tenant is checked on every request. A valid token for tenant A presented at tenant B's subdomain must fail, not fall back to tenant A's data.

Enforcing tenant scope below the application layer

The most common multi-tenant bug is a query that forgets the tenant filter: a new report, an admin search, a background export. Code review catches some of these. The database catches all of them if you let it.

With PostgreSQL we use row-level security. The application sets the current tenant on the connection at the start of each transaction, and a policy on each tenant-owned table restricts every read and write to rows for that tenant. A query that forgets its WHERE clause returns only the current tenant's rows instead of everyone's.

-- Every tenant-owned table carries tenant_id.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

-- Per request, inside the transaction:
BEGIN;
SET LOCAL app.tenant_id = '6f1c2e0a-7d0b-4b8e-9a51-2f3c9d4e8a10';
SELECT id, total FROM invoices WHERE status = 'open';  -- scoped by the policy
COMMIT;

A few details matter. FORCE ROW LEVEL SECURITY applies the policy to the table owner too. The application connects as a role without BYPASSRLS. SET LOCAL scopes the setting to the transaction, so a pooled connection cannot carry one tenant's setting into the next request. If current_setting is missing, the cast fails and the query errors rather than returning data, which is the failure you want.

Roles, permissions and SSO per tenant

RBAC with per-tenant roles

A user's role belongs to a membership, not to the user. The same person can be an admin in one tenant and a viewer in another, which is common when consultants or agencies use your product. We model this as user, tenant, membership (with role), and check permissions against the membership resolved for the current request.

Most products need a fixed set of platform roles (owner, admin, member) and, later, tenant-defined custom roles. We store permissions as named actions on resources ("invoice.approve", "user.invite") so that custom roles are a list of grants rather than new code paths. Field-level rules, such as hiding salary fields from non-HR roles, are enforced in the API response, not in the UI.

SSO per tenant

Business customers will ask to sign in with their own identity provider over SAML or OpenID Connect. Each tenant gets its own identity provider configuration, a verified email domain, and a rule for what happens to users who sign in through it: auto-provision with a default role, or require an invite. Map the identity provider's subject and issuer to your user, not just the email address, and decide early whether SSO is mandatory for a tenant once it is turned on. SCIM provisioning usually follows a few months later.

Per-tenant configuration and billing

Tenants will differ: branding, enabled features, limits, notification settings, integration credentials. We keep this in a typed tenant configuration with defaults at the plan level and overrides at the tenant level, rather than scattered flags. Integration credentials (API keys for a tenant's CRM, for example) are encrypted per tenant and never returned to the browser.

Billing needs metering you can trust. Record usage events (seats, API calls, documents processed, LLM tokens) with the tenant identifier at the point where the work happens, aggregate them per billing period, and reconcile against your payment provider. Plan limits should be checked on the server at the same point, so a tenant on a lower plan cannot exceed limits by calling the API directly.

Where tenants leak: jobs, caches and files

Cross-tenant leaks rarely come from the main request path, which is usually well tested. They come from the places that run outside a request:

  • Background jobs that are enqueued without a tenant identifier, then run with no tenant context or with a default one. Every job payload carries the tenant, and the worker sets the same database context as a request before doing anything.
  • Caches keyed without the tenant. A Redis key like "dashboard:summary" is shared by every tenant; it needs to be "t:<tenant>:dashboard:summary". The same applies to CDN caching of authenticated responses.
  • File storage paths that are guessable or not scoped. Store files under a tenant prefix and serve them through short-lived signed URLs after a permission check.
  • Search indexes and analytics exports that copy data out of the database without the tenant filter, where row-level security no longer applies.
  • Webhooks from third parties that are matched to the wrong tenant because the lookup uses a shared identifier.

Testing cross-tenant isolation

Isolation is a property you test continuously, not once. Our test suites for multi-tenant products include a cross-tenant set that runs on every change: create two tenants with overlapping data, sign in as each role in tenant A, and attempt every read and write against tenant B's records by ID, by search, by export and through background jobs. Every attempt must fail with a not-found or forbidden response, and the database must show no writes. We also run the main API tests with row-level security policies in place, so a missing policy on a new table fails the build.

For products with tenant-defined roles, we add tests that generate custom roles with narrow grants and check that each endpoint honours them. These catch the endpoint that checks "is admin" instead of the specific permission.

Working with us

Our Multi-tenant SaaS Development work covers the decisions above: isolation model, tenant resolution, database-level scoping, RBAC and per-tenant SSO, configuration, billing and the cross-tenant test suite, along with the admin consoles and onboarding flows that sit on top. If you are planning a new SaaS product or untangling an existing single-tenant one, we are happy to review the design with you.

Have a project like this?

Send us your requirements. Within a day, we come back with a working backend you can click through.

Multi-tenant SaaS: the architecture decisions that matter | Udeels