Back to blog

Blog

PostgreSQL row level security (RLS): a practical guide

How PostgreSQL row level security works: enabling RLS, policy examples, who bypasses it, FORCE ROW LEVEL SECURITY, performance, and multi-tenant pitfalls.

PostgreSQLsecurityRLSmulti-tenancySaaSproductiondatabase

PostgreSQL row level security (RLS) lets the database decide which rows each role can read or change: you turn it on per table with ALTER TABLE ... ENABLE ROW LEVEL SECURITY, then add policies that act as an extra WHERE clause on every query. Superusers, roles with BYPASSRLS and, unless you also run FORCE ROW LEVEL SECURITY, the table's owner skip those policies, which is the most common way RLS silently does nothing. This guide covers policy examples, setting tenant context through a connection pooler, performance, testing, and the mistakes that leak rows.

Your application code knows which tenant owns which row. Your ORM always filters by WHERE tenant_id = $1. Your team has reviewed the queries and they look fine.

Then someone forgets the WHERE clause. Or a bulk operation skips the filter. Or a new developer writes a raw query without knowing the convention. Suddenly one tenant can read another tenant's data, and you find out from a support ticket two weeks later.

Row level security moves the tenant isolation logic inside PostgreSQL itself. Instead of trusting application code to filter every query correctly, the database enforces the policy automatically, on every access, regardless of how the query was written. You cannot accidentally return the wrong rows because the database will not give them to you.

This guide covers how RLS actually works, how to write policies that hold up in production, and the traps that catch teams who set it up without reading the fine print.

What row level security does in PostgreSQL#

RLS lets you attach policies to a table that control which rows a given database role can see or modify. The policy is a SQL expression that runs as an invisible WHERE clause on every query against that table.

Enable RLS on a table:

ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

That single command changes the default behavior: until you add a policy, roles subject to RLS see no rows. SELECT returns zero rows, UPDATE and DELETE affect nothing, and INSERT fails with a row-level security error. (Superusers, BYPASSRLS roles and the table owner are exempt; more on that below.) This is intentional and important: the safe default is deny, not permit.

Now create a policy:

CREATE POLICY documents_tenant_isolation
  ON documents
  FOR ALL
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

From this point on, any query against documents automatically filters by tenant_id. A SELECT * FROM documents that would previously return every row now returns only the rows belonging to the current tenant. No changes to your queries required.

Policy expressions: USING and WITH CHECK#

The USING clause is the row filter. It's a boolean expression that PostgreSQL appends to every query as an additional WHERE condition. If it returns true for a row, the row is visible. If it returns false or null, the row is invisible.

For writes, you also have WITH CHECK. This expression controls which rows can be written. If a write would create or modify a row that doesn't satisfy WITH CHECK, PostgreSQL raises an error.

CREATE POLICY documents_tenant_policy
  ON documents
  FOR ALL
  USING (tenant_id = current_setting('app.tenant_id')::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);

For SELECT and DELETE, only USING applies (you can only read/delete what you can see). For INSERT, only WITH CHECK applies (the row doesn't exist yet, so there's nothing to filter). For UPDATE, both apply: USING determines which rows you can update, and WITH CHECK validates the post-update state.

If you only provide USING and omit WITH CHECK on a FOR ALL or FOR UPDATE policy, PostgreSQL uses the USING expression for both. (A FOR INSERT policy takes only WITH CHECK.) This is usually what you want, but knowing the distinction saves debugging time when you have separate read and write policies.

Setting the tenant context for RLS policies#

The policy expression needs some way to know which tenant the current connection belongs to. There are two main approaches: database roles and session variables.

Session variables

Session variables are the most common approach for web applications using connection poolers. Before executing any queries for a given request, your application sets a session variable:

-- Set at connection setup time, or at the start of each transaction
SET LOCAL app.tenant_id = '550e8400-e29b-41d4-a716-446655440000';

