The bug report was one line: "I can see an order that isn't ours." It came from a tenant user in an admin console, and it was the kind of sentence that makes you stop everything. We had Postgres row-level security turned on. The policies were written. The tests passed. And one tenant was still reading another tenant's rows.

This post walks through what went wrong with Postgres row-level security in a multi-tenant app, why it was two separate mistakes that only hurt in combination, and the connection-pool pattern that closed the hole. The details are generalized, with no client specifics, but the failure modes are exactly as described.

The setup: RLS as a backstop, not the primary check

The architecture was ordinary. A web backend, a shared schema, a tenant_id column on every tenant-owned table, and an admin console on top. The application layer already filtered by tenant in its queries. RLS was meant as the backstop: if a developer forgets a WHERE tenant_id = ... in some new endpoint, the database refuses to return the wrong rows anyway.

The policies looked like this:

ALTER TABLE orders ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = current_setting('app.tenant_id')::uuid);

The backend set app.tenant_id at the start of each request, and the policy compared every row against it. Clean, small, and easy to review. It was also wrong in two ways.

Bug one: ENABLE without FORCE

Table owners bypass RLS by default. ENABLE ROW LEVEL SECURITY applies policies to everyone except the table owner (and superusers, and roles with BYPASSRLS). Our migrations ran as a role that owned the tables, and, through a historical shortcut, the application's connection string used that same owner role in the admin console's service.

So for that service, the policies were decorative. The queries were protected only by the application-layer filter, which is precisely the thing RLS exists to backstop. Nothing had failed loudly because nothing had been exercised: with the owner role, an unfiltered query simply returned everything and nobody had written a test that tried one.

The fix here is two lines, plus a role split:

ALTER TABLE orders FORCE ROW LEVEL SECURITY;

-- and: the app connects as a non-owner role
CREATE ROLE app_user LOGIN NOINHERIT;
GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_user;

FORCE makes the owner subject to policies too. The role split is the stronger fix: the app should never connect as the role that owns the schema. Migrations run as the owner; the runtime uses a role that can't alter policies, can't disable RLS, and doesn't have BYPASSRLS.

Bug two: the session variable that outlived the request

Even with FORCE in place, we reproduced the leak in staging. This was the more interesting one.

The backend ran the setting as a plain session-level statement:

SET app.tenant_id = '...';

Session-level means it lasts for the life of the connection, not the life of the request. With a connection pool, connections are reused across requests and across tenants. Request A (tenant 1) sets the variable and returns the connection to the pool. Request B (tenant 2) checks out the same connection. If B's code path forgot to set the variable, or set it after its first query, B ran under tenant 1's identity.

In the admin console, a few background endpoints, an export job and a health-style summary, skipped the middleware that set the variable. They worked in testing because a connection was usually fresh or recently set to the "right" tenant by chance. In production, the pool made it nondeterministic. That's the worst kind of leak: intermittent, dependent on traffic ordering, and invisible to a single-tenant test suite.

There was a third trap hiding behind it. current_setting('app.tenant_id') without the missing_ok flag raises an error when the variable was never set, which is good. But once any request on a connection had set it, it never errored again; it just held a stale value.

The pattern that fixed it

The fix is to make tenant context transactional and make "no context" fail closed:

  1. Every query runs inside a transaction that sets context locally. Use SET LOCAL (or set_config('app.tenant_id', $1, true)), which reverts automatically at commit or rollback. When the connection goes back to the pool, there is nothing left to leak.
  2. One checkout function, no raw pool access. The pool is wrapped so the only way to get a connection is withTenant(tenantId, fn). It opens a transaction, sets the local variable, runs the callback, and commits. Code that tries to query without a tenant has no handle to do it with.
  3. Fail closed on missing context. The policy treats an unset or empty value as no rows, not an error you might catch and retry:
CREATE POLICY tenant_isolation ON orders
  USING (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);

With nullif and missing_ok = true, an absent variable yields NULL, and tenant_id = NULL is never true. Zero rows, always.

A caveat if you use PgBouncer: in transaction pooling mode, session-level SET is unreliable by design, and SET LOCAL inside a transaction is the pattern that works. In session pooling mode, you'd also want DISCARD ALL or RESET on release as a second line of defense, but we treat that as belt-and-braces, not the primary mechanism.

What we test now

The regression test is the part most teams skip. Ours does three things against a real Postgres instance, not a mock:

  • Connect as the runtime role and assert it is neither a superuser nor BYPASSRLS, and doesn't own any table.
  • Run a query with no tenant context and assert it returns zero rows.
  • Alternate tenants on a pool of size one, thousands of iterations, asserting that each request sees only its own rows. A pool of one forces connection reuse every time, so a stale variable shows up immediately instead of once a week.

The pool-of-one test would have caught the original bug on its first run. It's cheap and it's the highest-value test in the suite.

The takeaway

RLS is a good backstop, but only if you verify the backstop actually engages. Check who owns the tables, check who the app connects as, and make tenant context die with the transaction. Anything that depends on a connection being "clean" will eventually meet a connection that isn't.

At orithLabs, we spend a lot of our code audit work on exactly this kind of gap: security controls that exist on paper and quietly don't apply at runtime. If you're running a multi-tenant backend or admin console and want a second set of eyes on how isolation actually behaves under load, we're happy to talk it through, engineer to engineer.