Skip to content

SaaS

Designing Tenant Isolation in a SaaS Database

How to keep each customer's data separate in a multi-tenant SaaS: silo, pool and bridge models, PostgreSQL row-level security done safely, connection pooling pitfalls, noisy neighbors, backups and testing isolation.

VisionColab TeamSoftware engineering & AI 6 min read
SaaS tenant isolation – a database split into separate tenant partitions

In shortThere are three ways to separate tenants in a SaaS database: a database per tenant (silo), shared tables with a tenant_id column (pool), or a mix of both (bridge). Most SaaS products start with the pool model and enforce isolation inside the database with PostgreSQL row-level security (RLS), so a missing WHERE clause cannot leak data. The common failures are not in the policy itself but around it: roles that bypass RLS, tenant context leaking through connection pools, and no automated tests proving isolation works.

A data leak between customers is the most damaging bug a SaaS company can ship. It breaks contracts, triggers breach notifications and destroys trust. Isolation deserves a deliberate design, not a convention developers are asked to remember.

Silo, pool and bridge

AWS’s SaaS Lens uses three names that have become standard:

Silo (database per tenant)Bridge (schema per tenant)Pool (shared tables)
Isolation strengthStrongestStrongDepends on enforcement
Cost per tenantHighestMediumLowest
Schema migrationsRun on every databaseRun on every schemaRun once
Per-tenant backup and restoreEasyPossibleHard
Noisy neighbor riskNoneSomeHighest
Practical tenant countTens to hundredsHundreds to low thousandsUnlimited
Best forEnterprise, regulated or data-residency customersModerate numbers of mid-size tenantsSelf-serve products with many small tenants

Many products end up with a tiered design: most customers in the pool, and large or regulated customers on a dedicated database for an extra fee. Build the tenant-resolution layer so a tenant can be routed to either.

The pool model with row-level security

In the pool model every tenant-owned table carries a tenant_id. Relying on application code to add WHERE tenant_id = ? to every query works until one query forgets. PostgreSQL row-level security moves that rule into the database, so it applies to every query automatically.

-- 1. Every tenant table has a tenant_id
CREATE TABLE invoices (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id  uuid   NOT NULL REFERENCES tenants(id),
  amount     numeric(12,2) NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX ON invoices (tenant_id, created_at);

-- 2. Turn on RLS, and apply it to the table owner too
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

-- 3. One policy for reads and writes
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);

The USING clause filters which rows a query can see, update or delete. The WITH CHECK clause stops anyone inserting or moving a row into another tenant. If RLS is enabled and no policy matches, PostgreSQL denies access by default, which is the safe failure mode.

The five pitfalls that break RLS in practice

1. Roles that bypass RLS

Superusers and roles with the BYPASSRLS attribute ignore every policy, and table owners do too unless you set FORCE ROW LEVEL SECURITY. Many teams connect their application as the same role that owns the tables and runs migrations, which silently disables isolation. Use separate roles: a migration role that owns the schema, and an application role with only the permissions it needs and no bypass.

2. Tenant context leaking through connection pools

Pooled connections are reused across requests. If you set the tenant with a session-level SET, the next request on that connection can inherit the previous tenant. Set it per transaction instead, so it is cleared automatically at commit or rollback:

BEGIN;
SELECT set_config('app.tenant_id', $1, true);  -- true = local to this transaction
-- ... queries for this request ...
COMMIT;

This also works with poolers running in transaction mode. Wrap it in one middleware function so no endpoint can skip it.

3. Trusting the client for the tenant ID

Derive the tenant from the authenticated session or a verified token claim on the server, never from a request header or URL parameter the user can change. Then check the user is actually a member of that tenant.

4. Background jobs and admin tools

Workers, scheduled jobs, analytics exports and support dashboards often run with powerful roles. Each job should set the tenant context for the tenant it is processing. Cross-tenant admin access should use a separate, audited role and never sit in normal request paths.

5. Everything outside the database

RLS only protects the database. Caches, search indexes, file storage, vector stores and log files need tenant scoping too: prefix cache keys with the tenant ID, store files under tenant-specific paths with access checks, and filter search and vector queries by tenant. Leaks through these side channels are common because nobody thought to protect them.

Performance

  • Put tenant_id first in composite indexes so the planner can use the policy filter efficiently.
  • Keep policies simple. A policy that joins several tables runs on every row and can slow queries noticeably.
  • Check query plans with realistic data volumes from several tenants of different sizes.
  • For very large tenants, consider partitioning tables by tenant or moving them to a silo.

Noisy neighbors

In a shared database, one tenant running a huge export can slow down everyone else. Defenses include statement timeouts for the application role, per-tenant rate limits in the API, running heavy reports on a read replica, and queueing bulk jobs. Track resource usage per tenant so you can see who is driving load and price plans accordingly.

Backups, deletion and data residency

  • Restoring one tenant from a shared database backup is difficult. Plan a per-tenant export and import process before a customer asks.
  • Deleting a tenant must remove data from every table and every side store. Keep a registry of tenant-owned tables so deletion is complete.
  • Data residency requirements (for example, EU customers’ data stored in the EU) usually mean regional deployments or silos for those customers.

Prove isolation with tests

Isolation should be verified automatically on every change:

  1. A test that lists every table with a tenant_id column and fails if any of them lacks RLS or a policy.
  2. Tests that create two tenants, log in as one, and confirm every API endpoint returns nothing from the other.
  3. Tests that try to insert or update rows with another tenant’s ID and expect failure.
  4. A check that the application’s database role does not have BYPASSRLS and does not own tenant tables.

Frequently asked questions

Is row-level security enough on its own?

It is a strong safety net, not a replacement for authorization in the application. Use both: the application checks what a user may do, and RLS guarantees they can never see another tenant’s rows even if the application has a bug.

Should we start with database-per-tenant to be safe?

Only if your first customers require it. Silos multiply operations work, migrations and cost. A well-tested pool model with RLS, plus the option to move a large customer into a silo later, suits most new SaaS products.

Does RLS work with ORMs?

Yes. The ORM sends ordinary queries and the database applies the policy. You only need to set the tenant context at the start of each transaction.

What about MySQL or other databases?

Not every database offers native row-level security. Without it, enforce tenant filtering in a single data-access layer that every query must pass through, and back it with the same automated isolation tests.

Building a SaaS product?

VisionColab designs and builds multi-tenant SaaS platforms with isolation, billing and scalability planned from day one. See our SaaS development services or book a free consultation.

Written by the VisionColab team

VisionColab designs and builds AI, web, mobile and cloud software for businesses. Our guides explain the decisions, costs and trade-offs involved in planning a software project.

Have a project in mind?

Share your goals and constraints. We will suggest a realistic scope and the right technology approach.