There is one question I ask whenever I review the architecture of a multi-tenant SaaS, and I rarely get an answer that survives two minutes of scrutiny: how many of your routes would return the wrong customer’s data if someone forgot a single line?
The honest answer, in most systems I have looked at, is I don’t know. The last panel I audited had about a hundred and twenty routes. Not because the team is careless. It is because isolation is implemented as a condition somebody has to remember to write, rather than as a property of the system. The distance between those two things is the distance between a system you can audit and a system you merely trust.
The failure of omission
Here is the pattern. Swap the entity name and you will find it in every codebase:
@router.get("/equipment/{equipment_id}")
async def get_equipment(equipment_id: UUID, session: AsyncSession = Depends(get_session)):
result = await session.execute(
select(Equipment).where(Equipment.id == equipment_id)
)
return result.scalar_one_or_none()
Four lines. No syntax error, no type error, nothing a linter will flag. It clears review because you have to remember what is missing in order to see it, and what is missing is this:
select(Equipment).where(
Equipment.id == equipment_id,
Equipment.tenant_id == ctx.tenant_id, # <-- not there
)
Sequential IDs make this trivially exploitable. UUID v4 makes it non-enumerable, which is not the same thing as fixed: an identifier only has to arrive through some other channel — a shared link, a generated PDF, a webhook payload, an audit record, a support ticket — and the isolation is gone.
And here is the part that matters: the tests do not catch it. A functional test authenticates a user, requests that user’s resource, and asserts it comes back. The unfiltered query passes that test perfectly. Catching it requires a test almost nobody writes by default: authenticate as tenant A, request a resource belonging to tenant B, assert a 404. One per route.
Why the pattern decays
The standard answer to this is to centralize the filter in the repository layer. And that is fine: it moves the filter out of the route and into the data layer, shrinks the surface, and works.
For a while.
What I have watched decay, every single time, are the paths that route around the repository — and they are always the same four:
The performance query. Somebody needs an aggregate and writes raw SQL, or a hand-rolled select(), because the repository does not cover it. That path never sees the filter.
The background job. No HTTP request, so no tenant context, so the context gets passed as an argument. An argument can be forgotten; worse, it can be passed wrong.
The eagerly loaded relation. You filter the root entity correctly and then walk into a child collection that filters nothing, because you assume its parent was already validated.
The endpoint written in a hurry. Copied from the one above it, adapted, and the clause falls off during the adaptation.
There is now a fifth path, and it is the one that has changed the risk calculus of this whole problem: an agent reproduces the pattern it sees. If your codebase expresses isolation as “remember to add this condition”, an agent inherits that forgetting and propagates it across dozens of files in an afternoon, in perfectly consistent style. It is not that the agent fails more often than a person. It is that a person forgets once and an agent forgets at scale, in code that reads as though somebody has already reviewed it.
A pattern that depended on human attention was already fragile with a small team and a handful of routes. It is untenable when much of the code is produced by something that does not understand why that condition is there.
The three levels
I frame it this way because there is no single answer. There are three levels with genuinely different costs, and choosing too far up is as expensive as choosing too far down.
Level 1 — Convention
The filter lives in application code and depends on discipline: a repository, a base class, code review. It is where nearly every system starts, and it is the right answer while you are two people and fifteen routes. It stops being the right answer the day you can no longer answer the opening question from memory.
Level 2 — A dependency that forces the issue
This is where the conceptual shift is real: you make it impossible to obtain data access without tenant context. The point is not that forgetting becomes harder: it is that the wrong thing becomes impossible to construct.
In FastAPI, that means get_session stops existing as a public dependency. What gets injected is a session that is already scoped:
@dataclass(frozen=True)
class TenantContext:
tenant_id: UUID
async def scoped_session(
ctx: TenantContext = Depends(require_tenant),
) -> AsyncIterator[ScopedSession]:
async with session_factory() as session:
yield ScopedSession(session, ctx.tenant_id)
And ScopedSession does not expose raw execute(). It exposes operations that apply the filter themselves. The tenant ID is not an argument you pass; it is a property of the object you talk to the database through.
Two things go alongside it. First, the type of the identifier: a TenantId that cannot be constructed empty and is not interchangeable with any other UUID in the system. It sounds like ceremony right up until it prevents the first confusion of user_id with tenant_id in a six-argument signature. Second, an automated sweep that walks the router at test time and fails if any route touching tenant data does not go through the context. That is a whole article of its own, and it is the next one in this series.
What level 2 still does not cover: hand-written SQL. If somebody opens a connection and writes a query, level 2 never sees it. And migrations, maintenance scripts and data exports always end up writing hand-written SQL.
Level 3 — The database enforces it
Row Level Security in PostgreSQL. The filter stops living in your code and moves into the engine, where it applies regardless of where the query came from.
ALTER TABLE equipment ENABLE ROW LEVEL SECURITY;
ALTER TABLE equipment FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON equipment
FOR ALL
USING (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);
And once per transaction, before any query:
await session.execute(
text("SELECT set_config('app.tenant_id', :tid, true)"),
{"tid": str(ctx.tenant_id)},
)
Four details decide whether this works or merely looks like it does.
FORCE ROW LEVEL SECURITY is not optional. By default, the table owner bypasses its own policies. And if your application connects with the same role that runs migrations — the default in more places than it should be — you have RLS switched on and no isolation whatsoever. The application must connect as a different role: not a superuser, not the table owner, and without BYPASSRLS. A superuser bypasses the policies even with FORCE.
The third argument to set_config is what makes this safe behind a connection pool. With true, the value is transaction-local and disappears when the transaction ends. Use plain SET and the value persists on the session, the connection returns to the pool still carrying the previous customer’s tenant ID, and you have built a cross-tenant data leak triggered by concurrency. It is the hardest failure in this family to reproduce. The operational consequence is that every query has to run inside a transaction, with no exceptions.
It fails closed, but not the way you expect — which is why that nullif is there. The version of this policy you will find in almost every article compares current_setting('app.tenant_id', true)::uuid directly, on the reasoning that an undefined setting returns NULL, the comparison evaluates to NULL, and no rows come through. That holds on a freshly opened connection. It stops holding on the second request.
I checked this against PostgreSQL 18, and the detail matters: a custom setting assigned with set_config(..., true) does not revert to undefined when the transaction ends — it reverts to the empty string. And ''::uuid is not NULL; it is a syntax error. So on a connection that has already served one request, the next one that forgets to set the tenant does not get zero rows. It gets invalid input syntax for type uuid: "" and a 500.
It still fails closed, which is the part that matters: not a single row leaks. But the failure mode is a database exception rather than an empty result set, and that changes how you instrument it. Wrap the setting in nullif(..., '') and the empty string becomes NULL again, restoring the behavior the policy was supposed to have: zero rows, loud and harmless.
The policy is appended to every query. Keep the expression trivial — a direct comparison against a current_setting, which is stable and the planner handles well — and index tenant_id, usually as the leading column of the composite indexes you already have. Put subqueries or non-stable functions in the policy and the plan degrades in ways you will discover in production.
The fourth level, which I mention in order to rule it out
Schema per tenant, or database per tenant. Maximum isolation, and the easiest answer to sell to an auditor.
The cost is not performance. It is that every migration is multiplied by your customer count. At twenty tenants it is an annoyance. At two thousand it is a deployment system you have to build and maintain, complete with partial failures, retries and schemas stranded on different versions. Add the degradation of the PostgreSQL catalog and the plan cache on top.
It earns its keep in one specific case: a small number of large customers with contractual requirements for physical separation or per-customer data residency. Outside that, you are buying isolation and paying for it with your ability to ship.
The decision table
| Criterion | Level 1 · Convention | Level 2 · Dependency | Level 3 · RLS | Level 4 · Schema per tenant |
|---|---|---|---|---|
| Covers hand-written SQL | No | No | Yes | Yes |
| Covers background jobs | No | Partly | Yes | Yes |
| Cost to introduce | None | Medium | Medium-high | High |
| Ongoing operational cost | None | Low | Low | High |
| Performance cost | None | None | Low, if indexed | Variable |
| Cost per migration | 1× | 1× | 1× | N× |
| Needs a separate DB role | No | No | Yes | Recommended |
| Can be retrofitted | — | Yes, incrementally | Yes, table by table | Very expensive |
Two things are not in the table, and they are the ones that actually decide.
The levels stack; they do not substitute. RLS is not license to write unfiltered queries. Level 2 is your correct behavior and your decent error message; level 3 is the net underneath. A system with only the net returns inexplicably empty results instead of useful errors.
Level 3 can be introduced table by table. This is why I almost always dismiss the “it’s too late for RLS” argument. You start with the three tables where a leak would be a reportable incident, not with all thirty. The migration is one policy and one change of connection role.
nullif — verified on PostgreSQL 18.4FORCE ROW LEVEL SECURITY is missing — verified on PostgreSQL 18.4When not to
If your product has three customers, four tables and a single developer, standing up RLS now is ceremony. Level 1 with a disciplined repository will serve you, and the time is better spent on the product existing at all. Level 3 makes no sense either in a service that holds no tenant rows — a gateway, a renderer, a stateless worker: there is nothing to isolate, and you have only added a layer that will fail in confusing ways.
The honest threshold is not a customer count. It is the moment you can no longer enumerate from memory every place that reaches a given table. On that day, convention stops being a defense mechanism and becomes a hope.
Closing
Cross-tenant isolation is the one invariant in a multi-tenant SaaS whose violation has no repair path. A miscalculated total gets recalculated. A misdirected email gets retracted. A customer who has seen another customer’s data is a notification to a supervisory authority, an uncomfortable conversation, and — with luck — nothing worse.
Which is why it should not be implemented as something you have to remember to write. The right question is not “do we filter by tenant?” It is:
What would have to happen for a cross-tenant leak to be possible, and how many independent things would have to fail at once?
If the answer is “somebody forgets a condition”, you have one level. If it is “somebody forgets a condition, and gets hold of a session without context, and the database does not apply the policy, and the CI sweep does not catch it”, you have four. That is the entire job.
Next in this series: how to audit tenant isolation across an API already running in production, with the route sweep that turns it into a permanent CI gate.