SET LOCAL scopes the variable to the current transaction. SET (without LOCAL) scopes it to the session. For connection poolers in transaction mode, always use SET LOCAL so the variable resets when the transaction ends and the connection returns to the pool. If you use SET, a pooled connection will carry the wrong tenant_id into the next request.

Read the variable in your policy with current_setting():

USING (tenant_id = current_setting('app.tenant_id', true)::uuid)

The second argument to current_setting() is missing_ok. Pass true so the function returns null instead of raising an error when the variable isn't set. This matters during migrations, maintenance scripts, and any context where your full application setup hasn't run.

One more trap: once a session has set app.tenant_id with SET LOCAL, the setting reverts to an empty string (not null) after that transaction ends, and ''::uuid raises an error. On pooled connections, guard against it with NULLIF:

USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)

Database roles

If each tenant has their own database role, you can use current_user directly:

CREATE POLICY tenant_role_policy
  ON documents
  FOR ALL
  USING (tenant_id::text = current_user);

This is cleaner but doesn't scale to thousands of tenants. It works well for per-customer database setups or when you have a small, fixed number of roles (e.g., a public role, an admin role, an API role).

Separate RLS policies per operation#

The FOR ALL shortcut is convenient, but real applications usually need different rules for reads and writes. Break them out:

-- Anyone in the tenant can read
CREATE POLICY documents_select
  ON documents
  FOR SELECT
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);

-- Only the document owner can update
CREATE POLICY documents_update
  ON documents
  FOR UPDATE
  USING (
    tenant_id = current_setting('app.tenant_id', true)::uuid
    AND owner_id = current_setting('app.user_id', true)::uuid
  )
  WITH CHECK (
    tenant_id = current_setting('app.tenant_id', true)::uuid
    AND owner_id = current_setting('app.user_id', true)::uuid
  );

-- Members can insert rows for their own tenant only
CREATE POLICY documents_insert
  ON documents
  FOR INSERT
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);

When multiple policies apply to the same operation, they combine with OR by default. This is the permissive policy model: if any policy grants access, the row is accessible. Keep this in mind when stacking policies. If you intend to restrict access rather than expand it, use AS RESTRICTIVE:

CREATE POLICY require_active_tenant
  ON documents
  AS RESTRICTIVE
  FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM tenants
      WHERE id = current_setting('app.tenant_id', true)::uuid
        AND status = 'active'
    )
  );

A restrictive policy combines with AND against all other policies. The row is only visible if it passes the restrictive policy AND at least one permissive policy. Use restrictive policies for blanket rules that should always apply regardless of other grants.

Who bypasses row level security#

Two categories of users bypass RLS entirely:

Superusers. Any role with SUPERUSER bypasses RLS. This is why your application should never connect as a superuser. Create a dedicated application role with only the permissions it needs.

Roles with BYPASSRLS. You can grant this attribute explicitly:

ALTER ROLE admin_role BYPASSRLS;

This is useful for admin tooling, analytics queries, and migration scripts that need to operate across all tenants. Treat it with the same care as superuser access.

To see which roles bypass RLS on your cluster:

SELECT rolname, rolbypassrls FROM pg_roles WHERE rolbypassrls = true;

Table owners also bypass RLS by default unless you force it:

ALTER TABLE documents FORCE ROW LEVEL SECURITY;

Without FORCE ROW LEVEL SECURITY, the table owner's queries skip all policies. (FORCE does not affect superusers or BYPASSRLS roles; they always bypass.) If your application connects as the same role that owns the tables (a common setup with ORMs), your RLS policies do nothing. This is the most common RLS gotcha. Always either:

  1. Use FORCE ROW LEVEL SECURITY, or
  2. Have your application connect as a non-owner role

Row level security performance#

The obvious question: does adding a WHERE condition to every query slow things down?

The honest answer: sometimes, and it depends entirely on your policy expression and whether PostgreSQL can use an index for it.

A policy on tenant_id works well when you have an index on that column:

