← All posts

Multi-tenant SaaS: keeping each customer’s data isolated

A tenant_id column is not enough: the one query that forgets it is what leaks a customer's data to another. Here is how to enforce isolation in both your code and your database.

Multi-tenant SaaS: keeping each customer's data isolated

Key points

  • In a shared-database SaaS, the real risk is not speed, it is the query that forgets the tenant filter.
  • An automatic filter in code plus a database policy beats either one alone.
  • Background jobs, caching and file storage are where isolation usually breaks.

Most SaaS products we build keep every customer in one database, with a tenant_id column on each table. It is cheap to run and easy to evolve. The catch: a single hand-written query without WHERE tenant_id = ?, tucked away in a CSV export or a reporting screen, and one customer sees another’s invoices. The goal is to make that mistake impossible, not just unlikely.

Shared tables, schema per tenant or database per tenant?

A shared database with tenant_id is the cheapest option and the easiest to migrate: one migration covers everyone. A schema per tenant in PostgreSQL isolates better, but migrations get painful once you have hundreds of customers. A database per tenant mostly makes sense when a contract demands physical separation or dedicated hosting.

We almost always start shared and keep the door open to moving a large customer to its own database later. That only works if every business table carries tenant_id, pivot tables included.

Lock one: an automatic filter in the application

In Laravel, a global scope on every tenant-owned model adds the filter to each query and fills the column on insert:

trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope('tenant', function (Builder $q) {
            $q->where($q->getModel()->getTable() . '.tenant_id', app('tenant')->id);
        });
        static::creating(function (Model $m) {
            $m->tenant_id ??= app('tenant')->id;
        });
    }
}

It has well-known gaps: raw SQL, DB::table(), and the withoutGlobalScopes() someone added while debugging and never removed all slip past it. Hence the second lock.

Lock two: row-level security in PostgreSQL

Row Level Security lets the database itself enforce the boundary:

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

-- at the start of every request or job
SET app.tenant_id = '6f1c...';

Two things bit us here. Without FORCE, the table owner bypasses the policy, and the owner is often the very user your app connects as. And with connection pooling, a plain SET can leak into the next request on the same connection: use SET LOCAL inside a transaction, or reset the setting whenever a connection is checked out.

Where isolation breaks in real life

  • Queued jobs run outside any HTTP request, so there is no current tenant. Store the tenant_id on the job and restore the context before doing anything.
  • Caching: a shared dashboard_stats key serves the first customer’s numbers to everybody. Prefix every key with the tenant ID.
  • Files: store uploads under a per-tenant path and never serve a file based on its name alone.
  • Unique constraints: an invoice number is unique per tenant, so use UNIQUE (tenant_id, number), and lead composite indexes with tenant_id.

FAQ

How do we prove isolation actually holds?

We write tests that seed two tenants, log in as one, then hit every list and export endpoint and assert nothing from the other tenant comes back. They run on every deploy.

What about our internal admin panel?

It needs to see every tenant. Give it a separate database role that is explicitly allowed to bypass the policy, rather than switching the filter off in application code.

Launching a SaaS, or hardening one that already has customers? We design multi-tenant architectures that hold up from day one.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →