
Designing a Schema Around RLS
Where the tenant column goes, why foreign keys and unique indexes skip RLS, and how to index and name policies in a multi-tenant Rails schema.
Part 4 of a series on multi-tenant Rails with Postgres Row Level Security.
So far, the series has used a single invoices table with a single policy. Real apps have dozens of tables, and RLS changes how you architect your application. You need to make a few decisions early on, like where the tenant column goes and how foreign keys and unique indexes are set up, which determines whether your policies stay simple and fast or become something nobody wants to touch.
This post walks through those decisions using the same fictional invoicing app: accounts with customers, invoices, line items, and payments.
Put the tenant column on every tenant-owned table
Why should every table that holds an account’s data get its own account_id column, even if it could find the account through a parent record? Short answer: readability and maintainability.
Take invoice line items. Each line item belongs to an invoice, and the invoice already has an account_id, so it’s tempting to leave the column off and write the policy as a lookup:
CREATE POLICY account_isolation ON invoice_line_items
USING (
EXISTS (
SELECT 1 FROM invoices
WHERE invoices.id = invoice_line_items.invoice_id
AND invoices.account_id = current_setting('app.account_id')::bigint
)
);
That works, but every query on line items now runs a subquery against invoices, and policies on deeper tables have to chain through more parents. They’re harder to read and harder to index.
Adding account_id to invoice_line_items makes every policy the same one-line comparison:
CREATE POLICY account_isolation ON invoice_line_items
USING (account_id = current_setting('app.account_id')::bigint)
WITH CHECK (account_id = current_setting('app.account_id')::bigint);
It’s a small amount of duplicated data in exchange for policies you can verify at a glance. Make the column NOT NULL, so a row can’t exist without an owner.
Decide which tables aren’t tenant-owned
Not every table belongs to an account. For instance, in the fictional invoicing app, the tables fall into four categories:
- Tenant-owned tables that get an
account_idand standard policy:customers,invoices,invoice_line_items, andpayments. - Reference tables shared by everyone, which don’t need RLS at all:
tax_ratesandcurrencies. - Account-specific tables used to find accounts, users, and memberships that either stay out of the tenant policies or get policies that don’t depend on
app.account_id, as covered in Part 3. - Framework tables that Rails and its libraries own, like
schema_migrations,ar_internal_metadata, and the Active Storage and Action Text tables.
Shared and account-specific rows in the same table
Sometimes a table holds both. Say the app ships a set of standard invoice templates, and each account can also create its own. A NULL account_id can mean “available to everyone”:
CREATE POLICY read_templates ON invoice_templates
FOR SELECT
USING (account_id IS NULL OR account_id = current_setting('app.account_id')::bigint);
CREATE POLICY write_own_templates ON invoice_templates
FOR ALL
USING (account_id = current_setting('app.account_id')::bigint)
WITH CHECK (account_id = current_setting('app.account_id')::bigint);
Postgres combines policies for the same command with OR, so an account can read shared templates and its own, but can only create, change, or delete its own. The shared rows are managed through migrations or an admin process, not by the app role.
Leave Rails’ own tables alone
It’s tempting to put RLS on every table in the database, including the ones Rails and its libraries create. Don’t. Those tables fall into two groups, and neither one should get a policy.
Infrastructure tables belong to the framework, not to any account:
schema_migrationsandar_internal_metadata- Solid Queue, Solid Cache, and Solid Cable tables
- An Active Record session store
They’re read by processes that never have a tenant set, like job workers polling the queue, the cache, and migrations. A policy on them breaks Rails in confusing ways and protects nothing. They only need the right grants for app_user.
Content tables are trickier because they do hold account data.
- Active Storage:
active_storage_blobs,active_storage_attachments, andactive_storage_variant_records - Action Text:
action_text_rich_texts - Action Mailbox:
action_mailbox_inbound_emails
File names, metadata, and rich text can be more sensitive than the invoice they’re attached to. These tables still don’t get RLS, for three practical reasons. They have no account_id, and adding one means changing tables Rails owns and keeping that change working through upgrades. They link to their records polymorphically, with record_type and record_id, so a policy would have to look up a different parent table depending on the row, which is exactly the kind of policy the first section of this post warns against. And Active Storage’s controllers don’t inherit from ApplicationController, so they run without tenant context, and RLS would break file serving outright.
When I first added RLS to an app, I went down the rabbit hole of protecting Active Storage too. I overrode the Active Storage controllers so the account was set before every request, added a tenant ID column to the Active Storage tables, and monkey-patched the models to fill it in. The further I went, the clearer it became that I was building something hard to maintain and that would fight every Rails upgrade.
Instead, what I decided is that these tables are protected by how you reach them. Get to them through a tenant-owned record, like invoice.attachments or a rich text field on the invoice, which RLS already filters. Active Storage URLs are signed, so they can’t be guessed. The gap is code that queries these tables directly, like ActiveStorage::Attachment.where(...) or ActionText::RichText.find(...). Treat those direct queries as off-limits in app code, the same way you’d treat raw SQL against your tenant tables. These rows can also be left behind when their record is deleted without callbacks, which the section on polymorphic associations below shows how to prevent.
Foreign keys don’t respect RLS
Postgres skips row level security when it checks foreign keys and unique constraints because it has to enforce those rules across all rows, creating a gap. Suppose a line item’s invoice_id references invoices.id. The policy makes sure every new line item has the current account’s account_id. But nothing stops that line item from pointing to another account’s invoice. The foreign key check passes because the invoice exists. The data now links two accounts together.
In a Rails app, this usually isn’t an issue because belongs_to is required by default, so Rails checks that the invoice exists by loading it before saving. Under RLS, another account’s invoice is invisible, the lookup comes back empty, and the save fails with “Invoice must exist.” This is a good example of the application layer and RLS covering for each other.
The gap is still real in a few places:
- There are methods that skip validations and bypass
belongs_to, includinginsert_all,upsert_all,belongs_to optional: true,save(validate: false),connection.execute, and data imports. DELETEwith foreign key constraints:ON DELETE RESTRICTmeans the other account can’t delete its own invoice because of a row it can’t see, andON DELETE CASCADEdeletes the invoice and silently deletes the first account’s line item.- Existence checks will give a foreign key error that tells the first account that an invoice ID exists somewhere, which matters more with sequential IDs than with UUIDs.
If your app relies on those paths, or a dangling cross-account reference would be a compliance problem, a composite foreign key that includes the account closes the gap in the database itself:
class AddAccountScopedForeignKeys < ActiveRecord::Migration[8.1]
def change
add_index :invoices, [:account_id, :id], unique: true
add_foreign_key :invoice_line_items, :invoices,
column: [:account_id, :invoice_id],
primary_key: [:account_id, :id]
end
end
Now a line item can only reference an invoice with the same account_id, and since the policy forces that to be the current account, cross-account references are impossible. The cost is an extra unique index on every parent table, noisier migrations, and cleaning up any existing cross-account references before you can add the constraint. Composite foreign keys also need Rails 7.1 or newer. For most apps, the belongs_to validation is enough, and composite keys are worth adding only where the paths above are common.
Unique indexes have the same blind spot. Under RLS, Rails’ uniqueness validation only sees the current account’s rows, so it can’t catch a duplicate in another account. The insert then fails at the database with ActiveRecord::RecordNotUnique instead of a validation error, and the failure itself tells the account that the value exists elsewhere. If a value only needs to be unique within an account, include account_id in the index.
Polymorphic associations need their own guard
Active Storage and Action Text link to their records with record_type and record_id, and so do your own polymorphic associations, like comments or tags. Postgres can’t put a foreign key on a column that points at different tables, so nothing in the database ties an attachment to its invoice.
Rails covers this on the normal path. has_one_attached and has_rich_text delete their attachment and rich text rows when you destroy the parent. But delete_all, raw SQL, and ON DELETE CASCADE skip callbacks, and each one leaves rows behind that point at a record that no longer exists. Under RLS, those orphans are also hard to clean up later, because a cleanup job can’t see every account’s records.
A trigger can do what the missing foreign key would have done with ON DELETE RESTRICT and refuse the delete.
class AddAttachmentGuardToInvoices < ActiveRecord::Migration[8.1]
def up
execute <<~SQL
CREATE FUNCTION prevent_orphaned_attachments()
RETURNS trigger
LANGUAGE plpgsql
SET search_path = public, pg_temp
AS $$
BEGIN
IF EXISTS (
SELECT 1 FROM old_rows o
JOIN public.active_storage_attachments a
ON a.record_type = TG_ARGV[0] AND a.record_id = o.id
) THEN
RAISE EXCEPTION 'deleted % rows still have attachments; use destroy', TG_ARGV[0];
END IF;
RETURN NULL;
END;
$$;
CREATE TRIGGER invoices_prevent_orphaned_attachments
AFTER DELETE ON invoices
REFERENCING OLD TABLE AS old_rows
FOR EACH STATEMENT
EXECUTE FUNCTION prevent_orphaned_attachments('Invoice');
SQL
end
def down
execute <<~SQL
DROP TRIGGER invoices_prevent_orphaned_attachments ON invoices;
DROP FUNCTION prevent_orphaned_attachments();
SQL
end
end
A few things to know about it:
REFERENCING OLD TABLEhands the trigger every deleted row at once, so a delete_all on 50,000 invoices runs one join instead of 50,000 lookups; Active Storage indexesrecord_typeandrecord_id, so the join is cheap.invoice.destroydeletes the attachment rows before deleting the invoice, so the trigger finds nothing; only the paths that skip callbacks are blocked, and the whole statement rolls back.active_storage_attachmentshas no RLS, so the trigger runs as app_user and still sees every row it needs.- Delete triggers don’t fire on
TRUNCATE, so if that’s a risk in your app, add aBEFORE TRUNCATEtrigger that always raises an error. - You need one trigger for each model with attachments, passing the class name Rails stores in
record_type(the base class for STI models). Part 7 shows how to test the trigger.
You can repeat the same logic for Action Text and any other polymorphic table, whether from a library or one of your own. Separating them into different functions means each one answers one question, and only the tables needing them get that trigger.
While it might look like we’re moving business logic into the database, which Rails generally steers away from, we’re not. You can think of the trigger as enforcing a rule the code already enforces, the same way a foreign key, a unique index, or a NOT NULL column does. Another way to look at it is: we put in the database what must hold no matter which code writes the data, and keep in the app what depends on who is acting or where a workflow is. A record disappearing while its files stay behind is never valid, so the check belongs in the database.
The tradeoff is that intentional bulk deletes, like removing an account through ON DELETE CASCADE, now fail until the attachments are removed first, so purge the files, then delete the rows. In addition, the trigger only stops new orphans. So if the app has been running for a while, check for existing ones once, as a role that can see every account, before relying on it.
Index for the policy
Every query on a protected table now includes the policy’s condition, so account_id should lead your indexes. A query for an account’s open invoices is really a query on account_id and status:
add_index :invoices, [:account_id, :status]
add_index :invoices, [:account_id, :issued_on]
add_index :payments, [:account_id, :invoice_id]
When you check query plans, run EXPLAIN as app_user, not as a superuser, because superusers bypass policies and will not show how Postgres plans the query and the policy.
Keep policies consistent
Once most tables share the same policy, the risk shifts from writing it wrong to forgetting it on a new table. Write it once and reuse it. A small helper in your migrations is enough:
module TenantPolicy
def add_tenant_policy(table)
name = quote_table_name(table)
execute "ALTER TABLE #{name} ENABLE ROW LEVEL SECURITY"
execute "ALTER TABLE #{name} FORCE ROW LEVEL SECURITY"
execute <<~SQL
CREATE POLICY account_isolation ON #{name}
USING (account_id = current_setting('app.account_id')::bigint)
WITH CHECK (account_id = current_setting('app.account_id')::bigint)
SQL
end
end
Include it in a migration and call add_tenant_policy :payments in the up method. Give every tenant policy the same name, too. It makes the policies easy to query and easy to spot when one is missing. Proving that each policy actually keeps accounts apart is the subject of the testing post at the end of the series.
Troubleshooting
- “new row violates row-level security policy” on insert. The row’s
account_iddoesn’t match the current account. Usually the model didn’t set it, or a nested record was built without it. Setaccount_idexplicitly on every tenant-owned record, including children. - Foreign key errors after adding composite keys. Existing data may already link records across accounts. Find those rows before adding the constraint, because Postgres won’t add it while they exist.
- Slow queries after enabling RLS. Look for indexes that don’t start with
account_id, and check the plan withEXPLAINas app_user. - Records disappear from joins. Each table in a join is filtered by its own policy. If one side of a join is a shared table with a policy that’s too strict, rows from the other side drop out.
- “deleted Invoice rows still have attachments; use destroy”. Something deleted invoices without callbacks, like
delete_allor a cascading foreign key; you will need to usedestroy, or purge the attachments first.
What’s coming in this series
- Why RLS for tenant isolation in Rails
- Your RLS policies might not be doing anything: superusers, table owners, and the roles you actually need
- Setting tenant context per request with
SET LOCAL - Designing a schema around RLS (this post)
- Background jobs when every query needs a tenant
- Cross-tenant reads without punching holes:
SECURITY DEFINERdone safely - Proving isolation: testing RLS in Rails
If you’re planning a multi-tenant schema, or adding RLS to an app that wasn’t designed for it, I’d be glad to help. I can review your schema for gaps like unscoped foreign keys and unique indexes, or help you plan the migration. Get in touch.



