All posts
Engineering · 8 min read

Multi-Tenant SaaS: How Not to Leak Data Between Customers

The short answer

Most SaaS products isolate customers with a tenant_id column and database-level policies that filter every query by it. That is the right default: simpler than a schema or database per tenant, and safe provided the filter is enforced in the database rather than remembered in application code. The failure that actually causes leaks is a query path that forgets the filter, which is why the rule has to be enforced somewhere a developer cannot forget it.

Every multi-tenant leak has the same shape. Not a clever attack. One query that forgot the filter.

A new endpoint, an admin screen, a CSV export, a background job. Everything else in the codebase filters by tenant, and this one does not, because the person writing it did not know they had to.

So the question is not "how do we filter by tenant". It is "where do we put the filter so that forgetting it is impossible".

Three patterns

Shared database, tenant_id column. Every table carries tenant_id. Every query filters on it. Simple to run, simple to migrate, one backup. This is the right default.

Schema per tenant. Each tenant gets their own Postgres schema with identical tables. Stronger isolation, and every migration now runs N times. At fifty tenants this is an afternoon. At five thousand it is a job.

Database per tenant. Strongest isolation, highest cost. Justified for regulated data or a handful of enterprise customers who require it contractually. Rarely justified otherwise.

Start shared. Move individual large customers out later if a deal demands it. Almost nobody regrets that order; plenty regret the opposite.

Enforce it in the database, not in code

This is the part that matters.

If isolation lives in application code, it depends on every developer remembering, forever, on every code path, including the ones written at 11pm before a demo. That is not a security model, it is a hope.

Put it in the database with row level security, and the filter applies whether or not anyone remembered:

alter table public.documents enable row level security;

create policy "tenant isolation"
  on public.documents for all
  using (
    tenant_id in (
      select tenant_id from public.memberships
      where user_id = (select auth.uid())
    )
  );

Now a forgotten WHERE clause returns nothing instead of returning everything. The failure mode flips from silent breach to visible bug, which is the entire goal.

Index both sides or this policy becomes a full scan on every request:

create index on public.memberships (user_id);
create index on public.documents (tenant_id);

Where it still leaks

Row level security covers queries that run as the user. These paths do not:

Anything using the service key. Admin tools, background jobs, migrations, webhook handlers. The service key bypasses every policy by design. Every one of these must filter by tenant itself, and they are exactly the code nobody reviews carefully.

Admin views. The usual implementation grants broad access when a role says admin. If that role lives on a row the user can update, one compromised account reads every tenant. Keep roles in a table the API cannot write to.

Exports and reports. These aggregate, so they often bypass the normal data layer for performance. A report query written directly against the tables is the classic leak.

Caches. A cache key without the tenant id will happily serve tenant A's data to tenant B. This one is particularly nasty because it appears intermittently and looks like a ghost.

File storage. Database rows are isolated; the uploaded PDF in a bucket may not be. Check the storage policies separately, because they are a different system with different rules.

The test you must automate

Not a manual check. A test that runs on every change.

test("tenant A cannot reach tenant B's document", async () => {
  const { doc } = await seedTenantB();
  const asA = clientFor(TENANT_A_USER);

  // Read
  const { data } = await asA.from("documents").select("*").eq("id", doc.id);
  expect(data).toEqual([]);

  // Update
  await asA.from("documents").update({ title: "x" }).eq("id", doc.id);
  expect(await titleOf(doc.id)).not.toBe("x");

  // Delete
  await asA.from("documents").delete().eq("id", doc.id);
  expect(await exists(doc.id)).toBe(true);
});

Three separate assertions, because read, update and delete are governed separately and a policy covering one does not cover the others.

Write this once per table that holds tenant data. It is tedious and it is the only test in your suite that prevents a company-ending bug.

Getting the data model right early

Two decisions that are cheap now and expensive later:

Put tenant_id on every table, even where it is derivable. You can technically reach the tenant through a join from documents to projects to tenants. Do not. Denormalise it onto every table. It makes policies simple, indexes effective, and the filter obvious to whoever reads the schema next.

Decide early whether a user can belong to more than one tenant. Retrofitting that is a migration across every table and every policy. Even if today the answer is no, a memberships join table costs nothing now and saves a rewrite later.

Before you launch

  • Every table with tenant data has row level security on, and a policy for each of the four commands
  • tenant_id is indexed everywhere, and so is memberships(user_id)
  • Every service-key code path filters by tenant explicitly, and you have listed them
  • Roles live in a table users cannot write to
  • Cache keys include the tenant id
  • File storage rules are checked separately from the database
  • An automated cross-tenant test exists and is in CI

This sits in full stack development, and the SaaS customer portal and multi-tenant hiring platform case studies are both built this way.

For the policy mechanics in detail, including the four mistakes that cause leaks in the first place, see the complete guide to Supabase row level security. If the product was built with an AI tool, start with the production readiness checklist, because open policies usually travel with three other problems.

Common questions

What is the best way to isolate tenants in a SaaS app?
A shared database with a tenant_id column on every table, enforced by row level security so the filter cannot be forgotten. It is the simplest to operate and migrate, and the isolation is as strong as the policies. Separate schemas or databases per tenant give stronger isolation but multiply migration and operational work, and are worth it mainly for regulated data or a small number of large enterprise customers.
Why do multi-tenant apps leak data between customers?
Almost always one query that forgot the tenant filter. A new endpoint, an admin screen, a background job or an export runs without the WHERE clause everyone else remembered. This is why the filter belongs in the database as a policy rather than in a helper function developers are trusted to call.
How do I test tenant isolation?
Create two tenants with real data in each. Then, as a user of tenant A, try to read, update and delete a record belonging to tenant B by its id, calling the API directly rather than using the interface. All three must fail. Make this an automated test, because it is the one regression you cannot afford to find in production.
Should each customer get their own database?
Rarely, and usually only for compliance or for enterprise customers who require it contractually. Every schema change then has to run across every database, backups and monitoring multiply, and a single slow migration becomes a weekend. Start shared, and move individual large customers out later if a deal genuinely requires it.
Where do admin users fit in?
Admin access should be a separate path with its own policies, never an exception bolted onto tenant policies. The common mistake is a policy that grants access when a role column says admin, on a table the user can write to, which turns one compromised account into full access to every tenant. Keep roles in a table users cannot modify.
Work we do on this

Want this looked at properly?

Tell us what you're working with. We'll give you a straight answer in a 30-minute call, free.

One post a week

What this actually costs, and how it breaks.

Prices, timelines and the failures we keep running into, written down properly. No pitch, and you can leave in one click.

Read next