PostgreSQL row-level security for multi-tenant applications

Row-level security can isolate tenants inside shared PostgreSQL tables, but only if policies default to deny and privileged roles cannot silently bypass them. This page covers how to design, configure and test those policies before go-live.

On this page

PostgreSQL row-level security for multi-tenant applications: when teams need it

Row-level security enforces per-row visibility inside the database itself, so a query only returns or modifies rows that a policy allows for the current session. If your SaaS product or segregated dataset keeps many tenants in shared tables inside one PostgreSQL database, RLS is the control that stops a forgotten WHERE tenant_id = ... clause in one application query from exposing another customer's rows. It fits best when tenants share tables for cost, migration simplicity or reporting reasons. Schema-per-tenant or database-per-tenant designs give stronger physical separation and simpler per-tenant backups, but they multiply migrations and connections. The tenancy trade-offs are covered in the sibling topic on multi-tenant SaaS on PostgreSQL, so decide that model first and then decide whether RLS is the right isolation layer for it.

RLS is one layer, not a replacement for application authorization. Your application still has to decide which user may perform which action, handle sign-in, and pass the correct tenant context to the database for each request. RLS then enforces that decision at the data layer, so a bug in one endpoint does not automatically become a cross-tenant read. Confirm with your own security team which application checks remain authoritative, and document how the tenant identifier reaches the database session, because policies are only as trustworthy as that value.

Before committing to RLS, check two things in your environment. First, confirm which database roles your application connects as, since table owners and roles with the BYPASSRLS attribute skip policies unless you change that, and those exemptions are a common source of leaks. Second, confirm that your migration, reporting and backup jobs can run under roles that respect the intended policies. If those roles cannot be separated cleanly, RLS alone will not give the isolation your customers or auditors expect, and a schema-per-tenant design may be the simpler choice.

How a query passes through row-level security policies

The path starts at the application connection, where the tenant identifier is set as a session setting before any query runs. The database then checks the connected role: an ordinary role has policies applied, while table owners and roles with BYPASSRLS skip them unless FORCE ROW LEVEL SECURITY is set. Where policies apply, each SELECT, INSERT, UPDATE and DELETE is filtered or checked against the tenant key, and a non-matching row is either hidden or rejected. Check the exempt paths first, because they are where tenant data most often leaks.

Ordinary roles pass through policy checks, while owner and BYPASSRLS paths bypass them.

How default-deny policies are designed

Row-level security makes PostgreSQL filter rows on every query, so the design work is deciding what the database refuses by default and who is allowed through. The cards below cover the building blocks and the checks that keep tenant data separated once the application is live.

Enable RLS on each table

Row-level security is switched on per table with ALTER TABLE ... ENABLE ROW LEVEL SECURITY. Until it is enabled, policies on that table have no effect, so every tenant-scoped table needs an explicit entry in the migration checklist. Confirm the list against the schema, including tables added later by other teams, because a missed table is a silent gap.

Authentication methods

Hidden rows without a permissive policy

When RLS is enabled and no permissive policy applies to a command, the table returns no rows for that role. This is the default-deny behavior multi-tenant designs rely on: a new role or a forgotten policy shows nothing rather than everything. Test this explicitly by querying as an ordinary application role with no policy match and confirming zero rows come back.

USING and WITH CHECK clauses

The USING expression filters rows that can be read, updated or deleted. The WITH CHECK expression validates rows that are inserted or written, so a tenant cannot move a row into another tenant's scope. Write both for tenant-scoped tables, and review that the same tenant predicate appears in each so an update cannot change the tenant key to a foreign value.

Tenant ID from session settings or a function

The tenant identifier is usually set per connection with a custom setting such as app.tenant_id, read in policies with current_setting, or derived by a SQL function that checks the authenticated user. Session settings are simple but must be set on every request and reset when connections are pooled, so verify how your pooler and application handle them before go-live.

Separate policies for each command

Policies can be written for SELECT, INSERT, UPDATE, DELETE or ALL. Separate policies make it clear which operations each role may perform, for example allowing reads for all tenant members but writes only for administrators. Keep the command list explicit in review, since a broad ALL policy can grant more than the team intends.

Indexable predicates

Policy expressions run on every query, so a predicate that cannot use an index turns each lookup into a wider scan. Keep the tenant comparison simple, such as an equality on a tenant column with a matching index, and check query plans with and without RLS. Ask the team to confirm that the tenant column leads the composite indexes used by hot queries.

