Supabase Row-Level Security for Multi-Tenant Analytics

Database-enforced tenant isolation beats app-level filters, and here's how.

· 11 min read · Updated
Cover illustration for “Supabase Row-Level Security for Multi-Tenant Analytics”
Supabase Analytics · October 7, 2026 · 11 min read · 2,387 words

A developer removes a WHERE clause during a routine refactor. Neither event involves an attacker, and both can expose one tenant's data to another in a multi-tenant Supabase application. That is the problem a database-level access control mechanism exists to solve, and it is why that mechanism, not application code, has to be the layer that actually enforces tenant isolation in a multi-tenant analytics product.

The best way to enforce tenant isolation in a multi-tenant SaaS database is to put it in the database itself with row-level security, not in application code. In Supabase that means turning on RLS for every client-reachable table and writing policies that trace back to the tenant boundary. For users in one organization, a JWT claims policy such as USING (org_id::TEXT = auth.jwt()->>'org_id') is cheapest. For users in several organizations, a membership subquery wrapped in a STABLE SECURITY DEFINER function is the better fit, backed by indexes on the columns the policies filter on. The service_role key bypasses RLS, so it stays in server-side code only.

Every Supabase project exposes a PostgREST API and a Realtime WebSocket connection, both reachable by anyone holding the project URL and the anon key, both routed through Supabase's Envoy API gateway. Without RLS turned on, an authenticated user can read, update, or delete any row in a table, and the database will hand back every row it holds no matter what filtering the application tries to apply on top. The application layer can get this wrong in ways nobody notices until the data is already out: a middleware check gets bypassed, a filter gets dropped in a rewrite, an API route ships without the guard it was supposed to carry.

RLS moves that enforcement into PostgreSQL itself. A policy is a SQL expression the database checks on every query that touches a table, and a row either passes that check or, as far as the requesting user is concerned, does not exist. RLS is not a WHERE clause a developer has to remember to write into every query; it is a WHERE clause the database appends on its own, one no refactor can drop and no misrouted API call can skip. Supabase's own shared-responsibility model draws the line. The platform runs the server. Schema design, RLS policies, and API key handling belong to the developer, and a table with no policy on it is a gap the platform was never going to catch.

How RLS policies are structured

Every RLS policy has the same basic shape: it's named, it's attached to a specific table, it's bound to an operation (SELECT, INSERT, UPDATE, DELETE, or ALL), it can optionally be scoped to a role, and it carries a USING clause, a WITH CHECK clause, or both. Which clause a policy needs, and what each one actually checks, is the detail that separates a working tenant boundary from one that only looks like it works.

USING runs against rows that already exist in the table. WITH CHECK runs the other direction. It checks new or modified row data, and it governs INSERT and UPDATE: if the incoming values fail the WITH CHECK expression, Postgres rejects the write outright with a policy violation error.

UPDATE is the operation where both clauses matter at once, and it's the one place teams most often leave a gap. USING decides which existing rows a user is even allowed to reach for an update. WITH CHECK decides whether the new values they're trying to write are acceptable. Write one with only WITH CHECK and the gap opens the other way.

A table can carry more than one permissive policy for the same operation, and Postgres combines them with OR logic by default.

Two built-in functions do the identity work behind nearly every tenant-scoped policy. auth.uid() returns the authenticated user's UUID, pulled from their JWT. auth.jwt() returns the full JWT payload, letting a policy reach into custom claims like org_id or tenant_id in addition to the user's own ID.

One default catches almost every team that enables RLS for the first time: turning RLS on for a table with zero policies attached doesn't leave the table open. It locks it down completely. No policies means no accessible rows, for anyone, until explicit policies say otherwise. Teams retrofitting security onto an existing table routinely expect the table to keep behaving as it did before; instead, every query against it comes back empty.

The silent failure modes that bad policies produce in production

A misconfigured RLS policy rarely announces itself. Postgres doesn't throw an error when a policy excludes rows it shouldn't, and it doesn't throw one when a policy is more permissive than intended either. Wrong data, or no data, appears instead, with nothing in the logs flagging why.

An UPDATE that fails its USING clause doesn't fail loudly. It returns zero affected rows with no error message at all, so from the application's point of view the API call succeeded. The row simply never changed, because the USING expression excluded it before the update could touch it, and unless something downstream checks the row count, nobody finds out.

JOINs make this worse. When a query joins two tables that each carry their own RLS policies, rows that fail either table's policy drop out of the result silently, producing a result set that looks complete and isn't. These "ghost-missing rows" are hard to catch precisely because the query runs clean and returns real data, just less of it than it should.

A policy that looks correct there can fail completely the moment a real user hits it through the client SDK, which is the only place RLS should actually be tested.

Performance failure follows the same pattern: nothing breaks until the table grows. A policy that runs a subquery for every row scales fine in development against a few hundred rows and turns into a multi-minute query once a table holds millions, and that discovery usually happens under production load. That failure mode gets its own fix later in this piece, because it's common enough to deserve one.

The sharpest version of all of this is the service_role key. It bypasses RLS completely, by design, so that trusted backend processes can operate without tenant restrictions. If that key ends up where it shouldn't, committed into a repository, sent to a browser, embedded in client code, every tenant boundary the rest of the policy chain enforces disappears at once, and there's no policy violation, no error, no signal of any kind marking the moment it happened.

What is the best way to enforce tenant isolation in a multi-tenant SaaS database? The JWT claims pattern and the membership subquery pattern

Two patterns cover most of the ground in multi-tenant Supabase applications, and the choice between them comes down to one question: does a user belong to exactly one organization, or can they belong to several?

For users scoped to a single organization, the JWT claims pattern does the job with almost no runtime cost. A policy written as USING (org_id::TEXT = auth.jwt()->>'org_id') filters every query by organization automatically, and because the check happens against the token itself, there's no way for a developer to forget to add the org filter somewhere, since the database adds it for them every time. auth.jwt() reads that claim straight out of the token, with no database lookup involved, which is part of what makes this pattern fast. Getting here requires org_id to be embedded in the JWT at sign-in, typically through Supabase Auth's app_metadata, set server-side in a way the client has no ability to alter.

Users who belong to more than one organization need a different mechanism, because a single static claim can't represent membership in several tenants at once. That's the membership subquery pattern: a policy checks a membership table at query time to confirm the requesting user actually belongs to the organization the row claims to belong to. A production pattern for this wraps the check in a SECURITY DEFINER helper function, something like is_org_member(p_org_id UUID), which runs the EXISTS subquery against the membership table with elevated privileges and returns a plain boolean the policy can use directly. The membership table itself isn't exempt from this discipline. It needs its own RLS policies too, scoped so a user sees only the memberships belonging to organizations they're actually part of, not the entire table.

Choosing between the two patterns is a real design decision, not a default-and-fallback situation. JWT claims cost less at query time and suit the common case of one user, one organization. Membership subqueries cost more per query but handle the case JWT claims can't: a user who moves between organizations or holds membership in several at once. Either way, every table reachable by a client needs RLS turned on, and the policy chain has to trace back to the tenant boundary at every level: if projects belong to organizations and secrets belong to projects, the secrets table needs its own policy, and that policy needs to resolve back to the same organization check everything else in the hierarchy relies on.

LockIn's hierarchical RLS policy chain for a multi-tenant permission model

LockIn, a secure API key management platform built for hackathons and small teams, offers a concrete look at what these patterns turn into once a real permission hierarchy is involved. The product needed complete data isolation across organizations, each one containing projects, environments, secrets, and team members holding different roles, and that requirement doesn't resolve with a single table-level policy. It resolves with a chain.

The hierarchy runs six levels deep: Organization at the top, Members below it governed by role, Projects scoped to an organization, Environments scoped to a project, Secrets scoped to an environment, and Audit Logs scoped back to the organization. Each level in that chain needs a policy that correctly traces back to the organization boundary at the top, because a secrets table with a locally correct policy is still a leak if the environment or project above it isn't equally well scoped.

Two decisions inside LockIn's member-management policies each close a gap the simpler version of the pattern leaves open. The first is self-protection logic on the member UPDATE policy: an admin can change another member's role, but cannot change their own. The second is the "leave organization" DELETE policy, scoped narrowly to a user's own membership row. That narrowness is the point: a broad DELETE policy on a membership table is a standing risk, while one scoped to exactly the caller's own row allows a legitimate, common action without reopening the table to anything else.

None of this holds up at scale without indexes built to match. LockIn's composite indexes follow the hierarchy directly: member(user_id, organization_id), project(org_id), environment(project_id), secret(environment_id). Each index exists because a policy somewhere in the chain filters on that exact column, and an index that doesn't match what a policy actually checks does nothing for query speed no matter how well-designed the policy is.

Wrapping subqueries in SECURITY DEFINER functions to fix the performance problem

The performance failure introduced earlier, a policy subquery that runs once per row and turns into a multi-minute query at scale, has a standard fix: move the subquery out of the policy and into a SECURITY DEFINER function marked STABLE.

A STABLE function tells Postgres the function will return the same result for the same inputs within a single query, so Postgres can cache that result and reuse it across rows. Once the tenant lookup lives inside a function like that, the policy itself collapses into a scalar comparison, a single UUID checked against a single UUID, rather than a subquery Postgres has to re-run against every row it considers. A query Postgres can satisfy with an index lookup runs fast; one that forces it to re-execute a join or an EXISTS check per row does not.

One configuration step here is not optional. Every SECURITY DEFINER function needs search_path = public set explicitly. Setting search_path is the single line that prevents that, and it belongs on every SECURITY DEFINER function without exception.

Indexing matters just as much as the function rewrite. Missing indexes are the most common performance killer in RLS setups generally: a policy that filters on org_id with no index on that column forces Postgres into a sequential scan of the entire table for every authenticated request, no matter how efficient the policy expression itself is. The index has to match the column the policy actually filters on, which is the same principle behind LockIn's composite indexes in the previous section.

The broader discipline is to keep policy expressions themselves simple. A policy that joins three tables to make its decision is a policy that's going to slow down every query against that table, and the right response is to restructure the data model or pull the lookup into a helper function, not to leave the join sitting inside the policy expression. FORCE ROW LEVEL SECURITY closes a different gap: without it, a table's owner is exempt from that table's own RLS policies. Forcing RLS removes that exemption, with one caveat the Postgres documentation is explicit about: superusers and roles carrying the BYPASSRLS attribute still bypass RLS regardless of the FORCE setting.

The service_role key, Realtime, and the operational boundaries RLS creates

Two operational contexts in Supabase behave differently from the rest of the system, and both have to be handled on purpose. The service_role key bypasses RLS completely, by design, which makes it the right tool for trusted backend operations and the wrong thing to ever expose to a client. It belongs in server-side code only, in environment variables that never reach a browser or a public repository, because once it's exposed, it carries full access to every tenant's data with none of the policy checks the rest of the system depends on.

Realtime subscriptions work the other way: they honor RLS automatically. A client subscribed to a table's changes through Supabase Realtime only receives updates for rows that user's RLS policies actually permit them to see, so the same policy chain protecting REST queries protects the WebSocket stream as well.

Between the two, the operational rule is straightforward. Multi-tenant isolation in a Supabase application ultimately comes down to that one layer holding consistently, across every table, every query path, and every connection type the platform exposes.

More in Supabase Analytics