PostgreSQL Row-Level Security for Multi-Tenant Apps: Pitfalls That Break Isolation

In a shared-schema multi-tenant application, every query must include WHERE tenant_id = ?. Miss it once, in a new report, an admin export or a hastily written background job, and one customer sees another customer's data. PostgreSQL's Row-Level Security (RLS) adds a second line of defence: the database itself filters rows by tenant, so a query that forgets the condition returns nothing instead of everything.
This guide sets up tenant isolation with RLS and covers the three details that silently break it in real applications: table owners bypass policies by default, session settings leak between requests on pooled connections, and an empty setting can turn every query into an error. Each behaviour described here was checked against PostgreSQL 16.
Understanding Row-Level Security (RLS) Fundamentals
Before diving into the implementation, let's briefly understand the core concepts:
- Policies: These are the rules that define who can access what rows. They are associated with specific tables and apply to different command types (SELECT, INSERT, UPDATE, DELETE).
- Enabling RLS: RLS is not enabled by default on tables. You must explicitly enable it for each table where you want to apply policies.
USINGandWITH CHECKclauses:USINGclauses determine which rows are visible or eligible for an operation (SELECT, UPDATE, DELETE).WITH CHECKclauses determine which rows can be inserted or updated into a table. If a row being inserted or updated does not satisfy theWITH CHECKcondition, the operation is rejected, even if the user has privileges to perform the operation.
For multi-tenancy, policies compare each row's tenant_id with a custom setting (app.tenant_id) that the application sets for the current request.
Setting It Up
Let's walk through a practical example of setting up RLS for a multi-tenant application. We'll assume a simple e-commerce scenario where products belong to tenants.
Step 1: Set Up Your Multi-Tenant Schema
Use two database roles: one that owns the tables and runs migrations, and a separate, less privileged role that the application connects as. This separation matters for RLS, as Step 2 explains.
-- Run as the owner/migration role. The application connects as app_user.
CREATE ROLE app_user WITH LOGIN PASSWORD 'change-me';
-- Create the tenants table
CREATE TABLE tenants (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name VARCHAR(255) NOT NULL UNIQUE
);
-- Create the products table
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id),
name VARCHAR(255) NOT NULL,
price NUMERIC(10, 2) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Every policy filters on tenant_id, so index it (usually as the leading column)
CREATE INDEX products_tenant_id_idx ON products (tenant_id);
-- Grant privileges to the app_user
-- Replace 'your_database_name' with your actual database name
GRANT CONNECT ON DATABASE your_database_name TO app_user;
GRANT USAGE ON SCHEMA public TO app_user;
GRANT SELECT ON tenants TO app_user;
GRANT SELECT, INSERT, UPDATE, DELETE ON products TO app_user;
-- Insert some sample tenants
INSERT INTO tenants (id, name) VALUES
('a1b2c3d4-e5f6-7890-1234-567890abcdef', 'Acme Corp'),
('b1c2d3e4-f5a6-8901-2345-67890abcdef0', 'Globex Inc');
-- Insert products for different tenants
INSERT INTO products (tenant_id, name, price) VALUES
('a1b2c3d4-e5f6-7890-1234-567890abcdef', 'Acme Rocket Skates', 99.99),
('a1b2c3d4-e5f6-7890-1234-567890abcdef', 'Acme Invisible Paint', 49.50),
('b1c2d3e4-f5a6-8901-2345-67890abcdef0', 'Globex Teleporter', 1999.00),
('a1b2c3d4-e5f6-7890-1234-567890abcdef', 'Acme Giant Magnet', 75.00);Step 2: Enable RLS on the Target Table
RLS is off until you enable it for each table. Also force it:
ALTER TABLE products ENABLE ROW LEVEL SECURITY;
ALTER TABLE products FORCE ROW LEVEL SECURITY;Without FORCE, the table's owner isn't subject to its policies. In testing, the owner role saw every tenant's rows with RLS enabled and no tenant set at all, and saw none once FORCE was added. If your application connects as the same role that ran the migrations (very common in frameworks with a single database user), RLS does nothing for it unless the table is forced. Superusers and roles with the BYPASSRLS attribute always bypass policies, so the application role must be neither.
Step 3: Create RLS Policies
The policy compares tenant_id with the app.tenant_id setting. Write the comparison so that a missing or empty setting matches no rows, rather than raising an error:
-- Policy for SELECT, UPDATE, DELETE, and INSERT operations for app_user
-- Ensures app_user can only see/modify/insert products belonging to the current session's tenant_id
CREATE POLICY tenant_isolation_policy ON products
FOR ALL
TO app_user
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
-- Cross-tenant jobs (billing, analytics) should use a separate role,
-- not a weakened policy on app_user:
-- CREATE ROLE reporting_user LOGIN BYPASSRLS;FOR ALL: This policy applies toSELECT,INSERT,UPDATE, andDELETEcommands.TO app_user: The policy applies to theapp_userrole. You can specifyPUBLICor other roles.USING (...): rows are visible only whentenant_idequals the current setting. The second argument tocurrent_setting(..., true)returnsNULLinstead of an error if the setting has never been defined in the session. But once it has been set and then reset, it returns an empty string, and''::uuidfails with invalid input syntax for type uuid, on every query, for every request on that connection.NULLIF(..., '')turns both cases intoNULL, andtenant_id = NULLmatches nothing.WITH CHECK (...): new or updated rows must belong to the current tenant, so code can't insert a row for another tenant or move a row to one.
💡 Pro Tip: While
FOR ALLis convenient for identical read/write rules, consider creating separate policies for different command types (e.g.,FOR SELECT,FOR INSERT) if your access rules vary significantly between operations. ForINSERTandUPDATE, theWITH CHECKclause is particularly important to prevent users from inserting or changingtenant_idto a value outside their scope.
Step 4: Configure Application Context
The application sets app.tenant_id at the start of each request. Two details decide whether this is safe:
Use set_config(), not SET. SET doesn't accept bind parameters (SET app.tenant_id = $1 is a syntax error), which tempts people into string concatenation and SQL injection. set_config() is an ordinary function, so it takes parameters:
// Laravel middleware (runs after authentication)
public function handle(Request $request, Closure $next)
{
DB::select("SELECT set_config('app.tenant_id', ?, false)", [$request->user()->tenant_id]);
try {
return $next($request);
} finally {
// Clear it so the next request on this connection starts with no tenant
DB::select("SELECT set_config('app.tenant_id', '', false)");
}
}Account for connection reuse. A session-level setting stays on the connection after the request ends. With persistent connections, long-running workers (queues, Laravel Octane), or a pooler, the next request on that connection inherits the previous tenant unless you clear it, as the finally block does. With PgBouncer in transaction pooling mode, consecutive statements may run on different server connections, so session settings don't work at all. Wrap each unit of work in a transaction and use the transaction-local form, set_config('app.tenant_id', ?, true) (equivalent to SET LOCAL), which PostgreSQL discards automatically at COMMIT or ROLLBACK.
Step 5: Test Your RLS Implementation
Connect as a superuser to see the full dataset, then as app_user:
-- Connect as superuser (e.g., 'postgres' user)
-- You should see all products
SELECT * FROM products;
-- (Expected: All 4 products from both Acme and Globex)
-- Now, connect as 'app_user'
-- psql -U app_user -d your_database_name
-- No tenant set yet
SELECT * FROM products;
-- (Expected: 0 rows)
-- Set the tenant_id for Acme Corp
SET app.tenant_id = 'a1b2c3d4-e5f6-7890-1234-567890abcdef';
SELECT * FROM products;
-- (Expected: Only Acme Corp's 3 products)
-- Now, let's try to insert a product for Globex Inc (from Acme's session)
INSERT INTO products (tenant_id, name, price) VALUES
('b1c2d3e4-f5a6-8901-2345-67890abcdef0', 'Illegal Product for Globex', 1.00);
-- ERROR: new row violates row-level security policy for table "products"
-- (Success! The WITH CHECK clause prevents inserting data for a different tenant)
-- Let's try inserting a product for Acme (from Acme's session)
INSERT INTO products (id, tenant_id, name, price) VALUES
(gen_random_uuid(), 'a1b2c3d4-e5f6-7890-1234-567890abcdef', 'Acme Test Item', 10.50);
-- INSERT 0 1 (Success!)
-- Verify Acme's products now include the new item
SELECT name FROM products;
-- (Expected: Acme Rocket Skates, Acme Invisible Paint, Acme Giant Magnet, Acme Test Item)
-- Now, change to Globex Inc's tenant_id and verify
SET app.tenant_id = 'b1c2d3e4-f5a6-8901-2345-67890abcdef0';
SELECT * FROM products;
-- (Expected: Only Globex Inc's 1 product)
-- Try inserting for Globex Inc (from Globex's session)
INSERT INTO products (id, tenant_id, name, price) VALUES
(gen_random_uuid(), 'b1c2d3e4-f5a6-8901-2345-67890abcdef0', 'Globex Spaceship', 1000000.00);
-- INSERT 0 1 (Success!)
SELECT name FROM products;
-- (Expected: Globex Teleporter, Globex Spaceship)Keep the explicit WHERE tenant_id = ? conditions in application queries as well. They let the planner use tenant indexes predictably and make intent obvious to readers. RLS is the safety net underneath, not a replacement.
⚠️ Common mistake: Testing RLS as the table owner or a superuser, seeing correct-looking results, and shipping. Superusers bypass RLS entirely, and owners bypass it unless the table is forced. Always test as the exact role the application uses in production. An automated test that queries with no tenant set and asserts zero rows catches most misconfigurations.
💡 Tip: List tables that still lack RLS with
SELECT relname FROM pg_class WHERE relkind = 'r' AND relnamespace = 'public'::regnamespace AND NOT relrowsecurity;and run it in CI, so a new tenant-scoped table can't ship without a policy.
Summary
- Enable and force RLS on every tenant-scoped table, and connect the application with a role that isn't the owner, a superuser or
BYPASSRLS. - Write policies that fail closed:
NULLIF(current_setting('app.tenant_id', true), '')so a missing or empty setting matches no rows instead of erroring. IncludeWITH CHECKfor writes. - Set the tenant with
set_config()and a bound parameter, clear it after each request, and use the transaction-local form behind transaction-pooling proxies. - Test as the production application role, including the no-tenant case, and index
tenant_id.
