You turn on row-level policies in PostgreSQL, add a tenant_id filter, open the app—and every customer's records show up in the feed. There are no errors in the logs. Your app is connecting as the table owner, and for the owner, RLS protection is disabled by default.
When tenant boundaries rely only on WHERE tenant_id = $1 in app code and middleware, a single forgotten filter or a direct JOIN from the comments service into the billing table breaks isolation. It's far safer to build two defense layers inside the database itself: split modules into separate schemas and configure Row-Level Security (RLS) without the usual loopholes.
First line of defense: separate schemas and roles instead of one shared pot
Picture a modular monolith sharing one PostgreSQL instance: billing and comments live side by side. As long as tables sit in public and modules share one database user, nothing stops a developer from writing a direct JOIN across module boundaries.
Separate schemas enforce a hard wall: each module gets its own schema and role in the same database. Transactions and backups stay simple, yet PostgreSQL blocks one module from even seeing another module's tables.
-- Separate schemas and roles for billing and comments modules
CREATE SCHEMA billing;
CREATE SCHEMA comments;
CREATE ROLE billing_app LOGIN PASSWORD 'strong_billing_pass';
CREATE ROLE comments_app LOGIN PASSWORD 'strong_comments_pass';
-- Lock down public by default and grant targeted access
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA billing TO billing_app;
GRANT USAGE ON SCHEMA comments TO comments_app;
-- comments_app physically cannot JOIN against billing.*
Now an accidental SELECT from the comments module against billing tables immediately fails with permission denied. To make this setup work cleanly with RLS, split responsibilities across three roles:
| Role | Table owner | BYPASSRLS | Purpose |
|---|---|---|---|
migrator | Yes | No | DDL migrations; the app never uses this role |
comments_app | No | No | Comments module queries enforced by RLS |
backup_role | No | Yes | Full backups via pg_dump |
Application code can no longer alter table structures or bypass policies, while backups still capture the entire database cleanly.
Basic RLS and four permission traps
Now let's drop down to the row level in a multi-tenant comments.items table holding comments for different customers (tenant_id). RLS automatically appends policy conditions to every SELECT, INSERT, UPDATE, and DELETE, but four traps catch teams right at the start.
First: the table owner. If your app connects as the role that created the table, policies are ignored. FORCE ROW LEVEL SECURITY forces PostgreSQL to enforce rules even for the owner. Superusers and roles with BYPASSRLS still skip policies, so keep NOBYPASSRLS on app roles and never make them table owners.
Second: deny-by-default. After running ENABLE ROW LEVEL SECURITY with no policies yet, regular roles cannot read or write any rows—a handy safety net when rolling out new tables. Also revoke TRUNCATE and REFERENCES separately, because neither obeys RLS.
Third: passing tenant_id through the session. The app sets it at the start of a transaction with SET LOCAL, and policies read current_setting('app.tenant_id', true). Using LOCAL resets the value on COMMIT or ROLLBACK. With a plain SET behind a connection pooler like PgBouncer in transaction mode, one tenant's ID can leak into the next request. Also remember that the database trusts this setting: if you let a user run arbitrary SQL inside a transaction, they can overwrite it with another SET LOCAL.
Fourth: views. By default, a view checks permissions and RLS as its creator, not the caller. If the migrator role created comments.public_items, a query run by comments_app will expose rows from every tenant. Since PostgreSQL 15, CREATE VIEW supports WITH (security_invoker = true), which switches the check to the calling role.
-- Enable RLS and block bypass even for the table owner
ALTER TABLE comments.items ENABLE ROW LEVEL SECURITY;
ALTER TABLE comments.items FORCE ROW LEVEL SECURITY;
-- Make the view respect the caller's RLS policies (PG 15+)
CREATE VIEW comments.public_items
WITH (security_invoker = true) AS
SELECT id, body, created_at FROM comments.items;
-- Pass tenant context strictly inside a transaction
BEGIN;
SET LOCAL app.tenant_id = '550e8400-e29b-41d4-a716-446655440000';
SET LOCAL app.account_active = 'true';
SELECT id, body FROM comments.public_items;
COMMIT;
This keeps context from leaking across pooled connections and stops views from becoming a silent backdoor around policies.
Policy logic and why queries slow down
One rule for every operation is rarely enough. In comments.items, users read all comments in their tenant, but can only edit or delete their own. In CREATE POLICY, you split rules by command (FOR SELECT, FOR INSERT, FOR UPDATE, FOR DELETE): USING filters existing rows, while WITH CHECK validates new values on writes.
Cinematic architectural model with transparent multi-layered partitions illustrating schema isolation and strict Row-Level Security access control in PostgreSQL
Regular policies (AS PERMISSIVE) combine with OR: matching any single policy grants access. If someone later adds a permissive rule for support staff, it could override your baseline restrictions. For mandatory rules like "account must be active", use AS RESTRICTIVE—these combine with AND and always apply. It's also a great place for expiration checks (expires_at IS NULL OR expires_at > now()), so temporary links and trials expire automatically without a cron job.
If you write current_setting('app.tenant_id', true)::uuid directly in a policy, the planner may evaluate the function on every single row. Wrap it in a scalar subquery (SELECT ...) so PostgreSQL lifts it into an InitPlan and runs it once per query.
-- Read all tenant comments while caching tenant_id per query
CREATE POLICY tenant_read ON comments.items
AS PERMISSIVE FOR SELECT TO comments_app
USING (
tenant_id = (SELECT current_setting('app.tenant_id', true)::uuid)
);
-- Update only your own rows within your tenant_id
CREATE POLICY author_update ON comments.items
AS PERMISSIVE FOR UPDATE TO comments_app
USING (
tenant_id = (SELECT current_setting('app.tenant_id', true)::uuid)
AND author_id = (SELECT current_setting('app.user_id', true)::uuid)
)
WITH CHECK (
tenant_id = (SELECT current_setting('app.tenant_id', true)::uuid)
);
-- Mandatory rule (AND): active account + valid access window
CREATE POLICY active_not_expired ON comments.items
AS RESTRICTIVE FOR ALL TO comments_app
USING (
(SELECT current_setting('app.account_active', true)) = 'true'
AND (expires_at IS NULL OR expires_at > now())
);
After deploying policies, check your queries with EXPLAIN ANALYZE: without an index on tenant_id and the (SELECT ...) wrapper, the filter can easily degrade into a full Seq Scan.
Production edge cases: UNIQUE, recursion, and pg_dump
Three more subtle issues tend to surface in production.
First is a covert channel leak through integrity constraints. UNIQUE, PRIMARY KEY, and FOREIGN KEY always bypass RLS. With a global UNIQUE (email), tenant B can try to register ceo@competitor.com, hit a duplicate-key error, and learn that the competitor is already on your platform—even without seeing the row. When logins are scoped per tenant, switch the index to a composite UNIQUE (tenant_id, email).
Second is policy recursion across linked tables. If a policy on comments.items checks membership in comments.org_members, and org_members has a policy that queries back, the database enters infinite recursion. Break the loop with a CREATE FUNCTION marked SECURITY DEFINER, and always lock SET search_path so nobody can hijack operators via temporary objects in pg_temp.
-- Break policy recursion with SECURITY DEFINER + fixed search_path
CREATE FUNCTION comments.is_member(p_org uuid)
RETURNS boolean LANGUAGE sql STABLE
SECURITY DEFINER
SET search_path = pg_catalog, comments AS $$
SELECT EXISTS (
SELECT 1 FROM comments.org_members
WHERE org_id = p_org
AND user_id = current_setting('app.user_id', true)::uuid
);
$$;
Fixing search_path guarantees the function resolves against the system catalog and the comments schema rather than a spoofed temporary table.
Third is backups. pg_dump sets row_security = off by default: if the backup role lacks BYPASSRLS or superuser rights, the dump fails with an error instead of silently skipping hidden rows. Use a dedicated BYPASSRLS role for full backups, or pass --enable-row-security together with --inserts for a partial RLS-filtered dump (standard COPY FROM doesn't support RLS on restore).
# A role without BYPASSRLS fails instead of producing an incomplete dump
pg_dump -U comments_app mydb > backup.sql
# Partial dump under RLS requires the flag and INSERT format
pg_dump -U comments_app --enable-row-security \
--inserts mydb > partial.sql
Run a quick check on staging before shipping to production—it's much nicer than discovering security_invoker or SET LOCAL during an incident review.
Isolation checklist before going to production
- Modules live in separate schemas,
publicaccess is revoked, and roles only see their own schemas. - App connects without table ownership or
BYPASSRLS; bothENABLEandFORCE ROW LEVEL SECURITYare on. -
app.tenant_idis set viaSET LOCALinside a transaction and wrapped in(SELECT current_setting(...)). - Views use
WITH (security_invoker = true)(PG 15+);TRUNCATEandREFERENCESare revoked. - Mandatory rules use
AS RESTRICTIVE, andSECURITY DEFINERfunctions lockSET search_path. - Global
UNIQUEconstraints,EXPLAIN ANALYZEplans with atenant_idindex, andpg_dumpunder both roles are verified.