Which RLS configuration fits which tenancy and risk profile

This table compares the common ways to set tenant context and combine policies, along with the role model behind them. Read each row for when the option fits, what it costs to run, and where data can leak. The main takeaway is that connection pooling and the role model usually decide the leak risk more than the policy syntax does.

ConfigurationWhen it fitsOperational costLeak risk
Session setting per connectionDedicated connections for one tenant or a small, fixed set of tenantsLow setup, but every connection must be set before use and reset before reuseHigh with pooling: a tenant value left on a pooled connection can carry into another tenant's request
Per-transaction setting set by the poolPooled SaaS where each transaction sets the tenant with a local settingOne data-access wrapper must set the value on every transaction and no query may bypass itLower, because the value ends with the transaction, but any query outside the wrapper runs with no tenant context
Permissive policies onlyAdditive access, such as a tenant's own rows plus shared reference rowsEasy to reason about for a few rules, harder to audit as rules accumulatePermissive policies combine with OR, so one broad policy exposes every row it matches
Restrictive policies combined with permissive onesTenant isolation that must hold regardless of other grants in the schemaExtra policy on every table, and reviewers must read both policy types togetherLower: a later permissive grant cannot widen the tenant boundary, provided every table has the restrictive policy
Single application role for all tenantsOne service login over a shared schema with many tenantsSimplest to run and migrate, but isolation depends entirely on policy correctnessHighest exposure to policy gaps: a table without RLS, or a login with owner or BYPASSRLS rights, reads all tenants
Per-tenant database roles with RLSRegulated or high-sensitivity tenants that need separate grants and audit trailsMore roles to create, rotate and audit, and the work grows with tenant countLower for accidental cross-tenant reads because grants also apply, but role sprawl creates its own review burden
Owner and BYPASSRLS exemptions (any configuration)Applies to every option, including migration and admin accountsRequires a separate migration role and a periodic review of who holds BYPASSRLSTable owners skip policies unless FORCE ROW LEVEL SECURITY is set, and the owner is often the application login

Why owner and BYPASSRLS exemptions leak tenant data

Row-level security policies do not apply to everyone by default. Table owners and roles with the BYPASSRLS attribute skip policies, so a policy that looks correct can still return every tenant's rows when the query runs under one of those identities. Migrations, backfill jobs and admin scripts are the usual culprits because they often connect as the role that created the tables. If your application's database user owns the tenant tables, or if a reporting or support role carries BYPASSRLS, the isolation you tested through the app may not hold for those connections. Decide which roles are allowed to bypass policies, document why, and keep that list short.

Setting ALTER TABLE ... FORCE ROW LEVEL SECURITY makes policies apply to the table owner as well, which closes the most common gap, but it does not stop superusers or roles with BYPASSRLS. Keep the application role separate from the owner: the owner runs schema migrations, and the application role receives only the SELECT, INSERT, UPDATE and DELETE privileges it needs, with no ownership and no BYPASSRLS. Where a privileged task must read across tenants, give it a narrow, reviewed path rather than a general exemption. Confirm the exact behavior of superuser and BYPASSRLS roles against the PostgreSQL row security policies documentation for your version before you rely on it.

Detect exempt roles in the catalog before go-live and again after each migration. Query pg_roles for rolbypassrls and rolsuper, check pg_class for relrowsecurity and relforcerowsecurity on every tenant table, and list table owners through pg_tables. Any tenant table with row-level security enabled but not forced, or any application-facing role that owns a tenant table or can bypass policies, is a finding to resolve. Run the same checks in your change pipeline so that a new migration that recreates a table under the owner role is caught automatically. Treat the results as evidence for your access review and record who approved each remaining exemption.

How to set up RLS policies and verify them before go-live

This sequence turns row-level security from a design idea into a tested control: each tenant table is covered by a non-owner application role, forced policies and tenant context, and negative tests that prove one tenant cannot read or write another tenant's rows before production traffic arrives.

  1. Inventory tenant tables and database roles

    The data owner and the platform engineer list every table that holds tenant data, including join tables, audit tables and views, and mark the tenant key column on each. They also list every role that connects to the database: the application role, migration role, reporting or support roles, and the owner role that created the tables. Done means each tenant table has a named tenant key and each role has a stated purpose and an owner. Tables without a clear tenant key become the first findings to resolve, because a policy cannot protect data it cannot identify.

  2. Create a non-owner application role

    The database administrator creates a login role for the application that owns no tables, does not have BYPASSRLS, and is not a superuser. It receives only the table privileges the application needs, such as SELECT, INSERT, UPDATE and DELETE on specific tables. Check this with the catalog: query pg_roles for rolsuper and rolbypassrls for the application role and confirm both are false. Also confirm the application role is not a member of any role that carries those attributes. Done means the application connects as a role that the row-level policies actually constrain.

  3. Enable and force row-level security on tenant tables

    For each tenant table, the database administrator runs ALTER TABLE with ENABLE ROW LEVEL SECURITY and then FORCE ROW LEVEL SECURITY. Enabling alone leaves the table owner exempt, so FORCE is what makes the owner's queries subject to policy as well. Check the result by querying pg_class for relrowsecurity and relforcerowsecurity on every tenant table, and compare the list against the inventory from the first step. Done means no tenant table is missing either flag, and any table intentionally left out is documented with a reason.

  4. Write policies for each command

    The security engineer writes separate policies for SELECT, INSERT, UPDATE and DELETE, each comparing the row's tenant key with the tenant value the session sets. Use USING for rows a command can see or target, and WITH CHECK for rows a command may write, so that an UPDATE cannot move a row into another tenant. The policy must return no rows when the session value is unset, so the default is deny. Check each policy in pg_policies and confirm that no table has a permissive policy with a condition of true. Done means every command on every tenant table has an explicit policy and the unset-context case returns zero rows.

  5. Set tenant context in the connection pool safely

    The application sets the tenant identifier for each transaction using set_config with the local flag, for example through a function that the application calls at the start of each transaction, so the value cannot persist to the next client that receives the same pooled connection. If a connection pooler such as PgBouncer is in front of PostgreSQL, confirm the pool mode is compatible with transaction-scoped settings and that session variables are not reused across requests. Test this by opening two logical requests for different tenants on the same pooled connection and confirming the second sees only its own rows. Done means tenant context is set per transaction, and the pooled-connection test passes.

  6. Run cross-tenant negative tests

    The QA or security engineer writes automated tests that authenticate as tenant A and attempt to read, insert, update and delete rows belonging to tenant B, including by guessing identifiers and by changing the tenant key in an UPDATE. Each attempt should return zero rows, an error, or be rejected by WITH CHECK. The tests also cover the unset-context case and the case where the application forgets to set tenant context. Run the suite against a copy of production-like schema before go-live. Done means every negative case fails closed and the results are kept as evidence for the release.

  7. Check exempt roles and document the result

    The security engineer reviews every role that can bypass the policies: superusers, roles with BYPASSRLS, and the table owner if FORCE was not applied. Confirm which roles hold these attributes, who can grant them, and that the application, reporting and support paths use roles that are subject to policy or are approved with a documented reason. Re-run the catalog queries from earlier steps after any role change. Record the final policy list, test results and the list of exempt roles in the release record. Done means no application path reaches tenant data through an exempt role without an approved, documented exception.

What testing proves that tenant isolation holds

How do you test that one tenant cannot read another tenant's rows?

Run queries as the application role with the session set to tenant A, then try to select, update and delete rows that belong to tenant B by primary key, by filter and through joins. A correct policy returns zero rows for reads and affects zero rows for updates and deletes, with no error that reveals whether the other tenant's rows exist. Include inserts too: attempting to insert a row tagged with another tenant's ID should fail the WITH CHECK clause. Test with real identifiers from a second seeded tenant, because guessed IDs can miss the case where an attacker already knows a valid key. Each failed attempt proves the policy blocks that access path, not that the access path is absent from the code.

Do the isolation tests need to run through the connection pooler?

Yes. Session variables that carry the tenant context can leak between requests when a pooler reuses server connections, so a test that connects directly to PostgreSQL may pass while production fails. Run the same cross-tenant cases through PgBouncer in the transaction or session mode you plan to use, with concurrent requests for different tenants on a small pool. Confirm that the tenant setting is applied per transaction or reset at the end of each one, and that a request with no tenant context sees nothing. Check the pooler version against the fixes in its release notes before you rely on the result.

Why should you test as the table owner and as the application role separately?

Table owners bypass row-level security unless FORCE ROW LEVEL SECURITY is set on the table, and roles with BYPASSRLS skip policies entirely. A test run as a superuser or the owner can show full data and give false confidence. Run the suite as the application role that production uses, and add a short check that confirms the role is neither the owner nor carries BYPASSRLS. Then run one case as the owner on a table with forced RLS to confirm the policy applies to it. Your migration and admin roles should be tested separately, with a documented reason for any exemption they hold.

