Go to Page Content

Tenant Isolation in Rails: Why I Let Postgres Enforce It

James Fawks

One missed WHERE clause can expose every customer’s data. Compare four ways to isolate tenants in Rails, and see why Postgres RLS makes the safer backstop.

Part 1 of a series on multi-tenant Rails with Postgres Row Level Security.

In a multi-tenant SaaS app, every customer’s data lives in the same tables. Picture an invoicing app for small businesses: one company’s customers, invoices, and payment records sit right next to every other company’s. The only thing keeping them apart is a WHERE clause. Most of the time that’s fine. The problem is the one query that forgets the WHERE clause.

The problem with “remember to scope it”

Most Rails apps handle tenancy in the application code. You use a default_scope (which is not recommended), a gem like acts_as_tenant, or you make a habit of making sure the current tenant is applied to the query for everything. These approaches work, but the guarantee is only as strong as the least careful query in your codebase.

For example:

# In a controller, scoped and safe
current_account.invoices.where(status: "open")

# Six months later, in a reporting job written in a hurry
Invoice.where("due_date < ?", Date.current)

If your tests don’t check that only the current tenant’s invoices are included, nothing fails, and the tests pass. The “overdue invoices” report now includes every customer’s invoices.

The same thing happens with unscoped, raw SQL, a background job that never sets the current tenant, a one-off fix run in the Rails console, or a new developer who doesn’t know the convention yet. I’ve seen versions of all of them in real codebases over the years.

When tenant isolation depends on everyone remembering, someone will forget sooner or later.

The usual options

There are four common ways to separate tenant data in Postgres, depending on your situation.

Application-level scoping

One database and one schema, with your code adding the tenant filter. There are gems out there that help with this, but ultimately you need to remember to include the tenant in every query.

Pros

  • The simplest option to set up and to understand
  • Works with any database and every Rails feature
  • Needs no extra infrastructure or database configuration

Cons

  • Enforcement is a convention, not a guarantee
  • One unscoped query, raw SQL statement, or background job can expose every customer’s data
  • Hard to prove isolation to a customer or an auditor

Best for: Early-stage products, internal tools, and apps where tenant data isn’t sensitive enough to justify a second layer.

Schema per tenant

Each customer gets their own Postgres schema with its own copy of every table. The app switches to the right schema at the start of each request.

Pros

  • Strong separation, since one customer’s queries can’t reach another customer’s tables
  • Easy to export, restore, or delete a single customer’s data
  • A forgotten WHERE clause can’t leak across customers

Cons

  • Every migration runs once per tenant, so deploys slow down as you grow
  • Switching schemas on every request adds complexity and is easy to get wrong with pooled connections
  • Reporting across customers means querying many schemas
  • Postgres starts to struggle with very large numbers of schemas

Best for: A modest number of larger customers who expect their data kept apart, or who need per-customer exports and restores.

Database per tenant

Each customer gets a separate database, sometimes on a separate server. Rails 6.1+ supports this with horizontal sharding configured in database.yml, which works well for a handful of tenants.

Pros

  • The strongest isolation available
  • Per-customer backups, restores, and data residency
  • With separate servers, one busy customer can’t slow down the others

Cons

  • The most expensive option to run
  • Migrations, backups, and monitoring multiply with every customer
  • Connection management gets complicated, since Rails isn’t built to juggle hundreds of databases

Best for: Enterprise customers whose contracts or compliance rules require it, regulated data, or strict data residency requirements.

Row Level Security (RLS)

One database and one schema, like application-level scoping, but Postgres itself attaches a filter to every query on a protected table. If your code forgets the WHERE clause, the database doesn’t.

Pros

  • Isolation is enforced by the database, even when application code forgets
  • Keeps the simple single-schema setup that Rails is built around
  • Migrations run once, no matter how many customers you have
  • Works as a second layer alongside application-level scoping

Cons

  • Easy to set up wrong; superusers and table owners have the ability to bypass it
  • Every request needs a tenant context, and pooled connections need extra care
  • Background jobs and cross-tenant reports need their own design plan

Best for: SaaS apps with many small and medium customers sharing tables, where a leak would be serious and you want a guarantee stronger than convention. The trade-offs are covered in more detail below.

What RLS looks like

You can turn RLS on for a table that contains sensitive data and give it a policy that limits every query to the current tenant’s rows.

For example, using the invoices table, we can enable RLS and add a policy that ensures the returned invoices belong to the current account.

ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

CREATE POLICY account_isolation ON invoices
USING (account_id = current_setting('app.account_id')::bigint)
WITH CHECK (account_id = current_setting('app.account_id')::bigint);

