How to Design Multi-Tenant Architecture for AI SaaS with Supabase

How to Design Multi-Tenant Architecture for AI SaaS with Supabase

Introduction

To design multi-tenancy for a B2B AI SaaS on Supabase, the basic approach is to give shared tables a tenant_id and narrow down rows with Row Level Security (RLS), while switching to schema separation or database separation only for customers with strong regulatory or performance requirements is indispensable. This article is for engineers developing AI SaaS on Supabase, and explains, in 4 Steps, everything from tenant ID design, implementation of RLS policies, criteria for deciding on schema separation, to the procedure for verifying cross-tenant data leakage with pgTAP. By the end, you will be able to choose the isolation method suited to your own AI SaaS and write and verify RLS policies in Supabase.

Because Supabase generates a public API at the same time a table is created, until you enable RLS and write policies, the table remains readable and writable with the publishable key. Before deciding on a tenant isolation method, you need to first firm up this exposure scope and the key operation policy.

Tenant Isolation Options (RLS, Schema Separation, DB Separation)

In multi-tenant design built on Postgres, isolation methods are considered in 3 stages.

MethodStructureIsolation strengthOperational cost
Shared table + tenant_id (RLS)All tenants share the same table, narrowed down at the row levelLow to medium (depends on policy settings)Low. Migrations are applied once and reflected to all tenants
Schema separation (schema-per-tenant)Each tenant has a separate schemaMediumMedium. Migrations need to be rolled out across the number of schemas
Database separation (database-per-tenant)Each tenant has a separate database (a separate project in Supabase)HighHigh. Project management, backups, and connection management each occur individually

These 3 methods are in a trade-off relationship, and the higher the isolation strength, the greater the operational cost. The reason for making shared table + tenant_id + RLS the default configuration is that, as the comparison above shows, migration operational cost is low, and a realistic hybrid strategy is to migrate only the tenants with clear regulatory or contractual requirements to schema separation or database separation. If all tenants are put into schema separation or DB separation from the start, rolling out migrations and version management per schema becomes a burden on the development team, so a realistic order is to first solidify the design with RLS, and then add individual handling once it becomes necessary.

Additional Considerations When AI Agents Are Involved

In AI SaaS, it is increasingly common to store document embeddings in Postgres's pgvector as a vector database for RAG or similarity search. In this case, if the embeddings of all tenants are placed together in a shared table with a tenant_id, a tenant whose data volume is extremely large can affect search accuracy and latency, destabilizing even other tenants' search results.

The countermeasure is to separate indexes on a per-tenant basis. Either create a partial index per tenant conditioned on tenant_id, or partition the table itself by tenant and give each partition its own individual HNSW index. This makes it less likely that the search load of a large tenant will spill over into other tenants' query plans or latency.

However, this configuration increases operational cost as well, since it increases the number of index creations and rebuilds. At the stage when the number of tenants is small, a shared index with an explicit WHERE tenant_id condition is often sufficient, and it is realistic to consider introducing partitioning once the tenant count or a single tenant's data volume actually starts to strain performance.

As a rule of thumb for judgment, it is practical to proceed in stages: start operation with a shared index first, and switch to partial indexes or partitioning once search latency varies significantly from tenant to tenant, or once a particular tenant's data volume grows to exceed the combined total of all other tenants.

Step1: How to Design Tenant IDs and Assign Them to Each Table?

Step1: How to Design Tenant IDs and Assign Them to Each Table?

If you choose a table shared across all tenants, the starting point of the design is the tenant_id column. Unless the column's type, constraints, and indexing approach, along with a mechanism for identifying the tenant from the request, are all in place, room for leakage remains even if the RLS policy is written correctly.

Tenant ID Column Design and Indexing

The tenant_id column should be defined as UUID type with a NOT NULL constraint, set up as a foreign key to the tenants table. Allowing NULL would create rows that belong to no tenant, and since the RLS policy's conditional expression cannot catch such a row, this would cause either a data leak or an access failure. The foreign key should also explicitly specify behavior on deletion—deciding whether to cascade-delete related rows when a tenant is deleted, or use restrict if business requirements call for keeping them.

For index design, since RLS appends a tenant_id condition behind the scenes at query execution time, the leading column of any composite index should always be tenant_id. For example, for a listing query that filters by creation date, you should create a composite index on (tenant_id, created_at) rather than a standalone index on (created_at) alone. Without this, the execution plan is more likely to end up scanning the entire table to find rows satisfying the RLS condition.

