PostgreSQL row-level security

PostgreSQL Row-Level Security for Multi-Tenant SaaS

To implement PostgreSQL row-level security, add a tenant identifier to shared tables, enable RLS, and create policies that compare each row with trusted tenant context. Set that context inside every database transaction using a restricted application role.

This adds a database-enforced boundary when application code forgets a tenant filter. However, your backend still needs to authenticate users, validate tenant membership, and authorize actions.

We’ll use a shared document table to connect the schema, policies, and request handling into one practical implementation.

Key takeaways

  • Establish tenant context through server-side authorization before accessing tenant data.
  • Use separate roles for database ownership and application requests.
  • Apply both USING and WITH CHECK conditions to protect existing rows and proposed changes.
  • Keep tenant settings transaction-local so pooled connections don’t carry request context between customers.

Define the tenant boundary first

Resolve tenant identity through authorization

In this example, each SaaS workspace is a tenant. Documents share one table, but every document has a required tenant_id.

A workspace slug, URL parameter, or header can identify the workspace a caller requests. It doesn’t prove access. Authenticate the caller, resolve the workspace, and validate an active membership or service delegation.

Then construct trusted request context containing the actor, tenant, and permissions. Downstream code should consume that context rather than rereading arbitrary request fields. A person belonging to two workspaces may have different permissions in each.

Keep action permissions separate

RLS controls which rows a database role can access. Your application must still decide whether a workspace member may view, edit, or export documents.

For example, the tenant policy below permits updates within the selected workspace. It doesn’t distinguish viewers from editors.

PostgreSQL’s row security documentation also explains that policies work alongside ordinary SQL privileges. A policy doesn’t grant access that GRANT hasn’t already allowed.

Create the shared table and application role

Run this setup through a privileged administrative connection. The setup role owns the schema and table; application requests use the separate saas_app role.

CREATE ROLE saas_app
  LOGIN
  NOSUPERUSER
  NOBYPASSRLS;


CREATE SCHEMA saas;


CREATE TABLE saas.app_data (
  tenant_id uuid NOT NULL,
  id uuid NOT NULL,
  title text NOT NULL,
  PRIMARY KEY (tenant_id, id)
);


GRANT USAGE ON SCHEMA saas TO saas_app;


GRANT SELECT, INSERT, UPDATE, DELETE
  ON saas.app_data TO saas_app;

Here, app_data stores documents. Its composite primary key identifies each document within a tenant. It also makes tenant scope part of the database’s uniqueness rule.

NOSUPERUSER and NOBYPASSRLS remove two explicit bypass capabilities. However, the application role must also remain separate from the table owner and mustn’t inherit privileged roles.

Configure authentication for saas_app through your normal database credential process. Keep those credentials on the backend.

The grants permit document operations, but they don’t yet isolate tenants. Until you enable RLS and add a policy, these privileges allow access across the table.

Enable PostgreSQL row-level security

Turn on enforcement and handle ownership

Enable RLS before serving application traffic:

ALTER TABLE saas.app_data
  ENABLE ROW LEVEL SECURITY;


ALTER TABLE saas.app_data
  FORCE ROW LEVEL SECURITY;

ENABLE activates row-policy enforcement. Once enabled, a table with no applicable policy denies ordinary row access by default.

FORCE also subjects the table owner to RLS. However, superusers and roles with BYPASSRLS still bypass policies. The owner also retains control over the table’s configuration, so FORCE doesn’t make ownership safe for application requests.

Protect existing and proposed rows

Create one policy covering the application’s document operations:

CREATE POLICY tenant_isolation
ON saas.app_data
FOR ALL
TO saas_app
USING (
  tenant_id =
  NULLIF(current_setting('app.tenant_id', true), '')::uuid
)
WITH CHECK (
  tenant_id =
  NULLIF(current_setting('app.tenant_id', true), '')::uuid
);

USING determines which existing rows the application can read, update, or delete. Meanwhile, WITH CHECK validates inserted rows and the new values produced by updates.

Both expressions require the row’s tenant to match the transaction’s tenant. Therefore, changing a document’s tenant_id to another workspace fails.

The second argument to current_setting allows a missing setting to return NULL. NULLIF also treats an empty string as absent. Without valid context, the comparison doesn’t evaluate to true, so rows don’t qualify. A malformed UUID raises an error instead of granting access.

Set tenant context inside each transaction

Bind the authorized tenant before querying

After authorization, acquire a database connection and start a transaction:

BEGIN;


SELECT set_config(
  'app.tenant_id',
  '9f4e2c10-62c1-4b85-9946-8e0de2bc1900',
  true
);