CREATE INDEX idx_documents_tenant_id ON documents (tenant_id);

With this index, the RLS filter is just an index lookup. The performance overhead is negligible. Without the index, every query does a full table scan filtered by tenant, which gets expensive as the table grows.

Check that the planner is using the index:

BEGIN;
SET LOCAL app.tenant_id = '550e8400-e29b-41d4-a716-446655440000';

EXPLAIN ANALYZE SELECT * FROM documents WHERE title ILIKE '%invoice%';
ROLLBACK;

SET LOCAL only works inside a transaction block; outside one, PostgreSQL ignores it with a warning. You should see the tenant_id condition as the Index Cond and your own predicate as a Filter:

Index Scan using idx_documents_tenant_id on documents
  (cost=0.42..8.45 rows=1 width=256)
  (actual time=0.031..0.058 rows=3 loops=1)
  Index Cond: (tenant_id = '550e8400...'::uuid)
  Filter: (title ~~* '%invoice%')

If you see a Seq Scan, you're missing the index. A partial index on tenant_id for active tenants can also help if inactive tenant data is large and rarely queried.

For policies that query other tables, watch the query plan carefully. A correlated subquery (one that references the row being checked, such as a membership lookup on documents.tenant_id) can run once per row, which can kill performance on large tables. An uncorrelated check like require_active_tenant above usually runs once per query, but confirm it in EXPLAIN. When a check is expensive, materialize it in a session variable instead:

-- Check tenant status in application code, then set a verified flag
SET LOCAL app.tenant_verified = 'true';

-- Use the flag in the policy instead of a subquery
USING (
  tenant_id = current_setting('app.tenant_id', true)::uuid
  AND current_setting('app.tenant_verified', true) = 'true'
)

Testing RLS policies#

The cleanest way to test is to run queries as the role that will actually be using the policies:

BEGIN;
SET LOCAL ROLE app_user;
SET LOCAL app.tenant_id = '550e8400-e29b-41d4-a716-446655440000';

-- Should only return rows for this tenant
SELECT count(*) FROM documents;

-- Should report UPDATE 0: other tenants' rows are invisible
UPDATE documents SET title = 'hacked' WHERE tenant_id != current_setting('app.tenant_id', true)::uuid;

-- Should fail with a row-level security error
INSERT INTO documents (tenant_id, owner_id, title)
VALUES (gen_random_uuid(), gen_random_uuid(), 'wrong tenant');

ROLLBACK;

The failed INSERT aborts the transaction, which is fine here because the test ends in ROLLBACK anyway.

Test the boundary conditions:

  • What happens when app.tenant_id is not set? (It should return zero rows or error cleanly.)
  • Can tenant A read tenant B's rows? (It should not.)
  • Does the table owner bypass the policy? (It will unless you use FORCE ROW LEVEL SECURITY.)

Write these as automated tests in your test suite, not just manual spot checks. RLS policies are easy to accidentally break with schema changes.

RLS with connection pooling (PgBouncer)#

If you're using PgBouncer in transaction mode (which most production setups should), RLS with session variables works well, but there is one critical rule: always use SET LOCAL to set tenant context, never SET.

SET LOCAL rolls back automatically when the transaction ends. SET persists for the lifetime of the session. In transaction mode, a session is shared across many clients. If you SET app.tenant_id and don't reset it, the next client that gets that connection from the pool will inherit your tenant context.

The safe pattern:

BEGIN;
SET LOCAL app.tenant_id = '550e8400-e29b-41d4-a716-446655440000';
SET LOCAL app.user_id = 'a1b2c3d4-...';
-- your application queries here
COMMIT;

See our guide to PostgreSQL connection pooling with PgBouncer for more detail on pool modes and what can go wrong in session mode.

RLS in multi-tenant SaaS architecture#

Row Level Security is one piece of a multi-tenant data isolation strategy. Here's how it fits with the other pieces:

