Row-Level Security for Multi-Tenant Apps in Postgres
A practical guide to Postgres row-level security for multi-tenant SaaS: writing tenant policies, layering roles, using RPCs safely, and testing isolation in CI.
The most dangerous bug in a SaaS product is one tenant seeing another tenant's data. Using row level security multi tenant policies in Postgres turns that from "a bug waiting to happen in some query" into something the database refuses to do.
I contributed to HNEFA, a multi-tenant gaming cafe POS and ERP built with the Exlaso team on Supabase Postgres, where every tenant's data is isolated by row-level security. This guide covers the patterns that matter when you put RLS into a real product.
TL;DR
Enable RLS on every tenant-owned table and write policies that compare the row's tenant_id to a trusted claim from the user's JWT or session. Layer role checks (admin, cashier) on top. Use database functions for sensitive operations, keep service-role keys off the client, index the tenant column, and test cross-tenant access automatically in CI with every migration.
key takeaways
- Row-level security moves tenant isolation from application code into the database, so a forgotten filter cannot leak data.
- Policies should read the tenant from a trusted claim or session setting, never from a value the client can freely change.
- Roles like admin and cashier layer on top of tenant policies, restricting which rows and operations each user can touch.
- RLS is only as good as its tests, so cross-tenant access checks belong in CI alongside versioned migrations.
How RLS works for tenancy
Without RLS, every query has to include WHERE tenant_id = .... With hundreds of queries across a POS (sessions, orders, inventory, wallets, reports), someone eventually forgets one.
With RLS enabled, Postgres appends the policy condition to every query on that table. Here is the shape of a basic tenant policy:
alter table orders enable row level security;
create policy tenant_isolation on orders
using (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid)
with check (tenant_id = (auth.jwt() ->> 'tenant_id')::uuid);
using controls which rows a user can read, update or delete. with check controls which rows they can insert or update into. Leaving out with check is a classic mistake: users cannot read another tenant's rows but could write into them. The PostgreSQL row security docs explain both clauses in detail.
Where the tenant ID comes from
The policy is only as trustworthy as its source of tenant_id.
| Source | Trust level | Notes |
|---|---|---|
| Signed JWT claim | High | Set server-side at login; client cannot alter it |
Session setting via set_config |
High, if set by your server | Common in non-Supabase setups with a pooled connection per request |
| Lookup from a memberships table | High | Flexible for multi-org users; needs an index |
| Request body or query param | Never | Client-controlled, defeats the purpose |
For users who belong to more than one organization, I prefer a memberships lookup in the policy, or a short helper function that returns the tenant IDs the current user can access.
Layering roles on top
Tenant isolation answers "which business's data?" Roles answer "what can this person do inside it?" HNEFA has super admin, admin and cashier roles, and a cashier should not be able to edit purchase prices or delete past bills.
A practical approach:
- Keep a tenant isolation policy on every table.
- Add separate policies per operation (
for select,for insert,for update,for delete). - Check the user's role in policies for sensitive operations, such as allowing deletes only for admins.
- Push multi-step operations into functions so the rules live in one place.
RPCs and computed values
Some operations should not be raw table writes at all. Closing a gaming session, billing snacks and taking payment across cash, card and UPI involves several tables that must stay consistent.
HNEFA uses Supabase RPCs for this kind of work. A notable design choice: prepaid customer wallet balances are computed by database functions from the underlying transactions rather than stored as a column. There is no balance field for someone to update incorrectly, and the number always matches the history.
When writing such functions, be deliberate about security invoker versus security definer. Invoker functions run with the caller's RLS. Definer functions bypass it, so they must check tenant and role explicitly inside.
Testing and migrations
RLS policies are code, and they need tests. My checklist:
- Every tenant-owned table has RLS enabled. A CI query against
pg_tablescan flag any table whererowsecurityis false. - Seed two tenants and assert that a user from tenant A gets zero rows from tenant B on every table.
- Assert that inserts with a foreign
tenant_idfail. - Run end-to-end flows as each role.
- Version every policy change as a migration, never edit policies by hand in a dashboard.
How I built this in practice
On the HNEFA case study you can see the full product: a live machine floor of PCs and consoles with realtime timed sessions, bookings, touch POS billing, a cash drawer with denomination counting, FIFO inventory batches, purchases and returns, around 15 reports including P&L and GST/HSN tax, and thermal receipt printing.
All of it is multi-tenant on Supabase Postgres with row-level security per tenant. The schema evolves through 47 versioned SQL migrations validated in CI, and Playwright end-to-end tests exercise the real flows. The stack is Next.js, TypeScript and TanStack Query, deployed with Coolify and Nixpacks. Realtime updates for the machine floor use Supabase realtime, which also respects RLS, so one cafe never sees another's live sessions.
Common mistakes
- Enabling RLS on most tables and forgetting the one added last week.
- Writing
usingwithoutwith check, allowing cross-tenant inserts. - Reading the tenant ID from a request parameter instead of a signed claim.
- Shipping a service-role key to the browser, which bypasses every policy.
- Creating
security definerfunctions without explicit tenant checks inside. - Editing policies in a dashboard instead of through versioned migrations.
keep reading
FAQ
What is row-level security in Postgres?+
Row-level security is a Postgres feature that attaches policies to a table, so every query only sees or changes rows that satisfy the policy. For multi-tenant apps, the policy typically checks that a row's tenant ID matches the current user's tenant.
Does row-level security slow down queries?+
There is a small overhead because the policy condition is added to each query. With an index on the tenant column and simple policy expressions, it is rarely noticeable in typical SaaS workloads.
Do I still need tenant checks in my API if I use RLS?+
RLS should be the guarantee, but validating inputs and permissions in the API still gives better error messages and defense in depth. Never rely only on the frontend.
Can Supabase handle multi-tenant apps with RLS?+
Yes. Supabase exposes Postgres RLS directly, and policies can read claims from the user's JWT. HNEFA, a multi-tenant gaming cafe POS, uses exactly this approach.
How do service roles and admin tools work with RLS?+
Service roles bypass RLS, so they must only run on trusted servers and never ship to the browser. Admin features are safer as security-definer functions with explicit checks inside.
Devang Gandhi
AI & full stack developer at Passdn, building CRMs, SaaS, AI agents and Flutter apps for clients in the US, UK, Australia, UAE and India. More about me