What do migration test runs catch that application tests miss?

Migrations can silently change isolation. Adding a new table without enabling RLS, recreating a table so policies are dropped, changing a policy expression, or adding a column that the policy references can all open access without any application code change. Run the isolation suite against a database built from scratch by your migrations, and again after applying migrations to a copy of production schema. Compare the output of policy listings and table flags with an expected file kept in version control. A failing comparison is a stop signal for the release, not a warning to review later.

What happens when the tenant context is missing from a request?

The policy should match no rows, so the request returns empty results or fails on write. Test this on purpose by opening a connection without setting the tenant variable, running reads, writes and calls to any function that reads tenant data. Confirm that the error or empty result does not expose another tenant's data, and that a missing setting is not treated as an empty string that matches rows with blank keys. Also test a malformed or unknown tenant identifier, because a policy that casts or compares values loosely can behave differently from what the code expects.

How do regression tests in CI keep isolation from breaking later?

Put the isolation cases in the same pipeline that runs unit and integration tests, so every merge that touches queries, migrations or the pooler configuration runs them. Keep the suite small enough to finish on every change and run a larger set on a schedule. Store tenant fixtures in code, keep the expected denials as assertions, and fail the build on any cross-tenant row. Pair the tests with a schema check that flags tables without RLS enabled. The cost is mostly engineering time to write and maintain the fixtures, plus a database instance in the pipeline. Ask any partner to show how the suite is scoped, owned and extended when new tables are added.

Security and operational risks to control

Row-level security protects tenant data only when every path to the table respects the policy. The risks below sit outside the policy text itself: shared connections, privileged roles, copies of the data and the process that changes the rules. Each one needs an owner and a check before go-live.

Session settings leaking through pooling

Tenant isolation often depends on a session setting such as app.tenant_id that the application sets per request. A connection pooler that reuses server connections across tenants can carry that setting into the next request if it is not reset or set inside a transaction. Check the pooling mode you run, confirm that tenant context is set with transaction scope, and test two tenants sharing one pooled connection. PgBouncer documents its pooling modes and should be the first read.

PgBouncer docs

Superuser and BYPASSRLS in ops tooling

Superusers and roles with the BYPASSRLS attribute skip row-level security entirely, and table owners skip it unless FORCE ROW LEVEL SECURITY is set. Migration runners, reporting jobs and support consoles often run under these roles for convenience. Inventory every role that connects, record which ones carry BYPASSRLS or ownership, and move routine workloads to roles that the policies apply to.

Backups and replicas that bypass policies

A base backup, a logical replication subscription or a dump copies rows without evaluating policies, so a restored or replicated copy holds every tenant's data. Logical replication also replicates table data through a publication owned by a privileged role. Decide which consumers are trusted to see all tenants, restrict their credentials and network paths, and document that a restored cluster inherits the same policies.

Archiving docs

Audit logging of policy-relevant access

Row-level security filters results silently, so a query that returns fewer rows looks like a normal query. Capture who connected under which role, which policies applied and when privileged roles touched tenant tables. Set logging for connections and statements at a level your compliance team has agreed, and send those logs to storage that tenant administrators and application roles cannot alter.

Policy changes without review

A single ALTER POLICY or DROP POLICY can open every tenant's rows to the application. Treat policy definitions as code: keep them in version control, require review by a security owner, and run the isolation test suite in the same pipeline. Restrict which roles can alter policies or table ownership, and confirm that migrations cannot run as a role with BYPASSRLS.

How much effort does RLS implementation take and what must your team provide?

What drives the effort of a row-level security implementation?

The main drivers are the number of tables that hold tenant data, the number and shape of database roles that connect to them, and how many existing query paths read or write those tables. Each table needs a policy for every command it allows, and each role needs a clear answer to whether it is subject to that policy. Application code that sets tenant context per connection or per transaction adds work, as do background jobs, reporting users, migrations and admin tools that currently bypass tenant filters. An illustrative case with a few tenant tables and one application role is far simpler than a schema with dozens of tables, several service accounts and a reporting layer that queries across tenants. Ask for a count of tenant-scoped tables and a list of every role that connects to the database before any quote is discussed.

Can our internal team implement RLS without outside help?