sql
1create table documents ( 2id uuid primary key default gen_random_uuid(), 3tenant_id uuid not null references tenants(id) on delete cascade, 4created_at timestamptz not null default now() 5); 6 7create index idx_documents_tenant_created 8on documents (tenant_id, created_at);

When adding tenant_id to an existing table after the fact, it's easier to avoid locking or integrity errors by following this order: first add the column allowing NULL, backfill existing rows, and then apply the NOT NULL constraint. Keeping tenant_id consistently as the leading column in indexes makes it more likely that, regardless of what filter conditions the RLS policy writes, the execution plan will stably resolve into an index scan. The actual effect depends on table size and query patterns, so verification in your own environment is necessary.

How to Link Tenants with JWT or auth.users

In Supabase, PostgREST decodes the JWT sent by the client and passes the claim values into the PostgreSQL session. Using this mechanism, you can include tenant_id as a custom claim in the JWT, and have the RLS policy determine which tenant the current request belongs to. Just as auth.uid() returns the user ID, custom claims are retrieved via current_setting('request.jwt.claims', true).

One point to be careful of here is that user_metadata in auth.users is a value that can be rewritten from the client side. If the implementation allows a user to manipulate user_metadata through their own profile update API, then placing tenant_id there would let the user impersonate a different tenant.

Values used for access control, such as tenant_id, should be held in app_metadata or custom claims that can only be written server-side (via Supabase Auth hooks or custom token issuance processes), and should never be placed in user_metadata. When building tenant-switching or member invitation processes, you need to confirm beforehand that this write path is restricted to locations unreachable from the client.

Step2: How to Create Row Level Security (RLS) Policies?

Step2: How to Create Row Level Security (RLS) Policies?

Even after the tenant_id design and tenant association are complete, as mentioned in the premise, as long as RLS is not configured, reads and writes from the public API remain permitted. To prevent this, you need to enable RLS on the table with ALTER TABLE and write a CREATE POLICY for each operation. Policies should be separated by SELECT, INSERT, UPDATE, and DELETE, with the permitted conditions explicitly stated using USING and WITH CHECK.

Writing Read/Write Policies per Tenant

A typical way to write this is to narrow the readable rows with a USING clause, and explicitly state the conditions permitted at write time with a WITH CHECK clause. SELECT and DELETE should specify only USING, INSERT should specify only WITH CHECK, and UPDATE should specify both. This allows "visible rows" and "writable rows" to be controlled separately, making it possible to create asymmetric rules—for example, rows from other tenants are invisible, but even within your own tenant, updates that don't meet certain conditions are rejected.

For tenant determination, use the tenant_id extracted from the JWT's custom claim, comparing it against the value obtained via current_setting('request.jwt.claims', true). Policies should always separate roles using the TO clause: don't grant write policies to the anon role, and only grant tenant-conditioned policies to the authenticated role.

sql
1alter table documents enable row level security; 2 3create policy "tenant_select_documents" 4on documents for select 5to authenticated 6using ( 7tenant_id = (current_setting('request.jwt.claims', true)::json ->> 'tenant_id')::uuid 8); 9 10create policy "tenant_insert_documents" 11on documents for insert 12to authenticated 13with check ( 14tenant_id = (current_setting('request.jwt.claims', true)::json ->> 'tenant_id')::uuid 15);

When creating an UPDATE policy, use USING to restrict target rows to your own tenant, and also use WITH CHECK to confirm that the tenant_id doesn't change after the update. If WITH CHECK is omitted, there remains room for the update operation to rewrite the tenant_id itself to another tenant's value.

Performance Impact of Policies and Countermeasures

Since RLS conditional expressions are evaluated per row, writing a function call such as current_setting or auth.uid() directly in the USING clause makes the execution plan heavier as the number of rows in the target table increases. The solution is to wrap the function call in a SELECT so that it is evaluated only once, and then compared against each row.

sql
1create policy "tenant_select_documents_fast" 2on documents for select 3to authenticated 4using ( 5tenant_id = ( 6select (current_setting('request.jwt.claims', true)::json ->> 'tenant_id')::uuid 7) 8);