SELECT tenant_id, id, title
FROM saas.app_data;


COMMIT;

The UUID represents the authorized workspace. In application code, bind that value as a query parameter rather than interpolating it into SQL.

The final true makes the setting transaction-local. PostgreSQL’s configuration function documentation describes this distinction: true limits the change to the transaction, while false changes session state.

Set context before the first tenant-owned query. Use the same connection throughout, and roll back if any operation fails.

Keep connection pools from retaining tenant state

A pooled connection can serve many customers. Session-scoped tenant settings can therefore survive long enough to affect another request.

Transaction-local settings revert when the transaction ends. However, they restore any previous setting, so never establish tenant identity at session scope elsewhere.

Also, don’t run set_config(..., true) as a standalone autocommit statement. Its transaction ends immediately, before the next query.

Setting context and querying through separate pool calls is unsafe. Both operations must use the same checked-out connection and transaction.

On errors, roll back before releasing the connection. Apply this pattern to background workers and exports too.

Understand the allowed and denied operations

Connect as saas_app for application operations. An administrative connection can bypass RLS and give misleading results.

With the tenant context established, this insert creates a document inside that workspace:

BEGIN;


SELECT set_config(
  'app.tenant_id',
  '9f4e2c10-62c1-4b85-9946-8e0de2bc1900',
  true
);


INSERT INTO saas.app_data (tenant_id, id, title)
VALUES (
  '9f4e2c10-62c1-4b85-9946-8e0de2bc1900',
  '11111111-1111-4111-8111-111111111111',
  'Workspace onboarding'
);


SELECT id, title FROM saas.app_data;


COMMIT;

The final query can return this document even though it has no explicit tenant filter. RLS supplies the row restriction.

Under a different tenant context, that document doesn’t qualify for selection. An update or delete targeting its ID affects zero rows. Attempting to insert it with a foreign tenant_id fails the policy check instead.

Likewise, changing an accessible document’s tenant fails WITH CHECK. Without tenant context, reads return no qualifying rows and inserts fail.

These outcomes distinguish filtering from rejection. An empty read or zero-row update doesn’t necessarily produce a database error. Your application must interpret the result without revealing whether another tenant owns the requested document.

For an authenticated caller, a scoped resource lookup that finds nothing can return a normal not-found response.

Close the surrounding access paths

Scope related resources and indirect reads

RLS applies per table. Protecting app_data doesn’t protect a separate folders table, audit-log table, or storage service.

If documents reference folders, include tenant scope in the relationship. Give folders a unique key on (tenant_id, id), then reference that pair through (tenant_id, folder_id). This prevents a document from referencing another workspace’s folder.

Apply the same boundary to search, counts, bulk operations, and exports. Cache keys also need tenant scope, while object-storage downloads require their own authorization.

A newly created table without RLS won’t inherit another table’s policies. Include its tenant boundary when designing the table.

Treat workers and support access explicitly

A background worker doesn’t inherit the browser request’s trusted context. Pass authorized tenant and actor information to the job, then establish a fresh database transaction.

For user-delegated work, reevaluate access when the job runs because membership may have changed. System-owned maintenance needs its own narrow permissions.

Also, remember that saas_app can set app.tenant_id. This design trusts backend authorization; it doesn’t protect against a caller who can execute arbitrary SQL using application credentials. Keep queries parameterized and never expose those credentials.

Cross-tenant support operations need a separate, explicitly authorized and audited path.

Frequently asked questions

Can I use RLS with an ORM?

Yes. The ORM’s queries still pass through PostgreSQL’s policies. However, context setup and protected queries must share one transaction-bound connection.

A transaction helper is useful only if every query uses its transaction object. Queries accidentally sent through the general connection pool may run without the intended context.

RLS also doesn’t remove the need for application permission checks. The same tenant policy can allow database updates while your application restricts viewers to reads.

Can adding another policy weaken isolation?

Yes. PostgreSQL combines applicable permissive policies with OR by default. A broad additional policy can therefore make rows accessible even when the original tenant condition doesn’t match.

Keep ordinary application access under a clear tenant rule. Treat policies granting wider access as security-sensitive changes, especially when they apply to the same role.

Also remember that an enabled table with no applicable policy denies access. A table where RLS was never enabled has no such row-policy protection.

Make tenant isolation part of every request

Reliable isolation combines trusted tenant context, restricted database roles, and policies covering reads and writes. Transaction-local settings keep that context attached to the work using it.

RLS strengthens your shared-table boundary, but application permissions and surrounding services still matter. Use the same authorized tenant throughout requests, related resources, and background jobs so alternate paths don’t bypass the protection.

About the author

The SAAS Podium

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *