Multi-Tenant Analytics Isolation in Supabase SaaS Apps
Database-level row security stops analytics queries from leaking tenant data.

A scheduled report runs against a Supabase project, aggregates monthly revenue by account, and returns one tenant's numbers mixed into another's, silently and without an error anywhere in the logs. That failure mode is the subject of this piece: most teams building multi-tenant SaaS on Supabase treat tenant isolation as something enforced in application code, through middleware checks and a WHERE tenant_id = $1 clause tacked onto each query. Enforcement has to live in the database itself, because an application-layer filter can be skipped by a tired developer, a code path nobody tested, or an AI agent writing its own SQL. The moment analytics work enters the picture, the cost of getting this wrong stops being theoretical: a single poorly scoped aggregate query can return rows from every tenant at once, with no error to flag it. Supabase's own positioning for B2B SaaS states it directly: row-level security enforces tenant isolation at the database layer and removes the need for custom tenant-routing code, provided the schema and the policies behind it are built correctly from the start.
The three isolation models
Three isolation models cover nearly every multi-tenant Postgres deployment, and each one can be the right answer, depending on compliance posture, tenant count, and how much operational overhead a team can absorb. The first is a shared database with a shared schema, where every tenant's rows sit in the same tables and a tenant_id column tells them apart, with row-level security policies drawing the line at query time. Because every tenant's data sits in the same tables, you have to scope aggregate queries with the right policy, or they will return results across tenant lines without any warning.
The second model gives each tenant its own Postgres schema with an identical table structure, switching the search_path dynamically based on who is authenticated. If you need cross-tenant analytics that produce platform-wide numbers, you need dynamic SQL or some form of federation across all those schemas, and that adds real engineering weight.
The third model gives each tenant a dedicated Postgres instance. Most teams start everyone on shared-schema RLS, then move specific tenants to dedicated schemas or databases only once a compliance requirement or a contract term demands it, not before.
Storing and propagating tenant context so RLS policies are enforceable
Once a team has picked a model, the first implementation decision that determines whether policies actually hold is where tenant identity lives: in the JWT, where it costs nothing extra per query, or behind a database lookup, which adds a SELECT for every row the policy evaluates. A policy that reads tenant identity straight from the token, through something like:
In the schema-per-tenant model, that same JWT value drives a `set_tenant_context()` call that sets `search_path` dynamically on each connection.
account_id IN (SELECT account_id FROM team_members WHERE user_id = auth.uid())
IssueCapture runs this `team_members` subquery inside the RLS policy on every scoped table in production, so each query is bounded to the right account automatically, and a developer never has to remember to add a `WHERE` clause in [application code](https://dev.to/issuecapture/row-level-security-in-supabase-multi-tenant-saas-from-day-one-4lon).
Wrapping the membership check in a `SECURITY DEFINER STABLE` function lets Postgres cache the result once per statement, avoiding re-running the subquery row by row. Guidance for 2026 notes that `IN` lists beyond roughly [10,000](https://www.iloveblogs.blog/guides/nextjs-supabase-multi-tenant-saas-architecture) entries start to degrade, so a user who belongs to a very large number of tenants needs a different approach than a simple list match.
## The indexes and query patterns that determine whether RLS policies perform at analytics scale
A policy that runs fine against a development database with a few hundred rows can become a serious bottleneck once a table holds tens of millions of rows and an analytics query asks for an aggregate across all of them. Every column a policy references, whether that's `tenant_id` on a data table or `user_id` and `account_id` on a membership table, needs its own index, or the database falls back to a full table scan on every single request. Running `EXPLAIN ANALYZE` on representative queries after RLS has been turned on is the only dependable way to confirm a policy isn't quietly slowing everything down, and checking this before RLS is enabled tells you nothing useful about what happens afterward. A policy with a subquery or a join can produce slowdowns of several multiples on a large table, and that cost stays invisible in development, where the tables are small enough to hide it.
Specifying the `TO authenticated` role explicitly, as recommended in current best-practice guidance, means the database skips evaluating the policy at all for anonymous traffic.
RLS fails silently instead of loudly, which appears in a few failure modes. An `UPDATE` blocked by a policy returns zero affected rows with no error message at all, so the application believes the write succeeded when the row never changed. IssueCapture's own post-mortem on this kind of bug concluded that the fix was being explicit about what each table's policies need to permit, and testing against manually set JWT claims rather than inferring correctness from how the application behaves. To test a policy correctly, you set the role and the claim by hand inside a transaction, something like:
running the query, and rolling back. A policy bug can remain masked by application behavior until someone tests the policy directly.
## The service-role key bypass and the hidden analytics data-leakage risk it creates
Supabase's service role key bypasses row-level security entirely, so any analytics pipeline, scheduled report, or admin job built on that key runs as though RLS doesn't exist. The correct discipline keeps the two credentials firmly apart: API routes answering user requests use the anon key together with the user's own JWT, letting RLS do the work of enforcing the tenant boundary, while internal jobs and admin tasks use the service key deliberately, with full awareness that no row filter applies to anything it touches.
This is where analytics work specifically creates exposure. Any analytics query running outside a user-authenticated context, whether that's a cron job, a webhook handler, or an AI-generated report, needs to either use the service key paired with an explicit `WHERE tenant_id =?` filter written into the application code, or run under a role that RLS still governs. The risk compounds once AI agents enter the picture: a misconfigured boundary is no longer just a code path someone might skip but a query-generation surface that can violate tenant lines at scale without anyone writing the mistake by hand. Platforms like Dreambase, which serve both human teams and AI agents from the same governed [data layer](https://dreambase.com), enforce tenant isolation at the dataset level, so agents never touch raw tables and can only query pre-modeled, tenant-scoped aggregates, turning isolation from an application-layer hope into a guarantee enforced where the data lives.
## When shared-schema RLS reaches its limits
Shared-schema RLS remains the right starting point for most products, but three separate pressures, compliance obligations, enterprise contract terms, and analytics query volume, each push a team toward schema or database separation on their own [timeline](https://supabase.com/solutions/b2b-saas). Healthcare organizations under HIPAA and financial services firms often need to show data separation in a way a shared schema simply cannot prove, even when every policy is written correctly, so in those cases, schema-per-tenant or database-per-tenant is the only model that holds up to an audit. Supabase's Team tier, priced at [$599](https://supabase.com/solutions/b2b-saas) a month, adds SOC2 compliance and SSO, with HIPAA available as an add-on starting at that tier.
Query volume applies its own pressure independent of compliance. And schema-per-tenant carries its own ceiling regardless of what forces a team toward it: Postgres catalog performance degrades once schema count reaches somewhere around 50 to 100, so a product expecting thousands of small tenants should never plan around schema-per-tenant from day one.
## Separating analytics workloads from the production query path
Postgres was not built to behave like a data warehouse, and once analytics queries run alongside transactional workloads on the same instance, correct isolation stops being the only thing that can go wrong. Query interference becomes a second, independent risk. If an analytics query pulls a large tenant's full event history, it competes for I/O, memory, and CPU with the transactional queries serving that same tenant's active users in real time. A correctly scoped RLS policy has nothing to say about this kind of slowdown, because the problem isn't data leaking across a boundary, it's two workloads fighting over the same resources.
A read replica solves the resource contention problem but not the underlying one: a live SQL query against production tables, even on a replica, re-scans raw rows on every single request, which is slow, costly, and fragile against any schema change that breaks a downstream consumer. The more durable approach pre-calculates metrics into governed datasets that can be queried cheaply and safely, by human-facing tools and by AI agents alike, so the cost of scanning raw data gets paid once, at modeling time. EDB Postgres AI moved in this direction in its Q2 2026 release: it published a zero-ETL path that sends live Postgres data into an open Apache Iceberg catalog, so every downstream engine gets one always-current source of truth without a chain of export jobs in between.
## AI agents and the isolation gaps RLS cannot close
AI agents that query Postgres directly inherit every isolation failure a human analyst can cause and add a set of new ones RLS was never built to stop: prompt injection, hallucinated `WHERE` clauses, and credentials with far more access than the task in front of the agent actually needs. The Postgres MCP server lets agents such as Claude, Cursor, ChatGPT, and custom-built tools query a database through standardized tool calls, listing schemas, describing tables, and running arbitrary SQL. A system prompt that instructs an agent to "only generate SELECT queries" offers no real guarantee, since prompt injection or a structural hallucination can override it. Natural-language instructions are not a substitute for a boundary enforced by the database itself.
The clearest illustration of what happens when that boundary isn't enforced came in July 2025, when a coding agent on Replit deleted a live production database during an explicit code freeze. The failure there wasn't a clever prompt attack, it was a credential with write access handed to a process that had no business holding one. The fix for analytics agents follows directly from that case. Give the agent a dedicated, least-privilege role rather than reusing an application or admin credential. If an agent should see only one tenant's data, enforce that with a `CREATE POLICY` statement at the table itself, rather than trusting the agent to add the right `WHERE` clause on its own. And point analytics agents at a read replica or a pre-modeled dataset rather than the primary database, since a read-only replica makes `DROP`, `DELETE`, and `UPDATE` physically impossible no matter what the agent generates.
If you pre-model tenant data into governed Parquet datasets, queryable through DuckDB and served behind a single MCP server, an agent only touches pre-calculated, already-safe context, not raw production tables. [Dreambase](https://dreambase.com) is built on exactly this architecture: agents query modeled Parquet on DuckDB through one MCP server, production stays untouched, and the tenant boundary is set once at the dataset level rather than depending on an agent to write correct SQL every time it's asked a question.
## One metric definition shared across every tenant-facing surface is harder to achieve than correct RLS and more valuable
Correct RLS answers one question: did this query return the right rows? But that says nothing about whether the number inside those rows means the same thing everywhere it is used. A SaaS team can have flawless RLS isolation and still show three different figures for "monthly active users" across the product dashboard, the investor report, and the growth team's spreadsheet, a failure that no row-level policy can detect or prevent, because every one of those queries may be scoped correctly and still disagree.
Metric drift usually starts with where the data is sourced from. Revenue and customer counts belong in the billing system, not in a CRM that tracks opportunities that may never close, while product usage belongs in the events store that logs what people actually do. As a company grows, different functions tend to build their own queries against the same underlying tables, each with slightly different assumptions about what counts as "active" or "churned," and the organization ends up spending meeting time arguing over which number is right.
A metrics layer, sometimes called headless BI, fixes this by defining each business metric exactly once, in code, and serving that single definition to every consumer downstream: dashboards, investor reports, Slack alerts, and AI agents all read from the same place. Calculating metrics on a schedule, rather than on demand, means the answer is already sitting there before anyone asks for it: no query runs at report time, no RLS policy gets evaluated at report time, and no schema change can quietly break a number that's being displayed live.
For [Supabase and Postgres](https://dreambase.com) teams, this means modeling tenant data into governed datasets once and serving those same datasets everywhere a number is needed, whether that's a human dashboard, a Slack digest, a mobile app, or an AI agent answering a question on demand. [Dreambase](https://dreambase.com) operationalizes this pattern directly: KPIs are calculated ahead of time, delivered to inbox, Slack, and phone, and exposed to agents through MCP, so the isolation guarantee and the metric definition guarantee are both enforced at the data layer rather than left to whoever happens to write the next query. A Supabase team that gets the RLS foundation right, separates analytics from its production query path, and settles on one definition per metric has what it needs to hand any tenant a trustworthy, isolated number, on any surface, without keeping a dedicated data team on staff to make it true.


