• Residence: Bosnia & Herzegovina
  • City: Bijeljina
  • Age: 26
DOWNLOAD CV
Back to Blog

Multi-Tenant SaaS with NestJS and TypeORM: Choosing an Isolation Strategy

· Đorđije Lazarević · 3 min read

Every SaaS product has to answer one question early: how is one customer's data kept away from another's? The answer shapes your migrations, backups, costs and sales conversations for years. Here are the three options, how I choose between them, and how to enforce the choice in NestJS so a missed where clause cannot leak data.

Three strategies

Shared tables (tenant_id)Schema per tenantDatabase per tenant
IsolationLogical, in queriesStrong (PostgreSQL schemas)Strongest
Cost per tenantLowestLowHighest
MigrationsOnceOnce per tenantOnce per tenant
Per-tenant backup and restoreHardPossibleEasy
Good forMany small tenantsTens to hundreds of tenantsFew large or regulated tenants

My default is shared tables with a tenant_id column, plus database-level enforcement. I move a tenant to its own database only when a contract or regulation requires it.

Tenant context with AsyncLocalStorage

Passing tenantId through every function call does not scale. Node's AsyncLocalStorage keeps it available for the whole request without threading it through:

import { AsyncLocalStorage } from 'node:async_hooks';

export const tenantContext = new AsyncLocalStorage<{ tenantId: string }>();

export function currentTenantId(): string {
  const store = tenantContext.getStore();
  if (!store) throw new Error('No tenant in context');
  return store.tenantId;
}

@Injectable()
export class TenantMiddleware implements NestMiddleware {
  use(req: Request, _res: Response, next: NextFunction) {
    const tenantId = resolveTenantFromHost(req.hostname); // e.g. acme.app.example.com
    if (!tenantId) throw new NotFoundException();
    tenantContext.run({ tenantId }, () => next());
  }
}

After authentication, a guard checks that the signed-in user is a member of that tenant. Never trust a tenant ID from a header or the body on its own.

Repositories that cannot forget the tenant

For shared tables, every query must filter by tenant. Instead of relying on discipline, put the filter in the repository and do not expose the raw TypeORM repository to services:

@Injectable()
export class InvoicesRepository {
  constructor(@InjectRepository(Invoice) private readonly repo: Repository<Invoice>) {}

  findAll() {
    return this.repo.find({ where: { tenantId: currentTenantId() } });
  }

  findOne(id: string) {
    return this.repo.findOne({ where: { id, tenantId: currentTenantId() } });
  }

  create(data: Omit<Invoice, 'id' | 'tenantId'>) {
    return this.repo.save(this.repo.create({ ...data, tenantId: currentTenantId() }));
  }
}

A safety net in the database

With PostgreSQL, row-level security makes the database refuse cross-tenant reads even if a query is wrong:

ALTER TABLE invoice ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON invoice
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

Two details matter. The application must connect as a role that does not own the tables (owners bypass RLS unless you add FORCE ROW LEVEL SECURITY). And with a connection pool, set the tenant per transaction with SET LOCAL app.tenant_id = ..., so the value cannot leak to the next request on the same connection.

Database per tenant

When a tenant gets its own database, keep one TypeORM DataSource per tenant, created lazily and cached:

@Injectable()
export class TenantDataSources implements OnApplicationShutdown {
  private readonly sources = new Map<string, Promise<DataSource>>();

  get(tenantId: string): Promise<DataSource> {
    let source = this.sources.get(tenantId);
    if (!source) {
      source = new DataSource({
        ...baseOptions,
        database: `tenant_${tenantId}`,
      } as DataSourceOptions).initialize();
      this.sources.set(tenantId, source);
    }
    return source;
  }

  async onApplicationShutdown() {
    await Promise.all([...this.sources.values()].map(async (s) => (await s).destroy()));
  }
}

Watch the total number of connections: each data source has its own pool. Migrations run in a loop over all tenant databases as part of the release, and a failed migration for one tenant must not block the rest.

Details that bite later

  • Unique constraints must include tenant_id. An invoice number is unique per tenant, not globally.
  • Indexes start with tenant_id, because almost every query filters by it.
  • Background jobs carry the tenant ID in the job payload, and the worker re-enters tenantContext.run before doing any work.
  • Files in object storage use a tenant prefix, and signed URLs are generated per tenant.
  • Write at least one test per module that creates data in tenant A and asserts it is invisible from tenant B.

I have built multi-tenant systems in this style since Order2me, a multi-tenant QR-code restaurant ordering platform built with React and NestJS, and I apply the same rules on the business platforms I work on today.

Planning a React Native app?

I take on freelance projects for clients across DACH and the EU: React and Next.js web apps, React Native mobile apps and NestJS backends, from architecture to production. Remote, CET time zone.