Understanding Row Level Security Basics
Row Level Security (RLS) is a PostgreSQL feature available since version 9.5 that allows you to define policies controlling which rows a user can see or modify. Unlike application-level filtering that can be bypassed, RLS policies are enforced directly inside the database engine for every query.
When RLS is enabled on a table, the database automatically adds a hidden filter to every SELECT, INSERT, UPDATE, and DELETE statement based on your policies. This happens before the query planner even considers indexes, making it both secure and performant when properly configured.
The core commands are simple. You enable RLS with:
ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
Then you create policies that define the USING clause for reads and the WITH CHECK clause for writes. A basic policy might look like this:
CREATE POLICY "tenant_isolation" ON projects
USING (tenant_id = current_setting('app.current_tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);
This policy references a session variable that your application sets for each database connection. The cast to uuid ensures type safety and allows the query planner to use indexes effectively.
Why Choose RLS Over Separate Databases or Schemas
Many teams default to creating a new database per tenant for strong isolation. This approach creates operational complexity: migrations must run against hundreds of databases, connection pool limits become hard to manage, and cross-tenant analytics require separate ETL processes.
Schema-per-tenant reduces some complexity but still fragments your data and makes foreign keys across schemas painful. Application-level filtering in every repository method is easy to implement incorrectly and impossible to guarantee during ad-hoc queries or reporting.
RLS gives you a middle path. All tenants share the same tables and connection pool while the database enforces isolation. This simplifies backups, migrations, analytics, and reduces infrastructure costs. The trade-off is that you must write careful policies and monitor query performance as your dataset grows beyond 10 million rows across tenants.
For most SaaS applications with fewer than 500 tenants and moderate query complexity, RLS provides the best balance of security, operational simplicity, and cost.
Database Schema Design for Multi-Tenant Applications
Every table that holds tenant-specific data needs a tenant_id column, preferably as uuid referencing a tenants table. Avoid using integer tenant identifiers if you ever plan to merge companies or accept data imports.
Here's a minimal schema using Drizzle ORM syntax that works well with RLS:
export const tenants = pgTable("tenants", {
id: uuid("id").primaryKey().defaultRandom(),
name: text("name").notNull(),
createdAt: timestamp("created_at").defaultNow(),
});
export const projects = pgTable("projects", {
id: uuid("id").primaryKey().defaultRandom(),
tenantId: uuid("tenant_id").references(() => tenants.id).notNull(),
name: text("name").notNull(),
ownerId: uuid("owner_id").notNull(),
status: text("status").default("active"),
}, (table) => ({
tenantIdx: index("projects_tenant_idx").on(table.tenantId),
ownerIdx: index("projects_owner_idx").on(table.ownerId),
}));
The composite indexes you create depend on your access patterns. A common pattern is indexing both (tenant_id, owner_id) and (tenant_id, status) for frequent filtered queries.
Propagating Authentication Context to PostgreSQL
The most reliable way to pass user context is through session variables using set_config. In a Next.js API route or server action, wrap your database calls with a context setter.
Using the pg library directly, you can create a tenant-aware client:
async function withTenantContext<T>(
tenantId: string,
userId: string,
fn: () => Promise<T>
): Promise<T> {
const client = await pool.connect();
try {
await client.query(
`SELECT set_config('app.current_tenant_id', $1, true),
set_config('app.current_user_id', $2, true)`,
[tenantId, userId]
);
return await fn();
} finally {
client.release();
}
}
For connection pools like PgBouncer running in transaction mode, you must set these variables inside every transaction. Setting them at session level will not work reliably.
When using Drizzle, extend your database instance with middleware that injects these settings automatically:
const db = drizzle(pool, {
schema,
logger: true,
});
export async function withRLS<T>(
tenantId: string,
userId: string,
callback: (db: typeof db) => Promise<T>
) {
return db.transaction(async (tx) => {
await tx.execute(sql`
SELECT set_config('app.current_tenant_id', ${tenantId}, true),
set_config('app.current_user_id', ${userId}, true)
`);
return callback(tx);
});
}
Writing Effective RLS Policies
Start with the strictest policies. A basic tenant isolation policy for the projects table looks like this:
CREATE POLICY tenant_isolation_select ON projects
FOR SELECT
USING (tenant_id = current_setting('app.current_tenant_id')::uuid);
CREATE POLICY tenant_isolation_insert ON projects
FOR INSERT
WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);
CREATE POLICY tenant_isolation_update ON projects
FOR UPDATE
USING (tenant_id = current_setting('app.current_tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.current_tenant_id')::uuid);
For user-owned records within a tenant, add a more specific policy that takes precedence:
CREATE POLICY owner_or_admin ON projects
FOR ALL
USING (
tenant_id = current_setting('app.current_tenant_id')::uuid AND
(
owner_id = current_setting('app.current_user_id')::uuid OR
EXISTS (
SELECT 1 FROM tenant_members
WHERE tenant_id = current_setting('app.current_tenant_id')::uuid
AND user_id = current_setting('app.current_user_id')::uuid
AND role = 'admin'
)
)
);
PostgreSQL evaluates policies in order of specificity. More restrictive policies should come first. You can also use CREATE POLICY ... AS PERMISSIVE and AS RESTRICTIVE (Postgres 15+) to combine rules logically.
Integrating RLS with Drizzle ORM Queries
Drizzle does not automatically apply RLS unless you use raw SQL or the policies are enforced at the database level. The beauty of RLS is that you write normal Drizzle queries and the database filters results automatically.
However, you must ensure every query runs inside a proper tenant context. Here is a complete example of a tenant-aware service:
export class ProjectService {
async getProjects(tenantId: string, userId: string) {
return withRLS(tenantId, userId, async (tx) => {
return tx.query.projects.findMany({
where: eq(projects.status, "active"),
orderBy: desc(projects.createdAt),
limit: 50,
});
});
}
async createProject(tenantId: string, userId: string, data: InsertProject) {
return withRLS(tenantId, userId, async (tx) => {
return tx.insert(projects).values({
...data,
tenantId,
ownerId: userId,
}).returning();
});
}
}
Notice that we still pass tenantId explicitly when inserting. This provides defense in depth and makes the code more readable during code reviews.
Handling Authentication and JWT Integration
When using JWT-based authentication (Auth.js, Clerk, or Supabase), extract the tenant and user claims in your middleware. A common pattern is to include tenant_id in the JWT after a user selects or is assigned to an organization.
In Next.js middleware or route handlers, validate the token and pass the claims to your database context:
export async function GET(request: Request) {
const token = await getToken({ req: request as any });
if (!token?.tenantId || !token?.sub) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const projects = await projectService.getProjects(
token.tenantId as string,
token.sub as string
);
return NextResponse.json(projects);
}
For applications with users belonging to multiple tenants, create a separate endpoint that returns accessible tenants and requires the client to specify which tenant context to use for subsequent requests. Store the selected tenant in an HTTP-only cookie or short-lived JWT.
Performance Optimization and Indexing Strategies
RLS adds predicates to queries, which can prevent index usage if not written carefully. Always include the tenant_id column in your indexes for tables larger than a few thousand rows.
Use EXPLAIN (ANALYZE, BUFFERS) to validate query plans. A good index for the projects table when policies filter by both tenant and owner would be:
CREATE INDEX CONCURRENTLY idx_projects_tenant_owner
ON projects (tenant_id, owner_id, status);
Partial indexes can dramatically reduce index size for active records only:
CREATE INDEX idx_projects_active_tenant
ON projects (tenant_id, id)
WHERE status = 'active';
Monitor the pg_stat_statements view to find queries where RLS adds more than 15% overhead. In practice, well-indexed RLS policies add negligible overhead until you exceed several million rows per table.
Avoid using functions in policies that cannot use indexes, such as complex JSONB traversals without proper GIN indexes. When possible, extract values into dedicated columns for policy evaluation.
Testing RLS Policies Thoroughly
Manual testing with different database users is essential. Create test roles that mirror your application users:
CREATE ROLE test_tenant_user WITH LOGIN PASSWORD 'test';
GRANT SELECT, INSERT, UPDATE ON projects TO test_tenant_user;
Then run policy tests using SECURITY INVOKER views or dedicated test functions that set context variables and assert row visibility.
A practical test helper in TypeScript might look like this:
async function assertVisibleOnlyTo(
tenantId: string,
userId: string,
expectedCount: number
) {
const result = await withRLS(tenantId, userId, async (tx) => {
return tx.select({ count: count() }).from(projects);
});
if (result[0].count !== expectedCount) {
throw new Error(`Expected ${expectedCount} rows, got ${result[0].count}`);
}
}
Run these tests against a restored production-like dataset containing multiple tenants. Include tests for edge cases: users with no tenant, administrators with elevated policies, and attempts to bypass policies by manually setting session variables.
Advanced Policy Patterns
Soft deletes are common in SaaS. Combine RLS with a deleted_at column:
CREATE POLICY soft_delete_policy ON projects
USING (
deleted_at IS NULL
AND tenant_id = current_setting('app.current_tenant_id')::uuid
);
For hierarchical data such as folders, you can write recursive policies using WITH RECURSIVE queries inside the policy definition, though this impacts performance. A simpler approach is to materialize the full ancestor path in each row and filter on that array column with a GIN index.
Some teams implement "data sharing" between tenants using a separate tenant_shares table and policies that check for existence of a sharing relationship. This pattern powers marketplace and partner features without compromising core isolation.
Observability and Monitoring RLS Usage
Enable pg_stat_statements and log queries that take longer than 100ms. Look for queries containing current_setting in their plan to understand RLS impact.
Use PostgreSQL's RLS related views:
SELECT * FROM pg_policies WHERE tablename = 'projects';
SELECT * FROM pg_stat_user_tables WHERE relname = 'projects';
Tools like pgBadger can parse logs and highlight slow RLS-filtered queries. Set up alerts when the ratio of rows filtered by RLS exceeds 70% of total rows scanned, indicating missing indexes.
In Next.js, add OpenTelemetry spans around your withRLS calls to correlate database performance with specific API endpoints. This helps identify which features become slow as tenant data grows.
Migrating Legacy Applications to RLS
Adding RLS to an existing application requires careful sequencing. First add tenant_id columns with backfill scripts, then add indexes, then enable RLS with permissive policies that match current application behavior, and finally tighten policies after verifying correctness.
Use database views that expose tenant-filtered data during transition. Many teams run dual writes to both old repository methods and new RLS-protected tables until confidence is established, then cut over.
Plan for a maintenance window or use logical replication to a new schema with RLS enabled if your dataset exceeds 50GB.
Scaling Considerations for Growing SaaS Products
As your customer base grows, consider read replicas with RLS enabled. PostgreSQL 16 improved RLS performance for read-heavy workloads significantly. Use connection poolers like PgBouncer in transaction mode and ensure your withRLS helper always runs set_config inside the transaction.
For extremely high scale (thousands of tenants with heavy analytics), you may eventually split into multiple physical databases by tenant size tiers. RLS gives you time to reach that point without premature architectural decisions.
Combine RLS with PostgreSQL row-level triggers for audit logging that automatically captures the current tenant and user from session variables. This creates a complete audit trail without changing application code.
Finally, document every policy in your codebase with comments explaining the business rule it enforces. Policies become part of your security boundary and should be reviewed during security audits the same way you review authentication code.
The combination of PostgreSQL RLS, careful indexing, and a thin context propagation layer in Next.js creates a robust foundation for multi-tenant applications that can grow from prototype to millions in revenue without changing your data architecture.