Schema isolation (one schema per tenant) gives complete isolation but doesn't scale to thousands of tenants and makes migrations painful. Good for small numbers of large enterprise customers.

Database isolation (one database per tenant) is the strongest model but expensive to operate and hard to query across tenants. Rare in practice.

RLS isolation (shared schema, policies enforce tenant boundaries) scales to large numbers of tenants with little overhead if your indexes are right. It is the usual choice for SaaS with many small tenants.

For the shared schema approach with RLS, the typical setup looks like this:

-- All tenants share the same tables
CREATE TABLE tenants (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'active'
);

CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id),
  email TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'member'
);

CREATE TABLE documents (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id),
  owner_id UUID NOT NULL REFERENCES users(id),
  title TEXT NOT NULL,
  content TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE users FORCE ROW LEVEL SECURITY;
ALTER TABLE documents FORCE ROW LEVEL SECURITY;

-- Create application role (non-owner, non-superuser)
CREATE ROLE app_user LOGIN PASSWORD 'change-me';
GRANT SELECT, INSERT, UPDATE, DELETE ON users, documents TO app_user;
GRANT USAGE ON SCHEMA public TO app_user;

-- Policies
CREATE POLICY users_tenant_isolation ON users
  FOR ALL
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);

CREATE POLICY documents_tenant_isolation ON documents
  FOR ALL
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);

-- Indexes
CREATE INDEX idx_users_tenant_id ON users (tenant_id);
CREATE INDEX idx_documents_tenant_id ON documents (tenant_id);

Your application connects as app_user, sets app.tenant_id at the start of each transaction, and every query is automatically scoped. You get the simplicity of a single shared schema with the security of enforced isolation.

Inspecting existing RLS policies#

You can see all policies on a table in psql with \d table_name or query the catalog directly:

SELECT
  schemaname,
  tablename,
  policyname,
  permissive,
  roles,
  cmd,
  qual,
  with_check
FROM pg_policies
WHERE tablename = 'documents';

To see which tables have RLS enabled:

SELECT
  relname AS table_name,
  relrowsecurity AS rls_enabled,
  relforcerowsecurity AS rls_forced
FROM pg_class
WHERE relkind = 'r'
  AND relnamespace = 'public'::regnamespace
ORDER BY relname;

Common row level security mistakes#

Not enabling FORCE ROW LEVEL SECURITY. If your app connects as the table owner, policies are silently bypassed. Always set this or use a non-owner role.

Using SET instead of SET LOCAL with connection poolers. Tenant context leaks between clients. Always use SET LOCAL inside a transaction.

Missing the index on tenant_id. Your policy runs as a filter on every query. Without an index, this means a full table scan on every request.

Treating superuser connections as safe. Superusers bypass RLS completely. If your migration tool, analytics query, or admin panel connects as a superuser, it's operating outside your security model. That might be intentional, but make it explicit.

Not testing cross-tenant access. Write a test that explicitly tries to access another tenant's data and verifies it fails. Don't assume the policy is correct because it looks right.

RLS on managed PostgreSQL#

If you're running PostgreSQL yourself, you control the roles, the connection setup, and the policy lifecycle. But managing that infrastructure also means managing the security of the infrastructure itself: who has superuser access, how credentials rotate, how you audit policy changes.

None of this is tied to one vendor. RLS is the isolation model Supabase is built around, which is where a lot of teams first run into it, but the policies are plain PostgreSQL. If you adopted RLS through Supabase and want to run it on dedicated infrastructure, Rivestack is a Supabase alternative where the same tenant_id policies from this guide run unchanged on managed PostgreSQL.

On Rivestack, RLS policies are part of your schema and deploy with your migrations. The platform handles the underlying access controls, connection pooling configuration, and credential management, so you can focus on writing the policies that matter for your application rather than the operational scaffolding around them. The same isolation guarantees apply whether you're on Solo with a handful of tenants or scaling to millions of rows.

