Most multi-tenant SaaS bugs are not complex logic failures. They are simple, silent data leaks.
They happen when a query is missing a single WHERE tenant_id = $1 clause.
That one missing condition is all it takes for Tenant A to see Tenant B’s data. When you rely solely on application code to filter every database query, you are placing 100% trust in every developer who touches the codebase—forever. One tired developer, one rushed hotfix, or an edge case in an ORM query can expose private tenant records.
The solution is to push isolation down to the database layer. By using database-native security features like PostgreSQL Row-Level Security (RLS), the database enforces isolation automatically, regardless of how the query was written in the application.
The Problem with Application-Level Isolation
When building a shared-database multi-tenant app, the simplest pattern is adding a tenant_id column to every table. Your application code is expected to filter on tenant_id during every read, update, and delete operation:
-- Application depends on this WHERE clause every single time
SELECT * FROM invoices WHERE tenant_id = 'tenant_123' AND status = 'unpaid';
This pattern breaks down as your application grows:
- ORM Abstractions: Complex object-relational mapping (ORM) relationships, eager loads, and custom raw queries increase the risk of omitting the filter.
- Developer Turnover: New team members might not know which custom methods to call to enforce tenant scoping.
- Database Administration: Direct database access for debugging or running manual scripts risks accidental cross-tenant data modification.
Relying on code reviews to catch missing filters is not a scalable security strategy.
Moving Isolation to PostgreSQL Row-Level Security
PostgreSQL includes Row-Level Security (RLS), a feature that restricts which rows a database query can return or modify based on security policies you define.
Instead of putting tenant logic in every SELECT query, you define a single policy on your database tables.
Step 1: Enable RLS and Create Policies
First, enable RLS on your target tables and define a policy that checks a session variable.
-- Enable Row-Level Security on the invoices table
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
-- Create a policy using PostgreSQL session context
CREATE POLICY tenant_isolation_policy ON invoices
FOR ALL
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);
Once this policy is enabled, PostgreSQL will automatically apply the USING clause to every SELECT, UPDATE, and DELETE statement executed by normal database users. If app.current_tenant_id does not match the row's tenant_id, the database acts as if the row does not exist.
Step 2: Set the Context in Your Backend
Your application layer no longer needs to append WHERE tenant_id = ... to every query. Instead, it sets the session variable when opening a connection or transaction for an incoming request.
Here is an example using Node.js and the pg library inside an Express middleware or service context:
import { PoolClient } from 'pg';
async function executeTenantQuery(client: PoolClient, tenantId: string, queryText: string, params: any[]) {
try {
await client.query('BEGIN');
// Set the tenant ID for the duration of this transaction
// The third parameter (is_local = true) scopes the variable to the transaction block
await client.query("SELECT set_config('app.current_tenant_id', $1, true)", [tenantId]);
// Query invoices directly without appending WHERE tenant_id = ...
const result = await client.query(queryText, params);
await client.query('COMMIT');
return result.rows;
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
By passing true as the third parameter to set_config, the variable setting is LOCAL to the current transaction block. This prevents tenant context from leaking into pooled connections reused by subsequent requests.
Key Considerations for RLS in Production
-
Connection Pooling: Always use
set_config('app.current_tenant_id', tenantId, true)inside an explicit transaction block. If you set session variables globally without transactions, connection poolers like PgBouncer in transaction-pooling mode might reuse a connection with the previous tenant's ID. -
Bypassing RLS: Superusers and roles with the
BYPASSRLSattribute bypass security policies by default. Ensure your application connects to PostgreSQL using a dedicated database role that respects RLS. -
Performance: Indexes on
tenant_idremain critical. PostgreSQL applies the RLS filtering policy alongside your existing query indexes, keeping performance consistent with manualWHEREclauses.
Building a multi-tenant SaaS requires defense in depth. By shifting tenant isolation down to PostgreSQL, you remove human error from the data safety equation and keep tenant boundaries intact by default.
About me
Tanmay builds AI agents and automation for businesses and is open to freelance projects. Connect with him on LinkedIn.
Top comments (0)