Architecture & Multi-Tenancy · Backend · Data & Caching· 9 min read
Multi-tenancy: AsyncLocalStorage context scoping and zero cross-tenant leakage
How to enforce tenant isolation at the database layer using Node.js AsyncLocalStorage. Why manual query filtering fails, and how to guarantee strict multi-tenant boundaries in NestJS and MongoDB.
Multi-tenancyNestJSAsyncLocalStorageMongoDBArchitecture
On this page
In multi-tenant B2B platforms, the most catastrophic failure mode is cross-tenant data leakage. If Tenant A can view even a single payslip, invoice, or employee record belonging to Tenant B, trust is permanently broken. Relying on individual developers to remember appending `{ tenantId }` to every repository query is a fatal gamble. In my HRMS and SaaS platforms at Tedekstra, isolation is enforced centrally at the infrastructure boundary using Node.js native AsyncLocalStorage.
The three multi-tenancy models
| Strategy | Isolation Level | Ops Overhead | Migration Cost | Best For |
|---|---|---|---|---|
| Shared database with tenantId column/field | Logical (code-enforced) | Lowest | Single migration run | High-volume B2B SaaS, standard tiers, fast feature delivery |
| Schema per tenant (PostgreSQL namespaces) | Logical & structural | Moderate | N migrations across schemas | Mid-market clients requiring custom tables or namespace isolation |
| Database per tenant (Strict DB segregation) | Physical (separate stores) | Highest | Orchestrated multi-database fleets | Regulated enterprise accounts, strict data residency requirements |
Why manual filtering fails and how AsyncLocalStorage fixes it
When a codebase grows beyond 50 endpoints and multiple developers contribute features, manual query filtering inevitably leaks. A developer writes `find({ status: 'ACTIVE' })` instead of `find({ tenantId, status: 'ACTIVE' })`, passes code review, and leaks data in production. With Node.js AsyncLocalStorage, the tenant context is injected at the HTTP middleware boundary and automatically propagates through asynchronous execution paths without passing `tenantId` through every service method.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { AsyncLocalStorage } from 'async_hooks';
import { Request, Response, NextFunction } from 'express';
export interface TenantContext {
tenantId: string;
organizationId: string;
role: string;
userId: string;
}
export const tenantStorage = new AsyncLocalStorage<TenantContext>();
@Injectable()
export class TenantMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
const tenantId = req.headers['x-tenant-id'] as string || req.user?.tenantId;
if (!tenantId) {
return res.status(403).json({ error: 'Tenant context required for tenant-scoped operations' });
}
const context: TenantContext = {
tenantId,
organizationId: req.user?.organizationId || tenantId,
role: req.user?.role || 'GUEST',
userId: req.user?.sub || '',
};
tenantStorage.run(context, () => {
next();
});
}
}Enforcing automatic scoping in database queries
With AsyncLocalStorage running, Mongoose plugins and custom Prisma extensions can intercept every `find`, `findOne`, `updateOne`, and `delete` operation before execution. If a query lacks the tenant identifier, the repository middleware automatically merges `{ tenantId: context.tenantId }` into the filter criteria.
import { Schema } from 'mongoose';
import { tenantStorage } from './tenant-context';
export function autoTenantPlugin(schema: Schema) {
schema.add({ tenantId: { type: String, required: true, index: true } });
schema.pre(/^find/, function (next) {
const context = tenantStorage.getStore();
if (context?.tenantId) {
this.where({ tenantId: context.tenantId });
}
next();
});
schema.pre('save', function (next) {
const context = tenantStorage.getStore();
if (context?.tenantId && !this.tenantId) {
this.tenantId = context.tenantId;
}
next();
});
}