No. 39SaaS8 min read2,222 words
Multi-tenant architecture without headaches: Postgres RLS
Multi-tenant architecture for SaaS engineers: choosing an isolation model, enforcing tenant boundaries with Postgres RLS, pooling, Next.js 16 and common leaks.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways ยท 05
The short version
- 01Default to a shared schema with a tenant_id on every tenant-owned table, and let Postgres row-level security enforce the boundary instead of relying on every query having the right WHERE clause.
- 02Use FORCE ROW LEVEL SECURITY and connect the app as a role without BYPASSRLS, otherwise the table owner and superusers silently skip your policies.
- 03Set the tenant with set_config('app.tenant_id', id, true) inside a transaction so the value is discarded on commit and never leaks to the next request on a pooled connection.
- 04Resolve the tenant once per request (in Next.js 16 that is proxy.ts), pass it upstream as a request header, and re-verify membership on the server before any data access.
- 05Most real cross-tenant leaks happen outside the request path: background jobs, cache keys, search indexes, file storage paths and admin tools.
On this page ยท 08
The architecture that keeps multi-tenant SaaS simple is a shared Postgres schema with a tenant_id on every tenant-owned table, row-level security policies that enforce the boundary inside the database, and a tenant that is resolved once per request and scoped to a single transaction. With that in place, a missing WHERE tenant_id = ? returns nothing instead of another customer's invoices. Most multi-tenant horror stories start with exactly that one forgotten filter.
This post is the engineering deep dive behind our founder-level guide to building a multi-tenant SaaS, and if you want the concept first, start with what multi-tenancy is. Real Postgres and TypeScript, updated for Next.js 16, with the edge cases that usually only show up in an incident review.
Pick an isolation model, then live with it
There are three common ways to separate tenants. Pick based on compliance requirements, customer size and team capacity, not on what sounds impressive. Microsoft's multitenant architecture guide lays out the same spectrum in more depth.
| Shared schema | Schema per tenant | Database per tenant | |
|---|---|---|---|
| Isolation | Logical, enforced by RLS | Namespace per tenant | Physical |
| Migrations | Run once | Run once per schema | Run once per database |
| Tenant onboarding | Insert a row | Create a schema and tables | Provision a database |
| Cross-tenant analytics | Simple queries | Union across schemas | A separate pipeline |
| Connection pooling | Straightforward | Needs search_path handling | One pool per database, or a router |
| Typical fit | Most B2B SaaS | Tens to low hundreds of large accounts | Regulated or contractually isolated customers |
Shared schema, shared tables
Every row carries a tenant_id. One database, one schema, all tenants together. This is the default for good reasons: it is cheap, it serves thousands of tenants on one well-sized database, and migrations run once. The risk is that isolation depends on every query being right, which is exactly what row-level security fixes.
Schema per tenant
One Postgres schema per tenant inside the same database. You get cleaner separation and the ability to restore a single tenant, but operational cost climbs fast. Migrations must run across every schema and must be resumable when one fails halfway. Pooling gets awkward because each request has to set search_path, and the Postgres catalog grows with every table in every schema.
Database per tenant
Full physical isolation, with its own backups, encryption keys and sometimes its own region. It is the right answer for a handful of large or regulated customers who require it in a contract. It is the most expensive model to operate and the slowest to onboard. Do not reach for it until a customer is paying enough to justify the operations burden.
For the large majority of B2B SaaS, shared schema plus row-level security is the right starting point, and it is one more reason we reach for Postgres first. You can promote a noisy or sensitive tenant to its own database later, because every row already says who it belongs to.
Make the database enforce tenant boundaries
The best thing you can do is stop trusting application code to remember the filter. Row-level security lets Postgres apply a policy to every read and write on a table, regardless of which code path issued the query.
-- Every tenant-scoped table carries the column.
create table invoices (
id uuid primary key default gen_random_uuid(),
tenant_id uuid not null references tenants(id),
amount_cents integer not null,
status text not null default 'draft',
created_at timestamptz not null default now()
);
-- Lead composite indexes with tenant_id, because every query filters on it.
create index invoices_tenant_created_idx on invoices (tenant_id, created_at desc);
-- Turn RLS on and force it even for the table owner.
alter table invoices enable row level security;
alter table invoices force row level security;
-- Reads and writes must match the tenant set for this transaction.
-- current_setting(..., true) returns NULL or '' instead of erroring when unset,
-- and nullif turns '' into NULL, so an unset tenant matches no rows.
create policy tenant_isolation on invoices
using (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid)
with check (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);What each piece does, per the CREATE POLICY reference:
usingfilters which existing rows a query can see, update or delete.with checkrejects inserts and updates that would write a row into another tenant.force row level securityapplies the policy to the table owner too. Without it, the owner bypasses RLS, and your migration user or app user is often the owner.- Roles matter. Superusers and roles with
BYPASSRLSalways skip policies. Your application must connect as a dedicated role that has neither.
The nullif(current_setting(..., true), '') pattern is there because of a subtle behaviour: once a custom setting has been used in a session, reading it after the transaction ends returns an empty string rather than raising an error. Casting an empty string to uuid would throw; converting it to NULL makes the policy match nothing. Fail closed, quietly.
Set the tenant per transaction, not per session
Your application sets the variable at the start of each unit of work, inside the same transaction:
import { Pool, type PoolClient } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export async function withTenant<T>(
tenantId: string,
work: (client: PoolClient) => Promise<T>,
): Promise<T> {
const client = await pool.connect();
try {
await client.query("begin");
// is_local = true scopes the value to this transaction, so it is
// discarded on commit or rollback and never reaches the next request
// that reuses this pooled connection.
await client.query("select set_config('app.tenant_id', $1, true)", [
tenantId,
]);
const result = await work(client);
await client.query("commit");
return result;
} catch (err) {
await client.query("rollback");
throw err;
} finally {
client.release();
}
}The true argument to set_config is the detail that bites people. Pools reuse connections across requests. A session-level setting would carry the previous tenant into the next request on that connection. A transaction-scoped setting cleans itself up. This also makes the pattern safe behind PgBouncer in transaction pooling mode, where session state cannot be relied on at all.
Now even if someone writes select * from invoices with no filter, Postgres returns only the current tenant's rows. The boundary has moved from code review into the engine.
Keep RLS fast
A simple equality policy on an indexed column adds very little cost: the planner treats it like an extra WHERE clause. Problems appear when policies get clever. Rules of thumb:
- Keep the policy an equality check on
tenant_id. Do membership checks in the application before you open the transaction, not in a per-row subquery. - Make
tenant_idthe first column of composite indexes on large tables. - Use
explain analyzewith the tenant set to confirm the index is used. Test with your largest tenant's data volume, not your seed data. - Partition truly huge tables by tenant or time only when measurements say you need it. Declarative partitioning works with RLS but adds operational weight.
Resolve the tenant once, at the edge
Decide how a request maps to a tenant, and do it in exactly one place. The common options:
- Subdomain:
acme.yourapp.com. Branded, and the natural path to custom domains later. Needs wildcard DNS and certificates. - Path prefix:
yourapp.com/t/acme. Simplest to ship. - Token claim: the tenant ID rides inside the session or API token. Best for APIs and mobile clients.
In Next.js 16, Middleware has been renamed to Proxy: the file is proxy.ts and the exported function is proxy. It is the natural place to resolve a subdomain before any route runs. One correction to a pattern we see copied around a lot: to pass a value to your route handlers and Server Components, set it on the request headers with NextResponse.next({ request: { headers } }). Setting it on the response only sends it back to the browser.
// proxy.ts (Next.js 16; this file was middleware.ts in earlier versions)
import { NextResponse, type NextRequest } from "next/server";
const ROOT_DOMAIN = process.env.ROOT_DOMAIN ?? "yourapp.com";
const RESERVED = new Set(["www", "app", "api", "admin"]);
export function proxy(request: NextRequest) {
const hostname = (request.headers.get("host") ?? "").split(":")[0];
const suffix = `.${ROOT_DOMAIN}`;
const sub = hostname.endsWith(suffix)
? hostname.slice(0, -suffix.length)
: null;
const headers = new Headers(request.headers);
// Never trust a tenant header sent by the client.
headers.delete("x-tenant-slug");
if (sub && !RESERVED.has(sub)) {
headers.set("x-tenant-slug", sub);
}
// Forward the header upstream to route handlers and Server Components.
return NextResponse.next({ request: { headers } });
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};A Server Component or route handler then reads it with (await headers()).get("x-tenant-slug"), looks up the tenant, checks that the signed-in user is a member, and only then calls withTenant. The Next.js docs are explicit that Proxy is for optimistic checks, not full authorization, so the membership check belongs on the server, next to the data.
The discipline that matters: route handlers never parse the host themselves. One place resolves the tenant, one place verifies membership, one place opens the transaction. Three things to audit, not three hundred.
The leaks nobody warns you about
The request path is the part everyone protects. These are the paths that cause real incidents. The OWASP multi-tenant security cheat sheet is a good companion list.
| Leak path | How it goes wrong | The fix |
|---|---|---|
| Background jobs | The worker runs outside any request, so no tenant is set, and someone "fixes" it with an admin role | Put tenantId in every job payload and run the job through withTenant |
| Cache keys | settings cached for tenant A is served to tenant B | Prefix every key: tenant:ID:settings |
| Search indexes | The index holds documents from all tenants and a query forgets the filter | Store tenant_id in every document and filter on it in a single search helper |
| File storage | Predictable object paths or long-lived public URLs | Prefix paths with the tenant, serve through short-lived signed URLs after a permission check |
| Admin tools | RLS disabled on the main app role to make support easier | A separate role with BYPASSRLS, used only by internal tools, with every access logged |
| Exports and emails | A report job assembles data with the wrong context | Generate exports inside the tenant transaction and test them like any other endpoint |
Caching across tenants
Any cache key that omits the tenant ID is a data leak waiting to happen. That applies to Redis, to in-memory memoization and to framework-level caches. Our practical guide to Redis caching covers key design in more depth.
The noisy neighbor
One tenant running a huge export can starve everyone else on a shared database. Microsoft documents this as the noisy neighbor antipattern. Per-tenant rate limits on expensive endpoints, a separate connection pool for heavy background work, and query timeouts go a long way. When one tenant genuinely outgrows the shared database, promote it to a dedicated one. The architecture above already supports that.
Test isolation like a feature
Isolation is a property you can test, so test it:
- Seed two tenants with overlapping data in your test database.
- For every API route and server action, authenticate as tenant A and request tenant B's resource IDs. Expect a not-found response, not a forbidden one, so you do not confirm the record exists.
- Run a database-level test that opens a transaction without setting a tenant and asserts that tenant tables return zero rows.
- Check that the app role cannot bypass RLS by querying
pg_rolesforrolbypassrlsin CI. - Run the suite on every pull request. A new table without a policy should fail the build.
That last point is worth automating directly: a query against pg_class and pg_policies that lists any table with a tenant_id column but no forced policy catches the most common regression, which is a new table someone forgot to protect.
When to move a tenant out of the shared database
Promote a tenant when there is a concrete reason: a contract that requires dedicated infrastructure or a specific region, a data volume that dominates the shared database, or a regulatory requirement such as a dedicated encryption key. The move itself is mechanical when every row carries tenant_id: copy that tenant's rows to the new database, route their requests to it, and delete them from the shared one. It is the same code, pointed at a different connection.
The short version
Start with a shared schema and a tenant_id on every tenant-owned table. Let Postgres row-level security enforce the boundary with forced policies and a role that cannot bypass them. Resolve the tenant once, verify membership on the server, and scope it to the transaction with set_config(..., true). Then give background jobs, caches, search, files and admin tools the same discipline as your request path. Do that, and multi-tenancy becomes boring, which is exactly what you want from your data layer.
If you are designing a multi-tenant platform, or inherited one where isolation lives in "everyone remembers the filter," our SaaS development and PostgreSQL development teams do exactly this kind of work. Tell us what you are building and we will review the data model with you.
FAQ ยท 05 questions
Frequently asked questions
What is the best multi-tenant architecture for a SaaS?
For most B2B SaaS products, a shared database and shared schema with a tenant_id column on every tenant-owned table is the best default. It is cheapest to run, migrations run once, and Postgres row-level security can enforce isolation inside the database. Move to schema-per-tenant or database-per-tenant only for specific customers whose contracts or regulators require it.
Is Postgres row-level security fast enough for multi-tenant SaaS?
Yes, for a simple equality policy on an indexed tenant_id column the overhead is small, because Postgres adds the policy condition to the query plan like an extra WHERE clause. Keep policies simple, index tenant_id (usually as the first column of composite indexes), and avoid policies that call slow functions or run subqueries for every row.
Does row-level security work with connection pooling like PgBouncer?
Yes, as long as you set the tenant inside a transaction with a transaction-local setting. In transaction pooling mode a connection is handed to a different client after each transaction, so session-level SET commands are unsafe. A transaction-scoped set_config call is discarded on commit or rollback and travels with the transaction.
Should I use a subdomain or a path for each tenant?
Subdomains such as acme.yourapp.com feel more branded and make custom domains easier later, but need wildcard DNS and certificates. Path prefixes are the simplest to ship. Either way, treat the URL only as a hint: the server must still confirm that the logged-in user is a member of that tenant.
How do I let support staff see data across all tenants safely?
Use a separate database role for internal tools that is granted BYPASSRLS or has explicit cross-tenant policies, and never use it in the customer-facing application. Log every cross-tenant read with who did it and why, so the access is auditable.