In multi-tenant SaaS, scope every query by tenant at the data layer
Tenant isolation should be impossible to forget, not something each route remembers.
Anish KumarSaaS Architecture#multi-tenancy#postgresql#security
The most dangerous bug in a shared-database SaaS is one tenant seeing another tenant's data.
It usually happens because one route forgot a WHERE tenant_id = ?.
The fix is to make the tenant filter structural, not optional:
- Resolve the tenant once, in middleware, from the session or subdomain — never from the request body.
- Expose a tenant-scoped data client (
db.forTenant(id)) and don't give routes the raw client. - Use PostgreSQL Row-Level Security as a second line of defense, so even a missed filter returns nothing.
- Add
tenant_idto every unique index, otherwise two tenants can't both have an invoice#1001.
If isolation depends on every developer remembering a filter in every query, it will eventually fail.