I have built multi-tenant SaaS the way most teams build it first: a tenant_id column, a where clause in every query, and a quiet prayer that nobody forgets one. The Healthcare Ireland platform I worked on made the stakes concrete - Org, Branch and Department isolation across a healthcare system, with Socket.io rooms, Prisma tenant middleware, and a BullMQ document pipeline on top. One missing filter there is not a bug report. It is a patient's data on another organisation's screen. The setup that held up, across that platform and the ComplianceBot and recruitment systems after it, is shared tables with Postgres row-level security doing the enforcing. This post is that setup, the traps that break it, and the exact point where you leave it.
The short answer: shared tables, RLS, and a hybrid escape hatch
Start with the verdict, because the rest of this post is the evidence for it. For most B2B SaaS, put every tenant in the same tables, give every tenant-owned table a tenant_id column, and enforce the boundary with Postgres row-level security. Run one schema, one migration, one connection pool. Take the tenant from a verified JWT, set it per transaction, and let the database refuse any row that does not belong to it. When a customer contract demands residency, a dedicated database, or a hard isolation guarantee, move that one customer up to a silo and keep everyone else in the pool. The hybrid model is the escape hatch, not the default.
The three models, and what each one charges you
Every multi-tenant architecture is one of three models, and the choice is a bill, not a belief. I have seen all three in production, and the honest way to compare them is to price the same work three times.
| Shared tables + RLS | Schema per tenant | Database per tenant | |
|---|---|---|---|
| Isolation | Logical, enforced by the database policy | Stronger, one namespace per tenant | Strongest, physically separate |
| Migrations per schema change | 1 | Once per tenant | Once per tenant |
| Connection pooling | One pool, everyone | One pool, fragmented by search_path | One pool per tenant, or reconnects |
| New tenant costs | One INSERT into tenants | DDL plus a full migration | Provision, migrate, back up |
| Per-tenant restore | Hard - rows, not a database | Schema-level, awkward | Straightforward |
| Cross-tenant leak risk | Near-zero with RLS, high without it | Low, a wrong search_path still crosses | Zero |
| Fits | Most B2B SaaS | Mid-market with stricter requirements | Enterprise, regulated, residency |
The shared model wins on every operational axis and loses on exactly one: the boundary is logical, so it depends on the policy being right. That is a real risk, and the rest of this post is about making the policy unbreakable rather than pretending the risk does not exist.
Schema-per-tenant looks like a clean middle ground until the tenant count grows. Every schema change is N jobs, one failed migration is schema drift, and past roughly 500 schemas the pg_catalog metadata bloat starts eating the buffer cache. For Prisma specifically the break comes earlier: one generated client per schema means the model breaks at roughly 200 to 300 tenants. A database per tenant is the strongest isolation and the worst migration story - backups, monitoring and pools all multiply by the customer count, and onboarding a customer becomes provisioning instead of an INSERT.
The tiered answer is the one I would defend to a founder: start most tenants on shared tables, and move a tenant up when they ask for exclusivity or their traffic starts impacting others. Build the tenant-resolution layer as an abstraction over the data source early enough that the application code does not change at all when a client moves. That is not a compromise. It is the only model where the default stays cheap and the exception stays possible.
RLS in five lines: the policy, the role, and the setting
Row-level security is a filter the database adds to every query, based on who is asking. The whole setup is five lines of SQL, and every line earns its place.
-- 1. Every tenant-owned table carries its owner
ALTER TABLE invoices ADD COLUMN tenant_id uuid NOT NULL;
-- 2. Turn policies on, and force them even for the table owner
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
-- 3. One policy, reads and writes, on the app role
CREATE POLICY tenant_isolation ON invoices
TO tenant_app
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
Three things in that policy deserve a second look, because each one is a bug I have seen shipped.
USING filters, WITH CHECK validates. USING decides which rows a query can see and modify. WITH CHECK decides which rows an insert or update may create. Without WITH CHECK, an insert with another tenant's id succeeds quietly. Both halves are required; a policy with only USING is half a boundary.
The role matters more than the policy. Superusers and roles with BYPASSRLS always bypass row security, and table owners normally do too. If your app connects as postgres, or as the user that ran the migrations, every policy you just wrote is silently ignored. The fix is two roles: a migration role that owns the tables, and an app role - NOSUPERUSER, NOBYPASSRLS, not the owner - with only SELECT, INSERT, UPDATE and DELETE grants. FORCE ROW LEVEL SECURITY makes the policy apply to the owner as well, which is the belt to the role's braces.
The tenant is set per transaction, never per connection. set_config('app.tenant_id', id, true) with the third argument true is transaction-local: it resets at commit or rollback. A plain SET stays on the connection and leaks into the next request that borrows it from the pool. With a connection pool, transaction-local is not a preference. It is the whole point.
-- Inside the transaction, before the first query:
SELECT set_config('app.tenant_id', '123e4567-e89b-12d3-a456-426614174000', true);
And the NULLIF guard in the policy is not decoration. After a SET and then a RESET in a session, current_setting(..., true) returns an empty string, not NULL, and ''::uuid throws. NULLIF turns that into a NULL that matches no rows instead of an error your users see. Two independent write-ups of this exact trap - one tested on Postgres 18.6, one on 18.7 - both hit the same error, which is how you know it bites real teams.
The traps that break RLS in production
The policy above is five lines. The production system around it is where the leaks live. These are the five I check for in review, in the order I would check them.
1. The app connects as the owner
This is the most common failure and the quietest. Migrations run as a role that owns the tables, the app reuses the same connection string for convenience, and RLS never applies to a single query. Nothing errors. Nothing logs. The policies exist and do nothing. The test that catches it is one line: query as the app role with no tenant set and confirm zero rows come back. If rows come back, your role is wrong, not your policy.
2. A session SET leaks across the pool
The tenant setting is connection state, and connections are shared. A plain SET app.tenant_id = ... on a pooled connection survives the request and hands the next borrower the previous tenant's rows. The fix is the transaction-local set from the section above, and the test is two requests on one pooled connection with different tenants. The second request must see only its own rows. If you use PgBouncer in transaction mode, the same rule applies - transaction-local settings are the ones that survive pooling correctly.
3. The tenant comes from a header the client controls
The tenant id must come from a verified source: the subdomain, which DNS routed before your app saw the request, or the JWT, which you signed. Never the request body, never a query param, never a raw header. A tenant header is a claim, not proof of access, and the middleware must check the caller's membership in that tenant before it trusts the value. I have seen a session cookie outlive a subdomain change after a tenant rename; the middleware that refuses the request instead of guessing is the middleware that earns its keep.
4. Views and foreign keys ignore the boundary
Two Postgres behaviours surprise teams that test only SELECT on base tables. First, a view runs with its owner's rights unless you set security_invoker = true (Postgres 15 and later), so a view over a protected table happily returns every tenant's rows to a caller who should see one tenant's. Second, foreign-key checks ignore RLS: with Comment.noteId -> Note.id alone, one tenant can reference another tenant's row. The fix for the second is composite foreign keys on (id, tenantId) between tenant tables.
And the write path has its own hole, one that was only just patched. CVE-2026-120154 let a role with INSERT, UPDATE and applicable SELECT privileges iteratively use INSERT ... ON CONFLICT DO UPDATE to read rows that row-level-security policies should hide. It was fixed in the November 12, 2026 releases - 18.7, 17.12, 16.16, 15.20 and 14.25, a 52-CVE security drop that also ended Postgres 14 support. The lesson is not "patch Postgres", though you should - 18.7 is the current stable minor and 19.0 went generally available on November 19. The lesson is that a passing SELECT isolation test is insufficient: the write path and conflict handling need tenant-negative tests too. If your test suite only asserts that tenant A cannot SELECT tenant B's rows, you have tested the easy half.
5. The cache and the queue do not know about tenants
The database is not the only layer that can leak. I have read the post-mortem shape of this one more than once: the cache key in front of a query did not include the tenant, and for about fifteen minutes one customer's dashboard rendered snippets from another customer's data. The code looked correct, the query had a where clause, the user was authenticated, the role was right - and the cache key did not know about tenants.
The same hole lives in background jobs. Cron tasks, BullMQ workers, anything outside an HTTP request has no request-scoped context, so a tenant service that reads from the request blows up - or worse, silently runs with no tenant at all. The fix is explicit: the tenant id travels in the job payload, and the worker wraps the run in a runWithTenant(tenantId, ...) call that sets the context before the first query. The BullMQ post on this site builds the retry and dead-letter side of that story; the tenant id in the payload is the multi-tenancy half. Search the codebase for cache keys and job payloads missing a tenant before launch, not after the first incident.
The NestJS wiring: resolve once, carry everywhere
The NestJS shape that held up for me has three pieces, and the order matters: resolve the tenant once at the edge, carry it with AsyncLocalStorage, and enforce it below the call sites.
Resolve once, at the edge. Middleware runs first, so by the time guards, interceptors or controllers touch the request, the tenant context is already there. The middleware reads the subdomain or the verified JWT, checks membership, and refuses the request on mismatch. Refusing is cheap. Guessing is the bug.
Carry it with AsyncLocalStorage. The middleware sets the tenant, and AsyncLocalStorage threads it through repositories, listeners, queue workers and scheduled jobs - everywhere req no longer reaches. Request-scoped providers do this too, technically, but they tear down the DI graph per request, and the overhead is measurable once you are past a few thousand requests per second. ALS is close to free, and the deliberate choice is to throw when the store is missing: returning null and trusting downstream code to handle it is how you end up with cross-tenant queries. Fail closed, not open.
import { AsyncLocalStorage } from "node:async_hooks";
export const tenantContext = new AsyncLocalStorage<{ tenantId: string }>();
export function getTenantId(): string {
const store = tenantContext.getStore();
if (!store) throw new Error("No tenant in context - refusing to query");
return store.tenantId;
}
Enforce it below the call sites. Prisma's schema language has no syntax for policies, so the RLS SQL lives in a migration - create an empty one with prisma migrate dev --create-only and write the SQL yourself. Then a Prisma Client Extension applies the tenant filter to every model that has a tenantId, reading the active tenant from the AsyncLocalStorage context. The old $use middleware hook is deprecated; new code uses $extends with a typed query component scoped per model and operation. Because the rewrite happens inside the client, a developer who calls findMany() with no where still gets a tenant-scoped query. That is the application layer doing its job. RLS underneath is the second, independent boundary for the raw query, the bug in the merge logic, and the reporting script - the paths the extension cannot see.
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient().$extends({
query: {
$allModels: {
async $allOperations({ model, operation, args, query }) {
const tenantId = getTenantId();
// Models without tenantId (the tenants table itself) pass through.
const scoped = (args as { where?: object }).where
? { ...args, where: { ...(args as { where: object }).where, tenantId } }
: { ...args, where: { tenantId } };
return query(scoped);
},
},
},
});
Two honesty notes on that snippet. First, it is simplified: a production extension scopes per model, skips the tenants table and any genuinely global tables, and handles nested writes and updateMany explicitly - the merge logic is the part you test hardest. Second, if you would rather not own the extension, the ecosystem has caught up: @nestarc/tenancy (0.16.4, November 2026) carries the authorised tenant id through AsyncLocalStorage and sets the Postgres transaction-local context for Prisma, with an RLS-first design and a check/doctor command that verifies roles and policies at startup. I have not run it in production, so I am naming it as an option, not a recommendation - but the shape it encodes is exactly the shape above.
One version note before you copy the stack: Prisma 7.10.1 is the stable line as of this week. Prisma 8 is still a release candidate with no general-availability date announced - npm install prisma already installs the RC, so pin your version deliberately. The code above is written against Prisma 7, NestJS 11 and Postgres 18.7, the combination that was verified end to end in October and November 2026.
When to leave the shared pool
The shared model is the default, not a religion. Three triggers move a tenant up, and each one has a receipt you can point at.
A contract says so. Data residency, a dedicated database, a custom backup retention window, a hard isolation guarantee in an enterprise agreement. As a rule of thumb, this is the high-ACV enterprise tier - one practitioner guide puts the line at roughly $25,000 a year - and the figure is a judgment call, not a measurement. The point is the direction: the customer paying for a silo is the customer whose contract names one.
A noisy neighbour. One tenant does 10x the volume of everyone else and the shared pool feels it. Before you move them, check the cheaper fixes: per-tenant rate limits, a separate read replica for reporting, statement timeouts per tenant. A silo is the last resort for a performance problem, not the first.
A per-tenant restore you cannot do from rows. If a customer can demand their data back as a database, or a restore that must not touch anyone else, rows in a shared table make that a project instead of a command. This is the one trigger that is genuinely hard to retrofit, so name it in the design doc before launch even if no customer needs it yet.
None of these triggers is a reason to start on silos. Starting on silos means paying the migration, backup and pooling bill for every customer from day one, including the ones who will never ask. Start shared, keep the resolution layer abstract, and move tenants up one at a time with the contract or the measurement as the receipt.
The launch checklist, as six checks
Everything above compresses into six checks. Run them on your real app, in order, before the first paying tenant lands.
- RLS is enabled AND forced on every tenant-owned table. ENABLE plus FORCE, in the same migration as the table. A table added next month needs the same two lines.
- The app connects as a non-owner role. No SUPERUSER, no BYPASSRLS, not the owner. Query as the app role with no tenant set: zero rows, or the role is wrong.
-
The tenant is set per transaction.
set_config(..., true), never a plain SET. Two requests on one pooled connection, different tenants, each seeing only its own rows. -
Every policy uses the NULLIF guard.
NULLIF(current_setting('app.tenant_id', true), '')::uuid- the empty-string trap is the error your users see if you skip it. - Tenant-negative tests cover the write path. Not just SELECT: updates, deletes, inserts into another tenant, ON CONFLICT probes, cross-tenant foreign keys. CVE-2026-120154 is the reason this item exists.
- Cache keys and job payloads carry the tenant. A cache key without a tenant is a leak with a TTL. A BullMQ job without a tenant in the payload is a worker running blind.
My verdict
Build on shared tables with Postgres RLS, a Prisma client extension on top, and the tenant resolved once from a verified JWT and carried in AsyncLocalStorage. That is the setup I would defend for any B2B SaaS whose customers are roughly the same shape: one schema, one migration, one pool, and a database that refuses foreign rows even when the application is wrong.
The conditions that would flip it: a customer contract that names residency or a dedicated database - then that customer gets a silo and nobody else does. A tenant whose traffic starves the pool - then rate-limit and isolate that tenant first, and move them only if the measurements say so. A restore requirement that needs a whole database per customer - then the silo model from the start, with automated provisioning, because hand-run silos are a schema-drift incident waiting for its first schema change.
What I would not do, in any of those cases, is the thing I did on my first multi-tenant build: trust the where clause. A where clause is a request. A policy is a contract. The difference between them is the afternoon your support team spends explaining to a healthcare organisation why another organisation's data was on their screen.
Not sure which model fits your SaaS? Answer four questions and I will place you:
If you are building a multi-tenant SaaS and want the isolation layer, the tenant resolution, and the launch checks built as one system instead of bolted on one feature at a time, that is the layer I build for teams. Tell me about your project and I will tell you honestly whether you need shared tables, a hybrid tier, or nothing at all.
Related reading: BullMQ in NestJS: Retries, Idempotency and Dead-Letter Queues for the job layer this post's tenant payload rides on, Scaling Socket.io Rooms in NestJS With the Redis Adapter for the real-time rooms the Healthcare Ireland platform runs on, and Zod as a Contract, Not a Comment for the schema-first discipline the same systems use at every boundary. My case studies live at Healthcare Ireland and ComplianceBot AI.
FAQ
Is shared-schema multi-tenancy safe enough for paying customers?
Yes, when the isolation is enforced in two independent layers: a Prisma client extension that scopes every query to the tenant, and Postgres row-level security that refuses foreign rows even when the application layer is wrong. One layer alone is a convention; two layers is a guarantee. Add tenant-negative tests on the write path and you have the setup I would defend to a customer.
Does RLS slow down queries?
The policy is applied by the query planner, not as a post-filter, so rows from other tenants are never read from disk. The cost is the predicate itself, which a composite index leading with tenant_id keeps cheap. What does cost you is a missing index: without one, the policy turns a tenant-scoped lookup into a sequential scan, so every tenant-owned table needs that index.
Should I use Prisma Client Extensions or rely on RLS alone?
Use both. The extension makes the common path correct and ergonomic: a developer calling findMany with no where clause still gets a tenant-scoped query. RLS is the backstop for the paths the extension cannot see: raw queries, a bug in the merge logic, a reporting script. The extension is convenience; RLS is the guarantee. Neither replaces the other.
What happens when one tenant outgrows the shared pool?
You move that one tenant up a tier. Build the tenant-resolution layer as an abstraction over the data source from day one, so the application code does not change when a tenant moves from shared tables to a schema or a dedicated database. The trigger is a contract (residency, isolation guarantee) or a measured problem (one tenant's traffic starving the rest), never a feeling.
How do I migrate from schema-per-tenant to shared tables?
It is a data migration, not a rewrite: add tenant_id to every table, backfill it from the schema name, enable RLS with the policy, then cut reads over behind a flag and verify with tenant-negative tests before you drop the old schemas. The hard part is the same as any migration - proving the new path returns exactly the old rows - so keep both paths live until the tests pass on production data.
Does Supabase change any of this?
No - it leans on it. Supabase's data API relies on RLS for authorization, which is why ComplianceBot runs its tenant boundary there. The same rules apply: a non-owner app role, the tenant set per transaction from a verified JWT, policies with USING and WITH CHECK, and tests that try to read across tenants. Supabase removes the hosting, not the thinking.
The tools I would actually use
| Tool | What it is | What I use it for |
|---|---|---|
| PostgreSQL 18.7 | Open-source database, free | RLS policies, the tenant boundary, one schema and one pool |
| NestJS 11 | TypeScript backend framework, free and open source | Middleware, AsyncLocalStorage tenant context, the API layer |
| Prisma 7.10.1 | TypeScript ORM, free and open source | Client Extensions for tenant scoping, migrations for the RLS SQL |
| PgBouncer | Connection pooler, free and open source | Transaction-mode pooling that respects transaction-local settings |
| Supabase | Hosted Postgres with an RLS-first data API, free tier available | The managed path - ComplianceBot runs its tenant boundary here |
{/* MONETIZATION NOTE: Postgres, NestJS, Prisma, PgBouncer and Supabase's free tier have no affiliate program to swap in. The money path for this post is freelance/consulting leads: founders and hiring managers evaluating a multi-tenant build hire the author, which is why the CTA points at /#contact. */}
Top comments (2)
I wired your extension to the RLS policy on PG 17 with Prisma 7.10.1 and the app role. findMany came back [] because nothing in it calls set_config, and create() throws "Unknown argument
where". What worked was running each op like this:Then reads were scoped and a cross-tenant insert got 42501.
rls holding up at 5,000 tenants is the real test. the tenant context leaking once is the bug that costs the most.