Row-Level Security in Postgres: When to Turn It On, and When to Wait
Most SaaS apps keep every customer in one database. What keeps them apart is one line in every query: “only this customer’s rows”. Forget it once, and one customer sees another’s data.
Code review catches most of those. Not all. And with AI writing more of the code, there are more queries to check every week.
Row-level security (RLS) moves that line into the database. Postgres checks every row against a rule. A query that forgets the filter gets nothing back, not someone else’s data.
I turned it on in a job-alert app I built. Here is how, what I planned for later, and how to tell if your app needs it.
You don’t need to read SQL to decide this. I check how your app keeps customers apart, add the rules table by table, and add the tests that prove each wall holds.
How I set it up
No new passwords. The app keeps its one database login. For each customer request it switches, for one short transaction, to a role that has no password and cannot log in, and tells the database which account is asking. When the transaction ends, the switch ends too. The next request starts clean.
Two doors. Admin pages, payment webhooks, nightly jobs and sign-in use a system door that skips the rules. Everything else uses the member door. A test holds the exact list of files allowed on the system door, so a customer page cannot use it by mistake.
Every table, tested. Rules are on for 49 of 50 tables; the last is the database’s own change log. Tests check that account A sees only A’s rows, that no account set means zero rows, and that a new table with no rule fails. The full suite passed: 1,987 tests.
Easy to undo. The rules do not bind the app’s own login, so undo is one click: roll back to the previous version.
What I planned for later
Teams. The rules are keyed on the account, so when several people share one account, they share its work. Personal settings check the person too, so they stay private.
Speed. Each customer query now takes three short trips to the database instead of one. I have not measured the cost yet. If pages slow down, a driver that sends all three in one trip fixes it, and only one file changes.
Turn it on, skip it, or wait?
Turn it on when many customers share one database, when the browser talks to the database directly (on Supabase, RLS is the only wall), when more than one person or AI writes queries, or when the data is sensitive.
Skip it with one database per customer, an internal tool where everyone may see everything, or a prototype with no real users.
Wait if you are still finding your market, the schema changes every week, and one person writes all the code. Every new table needs a rule, and a missing rule shows up as empty pages.
But do one thing now: put the customer’s account id on every table. That turns RLS into a small job later instead of a rebuild. Turn it on before real customer data arrives or the second developer joins, whichever comes first.
For the other walls an app needs, see understanding security in your SaaS. To check the walls you already have, see a practical security audit toolkit.
The short version
RLS makes the database refuse the query you forgot to filter. Add the account id everywhere today, and turn the rules on before the risk is real.
Tell me how your app keeps customers apart and I’ll tell you if you need row-level security now, later, or never.
Where does your app keep customers apart today: in every query, or in the database?
Stack: Next.js on Vercel, Postgres on Neon through a pooled connection, pg driver.
The role
One role with no login. The app’s login may switch to it, but does not inherit its rights:
CREATE ROLE app_member NOLOGIN;
GRANT app_member TO CURRENT_USER WITH INHERIT FALSE, SET TRUE;
The ids for the current transaction. An unset value reads as NULL, so a rule matches no row:
CREATE FUNCTION app_account_id() RETURNS uuid LANGUAGE sql STABLE AS $$
SELECT NULLIF(current_setting('app.account_id', true), '')::uuid
$$;
The rules
Account tables:
CREATE POLICY member_own ON proposals FOR ALL TO app_member
USING (account_id = app_account_id())
WITH CHECK (account_id = app_account_id());
Personal settings check both the account and the person, so teammates in one account cannot read each other’s settings. Tables only the system uses (billing events, rate limits) have RLS on and no grant, so the member role cannot touch them at all.
The switch
Each member query runs in its own short transaction. true makes every setting transaction-local, which is what makes it safe on a pooled connection:
const setup =
"BEGIN; SELECT set_config('role', 'app_member', true), " +
`set_config('app.account_id', ${client.escapeLiteral(scope.accountId)}, true), ` +
`set_config('app.user_id', ${client.escapeLiteral(scope.userId)}, true)`;
await client.query(setup);
const result = await client.query(text, params);
await client.query("COMMIT");
Both ids are checked against a strict pattern before they reach the SQL. A failed query rolls back; if the rollback fails too, the pool drops that connection.
Two doors in code: getMemberDb(scope) for member work, getSystemDb() for admin, webhooks, timers and sign-in. The old getDb name is gone, so every call site had to pick one.
Gotchas
- Switch in its own statement. RLS is applied at plan time.
SELECT set_config('role', 'app_member', true), (SELECT count(*) FROM job_views)still counts every row, because the statement was planned as the owner. - Foreign key checks skip RLS. An insert that points at another account’s row is not stopped by the policy on the parent. Validate ownership in the app too.
- Functions run as the caller. Only one helper is
SECURITY DEFINER: it lists the accounts a separate read-only copy login may see. - Do not
FORCE ROW LEVEL SECURITY. The owner bypass is the system door and the rollback path.
Tests
- Integration tests against a real Postgres: RLS on for every table except the migrations log; grants match policies; no ids set means zero rows; A reads and writes only A; system tables refuse the member role; nothing leaks to the next transaction; a bad scope is refused before SQL.
- A unit test fixes the list of files allowed to call
getSystemDb(). Adding one is a review decision. - A test fails when a new table is not listed in exactly one ownership group.
Cost and the way out
Three round trips per member query: BEGIN + setup, the query, COMMIT. Unmeasured so far. The fix if it shows up: a driver that pipelines the three into one trip. Only lib/db/server.ts changes.
More Posts
All posts
November 25, 2026
Why Your App Went Offline on Vercel's Free Plan (and How to Stay Under the Limits)
Vercel's free plan pauses every site on the account when one monthly limit runs out. What the limits mean in plain words, what uses them up, and the fixes, from a real case.
November 24, 2026
Why Your Project Starts With a Small Paid Step: Requirements and an Estimate Before the Build
A price given before the work is measured is a guess, and someone pays for it later. What a small paid first step gets you: written decisions, a cost range and a time range, and the choice to stop there.