Building Multi-Tenant SaaS Applications With Scalable Architecture
Tenant resolution, data isolation and query scoping for one codebase serving many customers.
- saas
- multi-tenant
- architecture
- node.js
On this page ยท 14 sections
Multi-tenant SaaS is one application serving many customers. It is cost-efficient and easy to ship updates to, and it has one failure mode that can end a company's reputation: showing one customer another customer's data. Good multi-tenant architecture is mostly about making that mistake structurally difficult. This guide walks through the layers: choosing an isolation model, resolving the tenant, carrying tenant context safely, scoping queries, enforcing isolation in the database, and keeping caches, files, jobs and performance tenant-aware.
The code uses Node.js, TypeScript and PostgreSQL, but the ideas apply to any stack.
Choose an isolation model
| Model | How it works | Strengths | Costs |
|---|---|---|---|
| Shared schema | One database, every table has tenant_id | Cheapest, simplest migrations, easy cross-tenant analytics | Isolation depends on discipline and policies; noisy neighbors |
| Schema per tenant | One database, one schema per tenant | Stronger logical separation, easier per-tenant export | Migrations run per schema; many schemas strain the catalog |
| Database per tenant | A separate database per tenant | Strongest isolation, per-tenant backup and tuning | Highest operational cost; connection management |
A practical path: start with a shared schema plus strict scoping and row-level security, and design so that a large or regulated tenant can later be moved to its own database. The rest of this guide assumes a shared schema.
The request lifecycle
- 1Resolve the tenant
subdomain, header or token claim
- 2Authenticate and authorize
user must belong to that tenant
- 3Store tenant context
available to every layer for this request
- 4Scoped data access
every query filtered by tenant
Step 1: Resolve the tenant
A subdomain is the most user-friendly option:
// src/tenancy/resolve-tenant.tsimport type { NextFunction, Request, Response } from "express";import { AppError } from "../errors";const BASE_DOMAIN = process.env.BASE_DOMAIN ?? "app.example.com";export function resolveTenantSlug(req: Request): string | null { const host = req.hostname.toLowerCase(); if (!host.endsWith(`.${BASE_DOMAIN}`)) return null; const slug = host.slice(0, -(BASE_DOMAIN.length + 1)); return /^[a-z0-9-]{1,63}$/.test(slug) ? slug : null;}export async function tenantMiddleware(req: Request, _res: Response, next: NextFunction) { try { const slug = resolveTenantSlug(req); if (!slug) throw AppError.notFound("Tenant"); const tenant = await tenantRepo.findBySlug(slug); if (!tenant || tenant.status !== "active") throw AppError.notFound("Tenant"); req.tenant = { id: tenant.id, slug: tenant.slug, plan: tenant.plan }; next(); } catch (err) { next(err); }}Never trust the tenant the client claims. After authentication, verify that the user has a membership in this tenant; a valid login for tenant A must not work on tenant B's subdomain:
export async function requireMembership(req: Request, _res: Response, next: NextFunction) { const membership = await memberships.find(req.user!.id, req.tenant!.id); if (!membership) return next(AppError.forbidden()); req.membership = membership; // contains the user's role within THIS tenant next();}Step 2: Carry tenant context without passing it everywhere
Passing tenantId through every function is error-prone because one missed call leaks data. Node's AsyncLocalStorage keeps a per-request context available anywhere in the call chain:
// src/tenancy/context.tsimport { AsyncLocalStorage } from "node:async_hooks";interface TenantContext { tenantId: string; userId?: string;}const storage = new AsyncLocalStorage<TenantContext>();export const runWithTenant = <T>(ctx: TenantContext, fn: () => T) => storage.run(ctx, fn);export function currentTenantId(): string { const ctx = storage.getStore(); if (!ctx) throw new Error("No tenant context: this code ran outside a tenant-scoped request"); return ctx.tenantId;}app.use(tenantMiddleware);app.use((req, _res, next) => runWithTenant({ tenantId: req.tenant!.id, userId: req.user?.id }, next));The deliberate throw when no context exists is important: code that forgets tenant scope fails loudly instead of returning everyone's data.
Step 3: Scope every query in one place
Do not rely on each developer remembering WHERE tenant_id = .... Put scoping in a repository layer or a database client wrapper so it is the default:
// src/tenancy/tenant-repository.tsimport { currentTenantId } from "./context";export class InvoiceRepository { constructor(private db: Db) {} list(limit = 50) { return this.db.query( "SELECT id, number, total_cents FROM invoices WHERE tenant_id = $1 ORDER BY created_at DESC LIMIT $2", [currentTenantId(), limit], ); } findById(id: string) { // Both conditions: an ID from another tenant must look like "not found". return this.db.queryOne( "SELECT * FROM invoices WHERE id = $1 AND tenant_id = $2", [id, currentTenantId()], ); } create(input: NewInvoice) { return this.db.queryOne( "INSERT INTO invoices (tenant_id, number, total_cents) VALUES ($1, $2, $3) RETURNING *", [currentTenantId(), input.number, input.totalCents], ); }}Notice findById. A classic leak is looking up by id alone (an insecure direct object reference). Always combine the ID with the tenant, and return "not found" rather than "forbidden" so tenants cannot probe each other's IDs. Use composite indexes that start with tenant_id, such as (tenant_id, created_at), because nearly every query filters by tenant first.
Step 4: Enforce isolation in the database with row-level security
Application scoping is the first line of defense. PostgreSQL row-level security (RLS) is the second: even a buggy query cannot see other tenants' rows.
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- applies to the table owner tooCREATE POLICY tenant_isolation ON invoices USING (tenant_id = current_setting('app.tenant_id')::uuid) WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);The application sets the tenant for the duration of each transaction. SET LOCAL is scoped to the transaction, which keeps pooled connections from leaking context between requests:
export async function withTenantTransaction<T>(fn: (client: PoolClient) => Promise<T>) { const client = await pool.connect(); try { await client.query("BEGIN"); await client.query("SELECT set_config('app.tenant_id', $1, true)", [currentTenantId()]); const result = await fn(client); await client.query("COMMIT"); return result; } catch (err) { await client.query("ROLLBACK"); throw err; } finally { client.release(); }}Important RLS caveats: the application must connect as a role that is not a superuser and does not have the BYPASSRLS attribute (superusers and such roles bypass policies), and connection poolers in transaction mode need the set_config(..., true) transaction-local form shown above.
Step 5: Make everything else tenant-aware
Data in the primary database is only one place where tenants can mix.
Caches. Include the tenant in every cache key:
const key = `t:${currentTenantId()}:invoices:list`;A shared key like invoices:list would serve one tenant's cached data to another.
File storage. Namespace object keys by tenant (tenants/<tenantId>/uploads/...), generate signed URLs server-side after authorization, and never accept a raw storage path from the client.
Background jobs. A job runs outside the request, so the context is gone. Put tenantId in the job payload and restore the context when the worker starts:
worker.process(async (job) => { return runWithTenant({ tenantId: job.data.tenantId }, () => handleJob(job.data));});Search indexes and analytics. Filter on tenant in every query, or use per-tenant indexes. Logs and metrics. Tag with tenant id so you can debug and bill per tenant (and avoid logging other tenants' data in shared error reports).
Step 6: Plan for noisy neighbors
One tenant running a huge export should not slow everyone down.
- Per-tenant rate limits and plan-based quotas at the API layer.
- Queue concurrency limits per tenant so a flood of jobs from one tenant cannot starve others.
- Query timeouts and pagination limits.
- Usage metering per tenant, which also supports billing.
- An escape hatch: the ability to move a heavy tenant to dedicated infrastructure.
Tenant lifecycle and migrations
- Onboarding: create the tenant row, default roles and settings in one transaction.
- Migrations: shared-schema migrations run once. With schema-per-tenant, automate running them across all schemas and handle partial failures.
- Offboarding: support export and deletion, honoring retention requirements, and delete the tenant's files, cache keys and search data too.
- Per-tenant configuration: feature flags and plan limits stored on the tenant, not hard-coded.
Security considerations
- Never trust a tenant identifier from the client without verifying membership.
- Use unguessable identifiers (UUIDs) and still check tenant ownership on every lookup.
- Apply row-level security as defense in depth.
- Keep admin or support access to tenant data audited and time-limited.
- Separate platform administrators (who see all tenants) from tenant administrators with explicit, logged access paths.
Testing tenant isolation
Treat isolation as a feature with its own test suite, not an afterthought:
describe("tenant isolation", () => { it("never returns another tenant's invoices", async () => { const a = await createTenantWithInvoice("tenant-a"); const b = await createTenantWithInvoice("tenant-b"); const listA = await asTenant(a, () => invoices.list()); expect(listA.map((i) => i.id)).toEqual([a.invoice.id]); const stolen = await asTenant(a, () => invoices.findById(b.invoice.id)); expect(stolen).toBeNull(); // looks like "not found" }); it("fails loudly when there is no tenant context", () => { expect(() => invoices.list()).toThrow(/No tenant context/); });});Add the same pair of tests for every feature that stores data: exports, search, file downloads, webhooks, background jobs and cached endpoints. A generic test that scans your schema for tables missing a tenant_id column or an RLS policy is also valuable.
Common mistakes
- Looking up records by ID only.
- Shared cache keys and shared storage paths.
- Background jobs that run with no tenant context.
- Trusting a tenant ID from a header or request body.
- Connecting to the database as a superuser, which bypasses row-level security.
- Reports and admin screens that aggregate across tenants without a deliberate, audited path.
Best practices
- Resolve the tenant once, verify membership, and carry the context automatically.
- Make un-scoped data access fail instead of succeeding.
- Combine application scoping with row-level security.
- Namespace caches, files and jobs by tenant.
- Test isolation continuously, and monitor per-tenant usage.
Conclusion
Multi-tenancy is not a feature you bolt on at the end. It is a constraint that runs through routing, authentication, data access, caching, storage and operations. If tenant context is resolved once, carried automatically, enforced in the database and tested relentlessly, the dangerous mistake (a missing filter) stops being a hidden bug and becomes something your architecture catches for you.
Frequently asked questions
+What is multi-tenancy?
A single application and infrastructure serving multiple customers (tenants), with each tenant's data and configuration logically isolated from the others.
+What is the biggest risk in a multi-tenant system?
Cross-tenant data leakage: one customer seeing another's data because a query forgot to filter by tenant. Architecture should make that mistake hard to make and easy to detect.
+How should I identify the current tenant on each request?
Common options are a subdomain (acme.app.com), a path or header, or a claim in the authenticated user's token. Resolve it once, early, and verify it against the authenticated user's memberships rather than trusting the client.
+Should I use a shared database or one database per tenant?
A shared database with a tenant_id column is the cheapest and simplest to operate and scales to many small tenants. Schema-per-tenant or database-per-tenant gives stronger isolation and per-tenant backup at higher operational cost. Many products start shared and move large or regulated tenants to dedicated resources.
+How does PostgreSQL row-level security help?
It enforces tenant filters inside the database through policies, so even a query that forgets its WHERE clause cannot return another tenant's rows. It is a strong second line of defense behind application-level scoping.
+How do I handle the noisy neighbor problem?
Apply per-tenant rate limits and quotas, queue heavy work with per-tenant concurrency limits, monitor usage by tenant, and be able to move a heavy tenant to dedicated capacity.
+How do I test tenant isolation?
Write automated tests that create two tenants and assert that every read, update, delete, search, export and background job for tenant A can never touch tenant B's data, including through caches and file storage.