Often yes, if the team already knows PostgreSQL roles, privileges and transaction behavior, and can own a test suite that proves isolation. The parts that most often go wrong are the exemptions: table owners, roles with BYPASSRLS, and superusers ignore policies unless FORCE ROW LEVEL SECURITY is set, so a team that only writes policies can still leak data. Internal teams usually need time to audit every connection path, decide how tenant identity reaches the database and test cross-tenant access thoroughly. An outside review is most useful as an independent check of the policy set and tests before go-live, or as a fixed-scope build with a handover. Your team should confirm which of these it can staff and maintain over time.

What does our team need to provide to start?

The work depends on access and decisions from your side. You will need read access to the schema, migrations and role definitions, plus a non-production database that resembles production in structure. Test data should include at least two tenants with realistic row counts and edge cases such as shared reference rows, so isolation can be checked, and it should be handled under your data protection rules. The team also needs decisions on the tenant model: which column identifies the tenant, how the application passes that value to the database, whether tenants can belong to more than one organization, and which roles may bypass policies for support or reporting. Named contacts for the application, database operations and security teams speed up sign-off.

Which decisions must be made before the work starts?

Four decisions shape almost every policy. First, the tenant identifier and where it comes from, such as a session setting set by the application after authentication. Second, the role model: which roles are application, migration, reporting and administrative, and which of them, if any, may bypass RLS. Third, default behavior when the tenant setting is missing, which should deny access rather than return all rows. Fourth, how exceptions are approved and logged, including support access to a single tenant. Making these choices early avoids rework, because changing the tenant key or role model after policies are written touches every table. Write them down so the scope can reference them.

What makes the timeline longer or shorter?

Timelines move with the number of tenant tables, the number of distinct connection paths, how clean the current role model is, and how quickly access and test data are provided. Work on a schema with consistent tenant columns usually moves faster than one where tenant identity is inferred through joins across several tables. Testing time grows with the number of cross-tenant scenarios that must be proven, and with any compliance evidence you need to retain. Review cycles also add time if security or compliance teams require sign-off on each policy. Ask any provider to break the timeline into discovery, policy build, test automation, review and go-live, and to state which of your dependencies each phase assumes.

How do we request a fixed-scope quote for RLS work?

Send a written request that covers the list of tenant-scoped tables, the database roles and services that connect to them, the current tenant model, the target PostgreSQL version and any compliance frameworks that apply. Include whether you need design only, implementation, test automation, a pre-go-live review, or all of them. DeployOpen plans and delivers most engagements as fixed scope, with scope, deliverables and timelines agreed in writing before work starts, and does not publish a price list, so a quote follows from that written scope. Ask any provider to name what is one-time, such as policy build and test suite creation, and what recurs, such as policy updates when new tables are added and retesting after upgrades.

How DeployOpen scopes and delivers RLS work

DeployOpen plans and implements row-level security policies inside the PostgreSQL cluster you already run, in your cloud account, data center or air-gapped network. The work starts with a written inventory of tenant-scoped tables, the session settings that identify the tenant (for example, the custom parameter your application sets per connection), and the database roles each application component uses. From that inventory the scope is agreed in writing before work starts, so the deliverables are fixed: the policy set, the role model that separates the table owner, application roles and any administrative roles, the ALTER TABLE ... FORCE ROW LEVEL SECURITY settings where owners must also be restricted, and the test suite. Most engagements are fixed-scope, and the quote follows from that written scope rather than from a price list.

Cross-tenant isolation is tested against the database itself, not only through application code. The test plan covers each tenant-scoped table under the application role, checks that a query with no tenant context returns no rows (default-deny), attempts reads, updates and deletes across tenant boundaries, and confirms that roles carrying BYPASSRLS or table ownership are either removed from application paths or deliberately documented. Connection pooling and session variable reset behavior are included in that testing, because a pooled connection that keeps a previous tenant setting is a common source of leakage. DeployOpen also security tests the resulting setup, including the authentication settings, privilege grants and the paths through which administrators can read tenant data, and returns a findings report with fixes and a retest.

The same evidence supports compliance reviews. DeployOpen prepares the access control descriptions, role diagrams, test results and change records that your compliance and audit teams ask for, but it does not issue audit reports, attestations or certifications. Those come from your independent auditor or certification body. Ongoing work is available as a retainer for continuous testing, policy changes as tenant models evolve, and retesting after PostgreSQL minor or major upgrades. Before you request a quote, confirm with your own security and compliance teams which evidence they need, which tenant-scoped tables are regulated, and who in your organization owns the role model after handover.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.