With this approach, PostgreSQL's planner only needs to resolve the tenant_id value once, making it easier to reduce the query to an index scan using the composite index led by tenant_id.

When writing a subquery within a policy that references another table (for example, a process that joins a membership table to check permissions), the subquery tends to execute per row and become slow, so it should be extracted as a security definer function with the STABLE attribute, allowing the result to be cached within a single query. Rather than writing complex conditions directly in the policy itself, keep the policy as a simple expression that merely calls this function, consolidating the actual condition logic into the function side—this helps maintain both the readability of the execution plan and its speed.

After modifying a policy, it's also essential to make a habit of checking the execution plan. Run the query with explain analyze each time to check whether the expected composite index on tenant_id is being used as an index scan, or whether it has fallen back to a sequential scan. The difference may be hard to notice while the table's row count is small, but latency can surface once the number of tenants or records grows, so it's safer to build execution plan verification into your operational workflow every time you add or modify a policy.

Step3: How to Determine When Schema Separation Is Needed?

Step3: How to Determine When Schema Separation Is Needed?

Even when operating with shared tables plus RLS, there are situations where, once a particular customer's contractual terms or a single tenant's data volume exceeds a certain threshold, the same configuration can no longer cope. The two axes for making this judgment are legal/contractual isolation requirements and the limits of performance and operations.

Handling Large Tenants and Customers Requiring Regulatory Compliance

For customers whose regulations or contracts require physical separation of data, you need to allocate a dedicated database. Since Supabase separates databases on a per-project basis, the standard approach for this type of customer is to prepare a separate Supabase project from the shared project, making it entirely independent—including authentication, storage, and RLS policies.

The deciding factors are two: whether the contract contains clauses such as data residency requirements or a prohibition on co-locating with other companies, and whether a single tenant's data volume or access frequency is large enough to strain the performance of the shared tables. If either condition applies, schema separation alone may not provide sufficient isolation strength, making this a candidate for project-level separation.

Once you decide to migrate to a dedicated project, you need to replicate the existing migrations, RLS policies, and Storage bucket settings into the new project. If this replication work is done manually, schema changes made on the shared project side won't be reflected in the dedicated project, leading to a situation where policy content gradually drifts out of sync without anyone noticing. From the moment you have even a single customer on a dedicated project, you need to manage migrations and policies as code and design your operations on the premise of applying the same changes across multiple projects.

Migration Operations When Introducing Schema Separation

As the number of tenants migrated to dedicated projects (database separation) or schema separation increases, applying a single schema change to multiple targets in the same order and with the same content becomes the core of day-to-day operations. If you write migration files locally and apply them individually to each project or schema, mistakes in applied order or missed applications occur, causing schema versions to drift apart between tenants.

To avoid this drift, you should manage migrations centrally as code and build on the premise of a mechanism that rolls them out in sequence from CI across a list of target projects or schemas. Specifically, migrations that have been verified on the shared table side are applied one by one to the list of tenants with dedicated projects or tenants with separated schemas, and the applied version for each tenant is recorded.

bash
1for project in $(cat tenant_projects.txt); do 2supabase link --project-ref "$project" 3supabase migration up 4done

For rollout, you take a staged approach: first apply to a single verification tenant and confirm there are no issues, then roll out to the remaining tenants if everything checks out. If a tenant fails during application, without records that let you individually track which version has been applied to each tenant, you won't be able to narrow down the scope of recovery work.

The order of application also needs to be fixed. Build into CI a mechanism that halts rollout to the remaining tenants until the results for the verification tenant have been confirmed, and automatically stops subsequent application the moment a tenant fails. Alongside this, keep a record of each tenant's currently applied version in a tracking table or management file, so you can always check at a glance which migration each tenant has been brought up to. Without this record, as the number of dedicated projects or separated schemas grows, you won't notice when a particular tenant is left behind on an outdated schema, and you'll end up needing a separate investigation every time you develop features or handle bugs for that tenant.

Step4: How to Test and Validate RLS Policies?

Step4: How to Test and Validate RLS Policies?

At the point when a policy is written, you still can't confirm whether the intended conditions actually function correctly as a query. Only after using pgTAP to verify in code, for each role and operation, that allow and deny behave as expected, can the design be said to have been realized as an implementation.

Test Cases for Verifying Cross-Tenant Data Leakage