The USING statement controls which rows a query can see, and the WITH CHECK statement controls which rows it can insert or update, so nobody can write an invoice into another account either.

The policy reads a session variable, app.account_id. Your app sets it at the start of each request, inside a transaction, so the value disappears when the transaction ends:

ActiveRecord::Base.transaction do
    sql = ActiveRecord::Base.sanitize_sql_array(
    ["SELECT set_config('app.account_id', ?, true)", current_account.id.to_s]
    )
    ActiveRecord::Base.connection.execute(sql)
    
    # handle the request as usual
end

The true at the end makes the setting local to the transaction, the same as SET LOCAL. That detail matters a lot once connection pooling is involved, and it gets its own post later in the series.

Now go back to that hurried reporting job. With RLS in place, it doesn’t leak every customer’s invoices. It either returns only the current account’s rows or fails outright because no account was set. Either way, it fails closed, which is exactly what you want.

The trade-offs

There are a few trade-offs when implementing RLS:

  • Superusers bypass RLS, and table owners do too unless you force it. Many development setups connect as exactly that kind of user, so your policies look like they work while enforcing nothing. This is a strong enough concern to be the subject of my next post.
  • Every request needs tenant context per transaction and careful handling of pooled connections, so one request’s settings never leak into another.
  • Background jobs that work across many tenants, like nightly billing or reminders, can’t just run one big query anymore. You have to decide how they get access.
  • Rails has no built-in migration helpers for RLS, and schema.rb doesn’t record policies, so you’ll need to switch to structure.sql.
  • Debugging can be confusing at first, especially if a query returns zero rows. You need to get used to checking the tenant context first.
  • There’s a small performance cost as the policy condition is added to every query. With the tenant column indexed, it’s rarely noticeable, but it isn’t zero.

RLS is probably not worth it for a single-tenant app, an early prototype with one customer, or an app where every customer already needs their own database.

RLS along with application-level scoping

Application-level scoping is what makes queries correct and readable, and it’s what most of your code should rely on day to day. RLS is the second layer. It’s there for the query nobody reviewed carefully, the job that ran without a tenant, and the console session at 11pm. Two independent layers are much harder to get wrong at the same time than one.

Own the code that enforces it

There are already gems that add RLS to Rails, and they’re worth a look. In my experience, they share one trait: they decide how tenancy works for you. One tenant model, one tenant column, and their way of wiring it up. If your app fits that shape, great. If it doesn’t, you end up working around the gem.

Tenant isolation is security code, so I want to read every line and shape the policies to my app. Sometimes a policy depends on more than the tenant, like the user’s role within an account, and sometimes “tenant” isn’t even the right concept.

The Rails 8 authentication generator is a great example, and it handles this split well. It generates code you own and can change, and leaves the tricky primitive, has_secure_password and bcrypt, to the framework. I think RLS should work the same way: a small set of generic helpers for the mechanical parts, like migrations and setting session variables, while the policy design stays in your hands.

I’m extracting those helpers from one of my own apps into an open-source gem, and I’ll introduce it later in this series once I’ve explained each piece it covers.

What’s coming in this series

  1. Why RLS for tenant isolation in Rails (this post)
  2. Your RLS policies might not be doing anything: superusers, table owners and the roles you actually need
  3. Setting tenant context per request with SET LOCAL
  4. Designing a schema around RLS
  5. Background jobs when every query needs a tenant
  6. Cross-tenant reads without punching holes: SECURITY DEFINER done safely
  7. Proving isolation: testing RLS in Rails

If you run a multi-tenant Rails app and a customer has ever asked, “How do you keep our data separate from everyone else’s?”, I’d be glad to help you answer that with confidence. I can review your current setup or build tenant isolation into your app. Get in touch.

Related blogs

Local SEO: What You Can Do Now Without Hiring an Agency

Small business owners keep asking me what they can do about local SEO before they have the budget for an agency. This is the short list I give them.
Read in 6 minutes

What Is Web Accessiblity?

Web accessibility ensures websites are usable for people with disabilities, helping small businesses reach more customers, comply with federal and local laws, and improve user experience.
Read in 6 minutes

Why do I not sign NDAs?

As a consultant and developer, I’m often asked to sign NDAs (Non-Disclosure Agreements). Here are my top 5 reasons I will not and my 6 criteria for signing one.
Read in 5 minutes

How Much Does It Cost to Build a Web Application

Many factors can affect the price of building and maintaining a customer web application. There are also a few ways you can help mitigate costs. Just be careful; there are tradeoffs, and some decisions can be costly down the road, jeopardizing the success of your web application.
Read in 10 minutes