If you're building a multi-tenant PostgreSQL application, these posts cover the other pieces of the puzzle:

FAQ#

What is row level security in PostgreSQL?

Row level security (RLS) is a PostgreSQL feature that filters which rows a role can see or modify, using policies attached to a table. Each policy is a SQL expression that PostgreSQL adds to every query on that table, so the restriction holds even when application code forgets a WHERE clause.

How do I enable row level security in Postgres?

Run ALTER TABLE documents ENABLE ROW LEVEL SECURITY, then create at least one policy, for example CREATE POLICY tenant_isolation ON documents USING (tenant_id = current_setting('app.tenant_id', true)::uuid). Add ALTER TABLE documents FORCE ROW LEVEL SECURITY if your application connects as the table owner. Until a policy exists, roles subject to RLS see no rows.

What does a Postgres policy example look like?

A typical multi-tenant policy is CREATE POLICY documents_tenant ON documents FOR ALL USING (tenant_id = current_setting('app.tenant_id', true)::uuid) WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid). USING filters the rows you can read, update or delete, and WITH CHECK validates rows you insert or update. The application sets app.tenant_id with SET LOCAL at the start of each transaction.

Who can bypass row level security in Postgres?

Superusers, roles with the BYPASSRLS attribute, and the table owner. The owner stops bypassing once you run ALTER TABLE ... FORCE ROW LEVEL SECURITY; superusers and BYPASSRLS roles always bypass. Run SELECT rolname FROM pg_roles WHERE rolsuper OR rolbypassrls to see which roles skip your policies.

How do I disable row level security?

Run ALTER TABLE documents DISABLE ROW LEVEL SECURITY. The policies stay defined but are no longer applied, so every role with table privileges sees every row; ENABLE turns them back on. For admin or migration jobs that need all rows, prefer a separate role with BYPASSRLS over disabling RLS on the table. Setting row_security to off does not bypass anything: it makes queries that RLS would filter raise an error instead.

What does FORCE ROW LEVEL SECURITY do?

It makes the table owner subject to the table's policies too. By default the owner bypasses RLS, so an application that connects as the role that owns its tables (common with ORMs and migration tools) gets no protection at all. FORCE closes that gap; it does not affect superusers or BYPASSRLS roles.

Does row level security slow down queries?

Not much, if the policy can use an index. A policy on tenant_id with an index on tenant_id turns into an index condition, the same as writing the WHERE clause yourself. It gets slow when there is no index for the policy column, or when the policy runs a correlated subquery per row. Check with EXPLAIN ANALYZE inside a transaction that sets your tenant context.

What are the disadvantages of row level security?

Policies are invisible in application queries, so slow plans and empty results can be harder to debug. Superusers, BYPASSRLS roles and table owners without FORCE skip them, which makes misconfiguration easy. Tenant context needs care with connection poolers (SET LOCAL, not SET). And policies with subqueries can hurt performance. None of these is a reason to avoid RLS, but each needs a test.

Is row level security a good fit for multi-tenant SaaS?

Yes, for the common shared-schema model where many tenants live in the same tables. Every tenant-scoped table gets a tenant_id column, an index on it and a policy, and the application sets the tenant once per transaction. Schema-per-tenant or database-per-tenant gives stronger isolation for a few large customers, at a higher operational cost.

Does PostgreSQL support column level security?

Yes, through column privileges rather than RLS. GRANT SELECT (id, title) ON documents TO app_user lets that role read only the listed columns, and a query that touches any other column fails with a permission error. RLS controls rows and column grants control columns, so you can combine them. A view that exposes only some columns is another option.

Is there a CREATE POLICY IF NOT EXISTS in Postgres?

No. CREATE POLICY has no IF NOT EXISTS clause. In migrations, run DROP POLICY IF EXISTS documents_tenant ON documents and then CREATE POLICY in the same transaction, or wrap CREATE POLICY in a DO block that first checks pg_policies for the policy name.

Keep reading