There are four types of test cases you should cover at minimum.

  1. Rejection of cross-tenant reads: Confirm that a user from tenant A cannot SELECT, UPDATE, or DELETE rows belonging to tenant B.
  2. Rejection of anonymous access: Access the target table with the anon role, which holds no JWT, and confirm that not a single row is returned.
  3. Detecting exposure of service_role: Since operations using the service_role key bypass RLS entirely, separately audit whether this key is included in client-side code or in the repository, and set up a mechanism to detect it if it is.
  4. Checking for bypass via views/functions: Confirm that functions created with security definer, or views that don't have security_invoker set, aren't executing with the creator's privileges instead of the caller's privileges and thereby slipping past RLS conditions.

With pgTAP, you write tests by setting a JWT that mimics a user from tenant A or B and running the same query, then comparing the expected row count against the actual row count.

sql
1select set_config('request.jwt.claims', '{"tenant_id":"tenant-a-uuid"}', true); 2select results_eq( 3'select id from documents where tenant_id = ''tenant-b-uuid''', 4'values (null::uuid)', 5'tenant A cannot retrieve tenant B''s rows' 6);

For test data, don't use real customer information—instead, prepare a few dummy rows each for tenant A and tenant B, structured so that you can distinguish which tenant a row belongs to by its id or creation timestamp. For INSERT, UPDATE, and DELETE operations as well, use the same setup to attempt to operate on tenant A's rows using tenant B's JWT, and confirm that zero rows are processed. These four test types need to be structured so they can be re-run through the same procedure every time a policy is added or changed.

Incorporating RLS Testing into CI/CD

If tests are run manually, they are only verified at the moment a policy is changed, and you won't notice when a different change breaks an existing policy. You need to build a mechanism into CI that automatically runs pgTAP tests on every migration, maintaining a setup where cross-tenant test cases are run under the same conditions each time.

Specifically, on CI you create a clean DB with supabase db reset, apply the latest migrations with supabase migration up, and then run supabase test db to verify the policies' allow/deny behavior. By fixing this order, you can detect both missed migration changes and policy defects simultaneously within the same pipeline.

bash
1supabase db reset 2supabase migration up 3supabase test db

Configure the pipeline to stop the deployment at the point a test fails. On the premise that tests using dummy data for Tenant A and Tenant B return the same results in the CI environment, you should also manage the test data initialization process together with the migrations in the repository, so that tests that pass locally don't fail in CI.

If the Postgres version or the enabled state of extensions differs between the CI environment and developers' local environments, tests that pass locally may fail only in CI. By pinning the version in supabase/config.toml and enabling extensions such as pgvector on the migration side, you can prevent this kind of discrepancy in test results caused by environment differences. Run this pipeline on a per-pull-request basis, and make it standard practice to always check the pgTAP results before review for any migration that includes policy changes.

Common Failures in Multi-Tenant Design

Common Failures in Multi-Tenant Design

Even if you design and test RLS policies, isolation won't hold if the activation steps or key handling are mishandled. Data leaks between tenants tend to arise not from design flaws but from oversights at the operational stage—forgetting to enable RLS, exposing the service role key on the client side, exposing a table before policies are applied, and so on.

Failure of Deploying to Production Without Enabling RLS

Because Supabase automatically generates a public API as soon as a table is created, any table where you forget to enable RLS via ALTER TABLE remains exposed. A typical pattern is leaving RLS disabled during early development for the sake of testing, then missing the activation step for just that one table, which ends up exposed in production. With an operational approach where you individually run ALTER TABLE ... ENABLE ROW LEVEL SECURITY each time you add a new table, it becomes difficult to prevent such oversights through review alone.

The countermeasure is to bundle CREATE TABLE and ENABLE ROW LEVEL SECURITY into a single transaction within the migration file, making RLS activation an inseparable part of table creation. In addition, before deploying to production, you should incorporate into CI a step that runs Supabase's Security Advisor to list any tables where RLS is disabled. Testing policies with pgTAP verifies the content of the policies themselves, but detecting tables where RLS itself has been disabled requires a separate Security Advisor check.

Policy Bypass Due to Misuse of Service Role Keys

The service_role key (referred to as the secret key in the newer notation) has the privilege to read and write to all tables, bypassing all RLS policies. If this key is embedded in client-side API code called from the browser or in a mobile app bundle, then no matter how strictly you've designed your policies, any third party who reads the key can ignore tenant boundaries and access all data. The same outcome can result from the accident of committing a configuration file—along with this key as an environment variable—to a public repository.

