To isolate tenants in Rails with PostgreSQL row-level security (RLS), you turn RLS on for every table that has a tenant_id, add a policy that compares tenant_id with a setting on the database connection, and set that setting inside a transaction at the start of each request. From then on the database filters every read and rejects every write for another tenant, even when the application code forgets its where. The app has to connect as a role that is not a superuser, or the policy is skipped.
I am Ash, and I have built backend systems for a decade. For regulated fintech clients I made tenant isolation a database guarantee with row-level security, because one customer seeing another customer’s rows is the failure nobody can afford. This article is for you if your Rails app keeps tenants apart with where(tenant_id: ...) or a default_scope and you want the database to hold the line as well. You get a migration helper that reads like Rails (enable_rls :posts), a safe way to set the tenant for each request, and the four traps I check before I trust the setup.
I first published this in January 2026 on my Substack as “Bulletproofing Multi-Tenancy”. I rewrote it for this site in November 2026. The helper in the first version called a method the database adapter does not have, so I fixed it and ran every snippet here on Rails 8.1.4 and PostgreSQL 18.7.
What row-level security does
Row-level security is a filter that PostgreSQL adds to every query on a table. You write a policy, which is a condition on the row, and the database applies it to each row before the query can see or change it. The PostgreSQL documentation on row security says that once RLS is enabled on a table, all normal access has to be allowed by a policy, and if no policy exists “a default-deny policy is used, meaning that no rows are visible or can be modified”.
A policy has two parts. USING decides which existing rows a query can see, update or delete. WITH CHECK decides which new rows an insert or update may write. For tenant isolation both parts say the same thing, which is that the row’s tenant_id must equal the tenant of the current request.
The difference from a gem or a default_scope is where the rule lives. An application scope protects the queries that go through it. Raw SQL, a console session, a reporting job or a new team member who writes unscoped can go around it without noticing. A policy sits with the data, so every query from the application role meets it.
When shared tables with RLS are the right choice, and when they are not
RLS fits the model where all tenants share the same tables. The AWS SaaS Lens calls this the pool model, where “tenants share resources”, and sets it against the silo model, where each tenant gets dedicated resources. In PostgreSQL the silo options are a schema for each tenant or a database for each tenant.
Shared tables with RLS are where I would start. There is one schema to migrate, one connection pool, and adding a tenant is one row. What you give up is separation of load and of operations. A heavy tenant slows the others, and restoring one tenant from a backup means picking its rows out of shared tables.
A schema or a database for each tenant buys that separation and costs you a migration for every tenant on every deploy. I would move a tenant there when a contract or a regulator asks for dedicated storage, or when one tenant is large enough to need its own capacity. The two can live together, with most tenants in the shared tables and a few large ones on their own.
Start with one table by hand
I will use a tenants table and a posts table that belongs to a tenant.
bin/rails g model Tenant name --primary-key-type=uuid
bin/rails g model Post tenant:references title --primary-key-type=uuid
UUID keys are optional here. If you use them, PostgreSQL 13 and later has gen_random_uuid() built in (see the UUID functions), and the Rails guide for PostgreSQL asks for the pgcrypto extension only on older versions. With integer keys, change the ::uuid cast below to ::bigint.
Written by hand, protecting posts takes three statements.
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
ALTER TABLE posts FORCE ROW LEVEL SECURITY;
CREATE POLICY posts_tenant_isolation ON posts
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
FORCE matters more than it looks. The PostgreSQL documentation says table owners normally bypass row security unless the owner chooses to be subject to it. In most Rails apps the role that runs the migrations is the role the app connects with, which makes the app the owner of every table. When I removed FORCE in my test, the app read both tenants’ rows with no tenant set. A stricter setup gives migrations their own owner role and the app a second role that can only read and write data. Keep FORCE in both setups.
The expression inside the policy is written to fail closed. current_setting('app.current_tenant_id', true) returns NULL when the setting does not exist, where the one-argument form raises an error (see the configuration settings functions). NULLIF(..., '') covers the empty string that a reset setting leaves behind. Comparing tenant_id with NULL is never true, so a request with no tenant sees no rows and cannot write any.
A migration helper that reads like Rails
Three statements for each table is a lot of copy and paste, and a typo in a policy is a security bug. I add two methods to the PostgreSQL adapter so that a migration can say enable_rls :posts.
# config/initializers/active_record_rls.rb
module RowLevelSecurity
module SchemaStatements
def enable_rls(table_name, tenant: :tenant)
table = quote_table_name(table_name)
policy = quote_column_name("#{table_name}_#{tenant}_isolation")
column = quote_column_name("#{tenant}_id")
current = "NULLIF(current_setting(#{quote("app.current_#{tenant}_id")}, true), '')::uuid"
execute "ALTER TABLE #{table} ENABLE ROW LEVEL SECURITY"
execute "ALTER TABLE #{table} FORCE ROW LEVEL SECURITY"
execute "CREATE POLICY #{policy} ON #{table} USING (#{column} = #{current}) WITH CHECK (#{column} = #{current})"
end
def disable_rls(table_name, tenant: :tenant)
table = quote_table_name(table_name)
policy = quote_column_name("#{table_name}_#{tenant}_isolation")
execute "DROP POLICY IF EXISTS #{policy} ON #{table}"
execute "ALTER TABLE #{table} NO FORCE ROW LEVEL SECURITY"
execute "ALTER TABLE #{table} DISABLE ROW LEVEL SECURITY"
end
end
module CommandRecorder
def enable_rls(*args) = record(:enable_rls, args)
def disable_rls(*args) = record(:disable_rls, args)
ruby2_keywords :enable_rls, :disable_rls
def invert_enable_rls(args) = [:disable_rls, args]
end
end
ActiveSupport.on_load(:active_record_postgresqladapter) do
include RowLevelSecurity::SchemaStatements
end
ActiveSupport.on_load(:active_record) do
ActiveRecord::Migration::CommandRecorder.include RowLevelSecurity::CommandRecorder
end
The first module does the work. It is included into the PostgreSQL adapter only, through a load hook, so nothing happens until Rails loads that adapter.
The second module is what makes change reversible. During a rollback Rails does not run your migration against the database. It records each command and replays the opposite one, and the CommandRecorder is the class that knows the opposites. invert_enable_rls tells it that the opposite of enable_rls is disable_rls with the same arguments. ruby2_keywords keeps an option such as tenant: :account working on the way back.
The migration for a new table is now short.
class CreatePosts < ActiveRecord::Migration[8.1]
def change
create_table :posts, id: :uuid do |t|
t.references :tenant, null: false, foreign_key: true, type: :uuid
t.string :title
t.timestamps
end
enable_rls :posts
end
end
bin/rails db:rollback prints disable_rls(:posts) followed by drop_table(:posts), with no down method written.
Set the tenant once per request, inside a transaction
The policy reads a setting, so something has to set it. This is the part I got wrong in the first version of this article, where I ran a plain SET app.current_tenant_id = ... on the connection.
A plain SET lasts for the whole database session, and a Rails app shares its sessions through a connection pool. The connection goes back to the pool with the tenant still on it, and the next request that picks it up inherits that tenant. I tested this. After one session-level SET for Company A, eight later checkouts that set no tenant each read Company A’s row.
The fix is to make the setting local to a transaction. set_config takes a third argument, and the PostgreSQL documentation says that when it is true “the new value will only apply during the current transaction”.
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
def self.with_tenant(tenant)
transaction do
with_connection do |connection|
connection.execute(sanitize_sql([ "SELECT set_config('app.current_tenant_id', ?, true)", tenant.id ]))
end
yield
end
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
around_action :scope_to_tenant
private
def scope_to_tenant(&block)
ApplicationRecord.with_tenant(current_tenant, &block)
end
end
current_tenant is however your app finds the tenant, usually from the signed-in user or the subdomain. Take it from what the user is allowed to access, never from an id the browser sends. The tenants table has no policy of its own, because the app has to read it before it knows which tenant it is serving.
The same reasoning applies if you run a connection pooler in transaction mode. The PgBouncer feature table lists SET and RESET as never supported in transaction pooling, because two statements from one client can land on two different server connections. A setting that is local to a transaction travels with that transaction.
There is a cost, and you should know it before you copy this. Every request now runs inside one database transaction, so it holds one connection from start to finish. Keep slow work such as calls to other services out of the request, or wrap only the database part in with_tenant. Background jobs, seeds and data migrations need the same wrapper, because they connect as the same role and see no rows without it. Pass the tenant id to the job and call with_tenant at the top of perform.
Check it in the console
This is what I ran in bin/rails console, connected as the app’s own role, and what came back.
a = Tenant.create!(name: "Company A")
b = Tenant.create!(name: "Company B")
ApplicationRecord.with_tenant(a) { Post.create!(title: "Secret A", tenant: a) }
ApplicationRecord.with_tenant(b) { Post.create!(title: "Secret B", tenant: b) }
Post.pluck(:title)
# => [] (no tenant set, so no rows)
ApplicationRecord.with_tenant(a) { Post.pluck(:title) }
# => ["Secret A"]
ApplicationRecord.with_tenant(a) { Post.where(tenant_id: b.id).update_all(title: "Mine now") }
# => 0 (Company B's row is not visible, so nothing is updated)
ApplicationRecord.with_tenant(a) { Post.create!(title: "Sneaky", tenant_id: b.id) }
# PG::InsufficientPrivilege: ERROR: new row violates row-level security policy for table "posts"
The read with no tenant returns nothing, and the write for the wrong tenant is an error from the database. Neither depends on a where in my code.
Four traps to check before you trust it
The app connects as a superuser
The PostgreSQL documentation is direct about this. “Superusers and roles with the BYPASSRLS attribute always bypass the row security system.” The default user in the official Docker image is a superuser, so a local setup often shows every row and looks like RLS is broken. In my test the superuser counted both tenants’ posts while the app role counted none. Run this as the app and expect two false values.
SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user;
schema.rb forgets the policies
After the migrations ran, my db/schema.rb had no trace of the policies or of RLS being enabled. The Rails migrations guide says schema.rb “cannot express everything your database may support” and tells you to set the schema format to :sql when you use such features. This matters because a test database is loaded from the schema file. With schema.rb your tests run against tables that have no isolation, and they will pass.
# config/application.rb
config.active_record.schema_format = :sql
A tenant table without a policy
RLS protects the tables you turned it on for. A table added six months from now with a tenant_id and no enable_rls is wide open. This query lists every table that has a tenant_id column and is missing RLS or FORCE. Put it in a test that fails when the list is not empty.
SELECT c.relname
FROM pg_class c
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = 'tenant_id'
WHERE c.relkind = 'r' AND NOT (c.relrowsecurity AND c.relforcerowsecurity);
Constraints see across tenants
The PostgreSQL documentation notes that unique constraints, primary keys and foreign key checks “always bypass row security” so that data stays consistent. A unique index on email alone tells Company A that an address is taken when only Company B uses it. Put tenant_id first in every unique index on a tenant’s table. A foreign key has the same blind spot, so a post can point at another tenant’s record by id unless the key includes tenant_id too.
A plan for the first week
- Check which role your app connects as, and create one that is neither a superuser nor
BYPASSRLSif needed. - Add the initializer and the
with_tenantwrapper, and wrap requests and jobs. - Switch the schema format to
:sql. - Turn RLS on for one low-risk table and run your test suite. Queries that ran with no tenant will now return nothing, and that list is worth reading.
- Add the test that lists unprotected tenant tables, then work through the list.
Keep your application scopes while you do this. RLS is the second lock, and the first one still makes your queries clear to the next reader. If AI agents reach this database through tools, the same thinking applies one layer up, and my guardrails checklist covers checking the tenant on every tool call. For the Rails side of keeping a codebase easy to reason about, I wrote about naming REST resources and routes.
A forgotten where used to keep me up at night. Now it returns an empty list, which is a much better way to find out.
Frequently asked questions
Does row-level security replace where(tenant_id: ...) in my Rails code?
No. Keep both. Application scopes make the intent of a query clear to the next reader. Row-level security is the guarantee underneath for the query that forgot its scope.
Should I use row-level security or a separate schema for each tenant?
Start with shared tables and row-level security, because there is one schema to migrate and adding a tenant is one row. Give a tenant its own schema or database when a contract or a regulator asks for dedicated storage, or when that tenant needs its own capacity.
Does row-level security slow down queries?
The policy adds one equality check on tenant_id to each query, and t.references already created an index on that column. I did not benchmark it for this article, so measure your own slow queries with EXPLAIN ANALYZE before and after, connected as the app role.
How does an admin or a support tool see all tenants?
Give that tool its own database role with the BYPASSRLS attribute, or a second policy written for that role, and keep it away from the web app’s credentials. Do not make the app role a superuser to get around one screen.
Does it work with a connection pooler such as PgBouncer?
A tenant set with set_config(..., true) inside a transaction is the form that fits transaction pooling, because the setting ends with the transaction. I have not run this exact code behind a pooler, so test it on yours. A session-level SET is the one to avoid, and it can leak a tenant between requests even without a pooler.