The use of the service_role key should be limited to environments the client cannot reach, such as server-side batch processing or administrative scripts. Calls from the frontend or mobile app should use only the publishable key, and administrative operations such as cross-tenant aggregation or migrations should be structured so that the service_role key is referenced only internally, within a separately prepared server function.

Processing that uses this key must also incorporate checks that are mindful of tenant boundaries. Given that RLS does not apply, it's a good habit to explicitly write tenant_id conditions into batch processing queries and restrict the target tenant via an argument before execution; this helps avoid a situation where the key's broad privileges directly translate into a leak. In addition, it's essential to decide on a rotation procedure in advance, in case this key is accidentally exposed.

FAQ

FAQ

We answer three questions about how to choose an isolation approach, how to handle AI agents, and scalability as the number of tenants grows.

Q1: Which Should Be Adopted First, RLS or Schema Separation?

We adopt a shared table + tenant_id + RLS approach first. Choosing schema separation from the early stages of development causes migrations to be rolled out across multiple targets even when there are only a few tenants, which slows down development speed. The appropriate order is to switch only that specific customer to schema separation or a dedicated project once a customer appears whose contract includes clauses such as data residency requirements or prohibition of co-location with other companies, or once a single tenant's data volume begins to strain the performance of the shared table.

Q2: How to Prevent AI Agents from Referencing Data Across Tenants?

First, we check whether the AI agent's processing is directly manipulating the DB using the service_role key. We also pass JWT claims containing tenant_id to the agent's process and route it through RLS policies. For vector search, in addition to tenant_id partitions and partial indexes, we also explicitly specify WHERE tenant_id in the query itself to suppress fluctuations in the search plan.

Q3: How to Ensure Scalability as Tenant Count Grows in Supabase?

We address increases in tenant count through three stages: indexing, connection management, and project splitting.

  1. We regularly review composite indexes with tenant_id placed first and the query execution plans, confirming whether index scans are maintained even as the number of tenants grows.
  2. As the number of connections increases, we route them through a pooler such as Supavisor or PgBouncer, bundling the application-side connections in transaction mode. In this case, if session variables are set with a plain SET, there is a risk that a tenant's value could leak into another request in a pooling environment, so we isolate them per connection using SET LOCAL.
  3. Once a single tenant's data volume or contractual requirements exceed the limits of the shared table, we split out only that tenant into a dedicated Supabase project.

There is no need to uniformly separate the DB for all tenants; we distinguish between stages that can be absorbed through indexing and pooling, and stages that require individual separation.

Summary

Summary

When proceeding with multi-tenant design for an AI SaaS on Supabase, in Step 1 we give tenant_id to each table as UUID, NOT NULL, and a foreign key, and set up composite indexes with tenant_id first along with linkage via JWT custom claims. In Step 2, we enable RLS, create policies that separate reads and writes using USING and WITH CHECK, and tune performance by wrapping function calls in SELECT so that indexes are utilized. In Step 3, we decide on migration to schema separation or a dedicated project based on regulatory or contractual isolation requirements and single-tenant performance limits, centralizing the migration rollout order and version control in code. In Step 4, we use pgTAP to test cross-tenant read denial, anonymous access denial, and whether views can be bypassed, incorporating this into CI for automatic verification with every change. We also must not neglect operational practices to prevent two typical failures: forgetting to enable RLS and misusing the service_role key. We recommend starting by implementing the shared table + tenant_id + RLS approach as the initial configuration, and then incorporating pgTAP tests into CI.

References

  1. docs.aws.amazon.com/prescriptive-guidance/latest/saas-multitenant-managed-postg…Accessed November 23, 2026

Author & Supervisor

Yusuke Ishihara

Yusuke Ishihara

Started programming at age 13 with MSX. After graduating from Musashi University, worked on large-scale system development including airline core systems and Japan's first Windows server hosting/VPS infrastructure. Co-founded Site Engine Inc. in 2008. Founded Unimon Inc. in 2010 and Enison Inc. in 2025, leading development of business systems, NLP, and platform solutions. Currently focuses on product development and AI/DX initiatives leveraging generative AI and large language models (LLMs).