Tenant isolation with PostgreSQL row-level security: what I learned as a backend intern
In a multi-tenant backend, every customer's data sits in the same tables. A tenant_id column is the only thing separating one company's records from another's.
That means every query needs a tenant filter. Every SELECT, every UPDATE, every query someone adds next year.
Forget that WHERE clause once and one tenant can read another tenant's rows. Nothing crashes. No test fails unless someone wrote that exact test. The data just goes to the wrong customer.
This summer I worked as a backend intern on a codebase that didn't rely on developers remembering that clause. It pushed tenant isolation down into PostgreSQL using row-level security. This post covers what I understood about the mechanism, and the part that actually broke my code. That turned out not to be RLS at all.
The context
I interned at Koto7 Technologies from June to August 2026. The product is a headless logistics backend: no UI, just a GraphQL API that other companies build on.
The stack was Go, PostgreSQL 16, pgx, gqlgen and goose. Every PR went through review with the CTO.
Every request authenticates with an API key. Middleware resolves the key to a tenant and puts the tenant ID into the request context. Everything after that is scoped to that tenant.
I want to be clear about my part. The RLS setup was already there when I joined. The CTO wrote the policy pattern and the plumbing that passes the tenant to the database. I didn't design any of it.
What I did was build seven stories on top of it. These covered the tenant status lifecycle, listing and revoking API keys, partner application tracking, and driver and vehicle features. When I added tables, I applied the existing policy pattern to them.
So this isn't a guide to designing multi-tenancy. It's what I learned by working inside one, and where I got stuck.
The obvious approach, and why it wasn't enough
Before this internship, I'd only done tenant-style scoping in application code, in Node.js and MongoDB projects. Every repository function takes a tenant ID and adds it to the query.
That works. The problem is what it depends on: every developer remembering the filter in every query, forever.
A new endpoint written in a hurry. A reporting query someone adds six months later. A generic helper that does SELECT * FROM orders WHERE id = $1. Any one of these quietly removes the boundary between two customers.
Code review helps, but review is also a person remembering. And this bug doesn't show itself. A query missing a tenant filter returns perfectly valid rows. They just belong to someone else.
How row-level security works
RLS moves the rule from "every query must include the filter" to "the table refuses to show rows that don't match." You attach a policy to the table once, and PostgreSQL adds that condition to every query against it.
Here's the shape of the pattern we used, with generic names:
-- Simplified illustration of the pattern, not production code
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY orders_tenant_isolation ON orders
FOR ALL
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
This turns RLS on and attaches one policy covering reads and writes. Its two clauses do different jobs.
USING decides which existing rows a query can see. For SELECT, UPDATE and DELETE, rows from other tenants simply don't exist as far as the query is concerned.
WITH CHECK decides which rows a query is allowed to write. Without it, a buggy INSERT could create a row with someone else's tenant_id. With it, PostgreSQL rejects that write.
Where the tenant comes from
The policy compares against current_setting('app.tenant_id', true). This is a custom setting, not a column. The application sets it, and the policy reads it.
The true argument means "don't error if it's missing, return NULL." Comparing anything to NULL is never true. So if the application forgets to set a tenant, the query sees no rows instead of all rows. It fails closed.
Why it has to be set per transaction
We used pgx's connection pool. A pool keeps a fixed set of open connections and lends them to requests one at a time. When a request finishes, its connection goes back and the next request reuses it.
A plain SET app.tenant_id = ... lasts for the whole session, and a pooled connection's session outlives the request. If request A sets tenant A and returns the connection, request B could pick up the same connection. If B doesn't set its own tenant, it runs as tenant A.
The fix is to make the setting local to a transaction. It then resets automatically on commit or rollback, so it can't leak into the next request.
// Simplified illustration of the pattern, not production code
func withTenant(ctx context.Context, pool *pgxpool.Pool, tenantID string,
fn func(pgx.Tx) error) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) // no-op once committed
// third argument true = setting lasts only for this transaction
if _, err := tx.Exec(ctx,
"SELECT set_config('app.tenant_id', $1, true)", tenantID); err != nil {
return err
}
if err := fn(tx); err != nil {
return err
}
return tx.Commit(ctx)
}
This opens a transaction and sets the tenant for that transaction only. It uses set_config(..., true) rather than SET LOCAL because SET LOCAL doesn't accept query parameters. With set_config the tenant ID goes through as a bound value instead of being formatted into SQL.
I didn't write this plumbing in our codebase. I had to understand it, though, because it decides whether the policy sees the right tenant at all.

Roles: who the policy applies to
RLS policies apply per database role. Our application didn't connect as the database owner. It connected as a restricted role, app_role. A separate auth_role did nothing except look up API keys.
That detail matters more than it looks. By default, the owner of a table bypasses its RLS policies, and superusers always do. If the application connected as the owner, the policies would do nothing.
Defence in depth
My repository queries still included an explicit WHERE tenant_id = $1, following the existing code. RLS is the guarantee. The explicit filter makes each query's intent obvious to the next reader, and it doesn't depend on the session setting being right.
What was harder than expected
RLS and grants are two separate layers
This is the thing I didn't understand at the start, and it caused all my real bugs.
RLS decides which rows a role can see. Grants decide whether the role can touch the table, or a specific column, in the first place. If the grant is missing, the policy never even comes into play. The query just fails with "permission denied."
Our codebase used column-level grants everywhere. For example, app_role could read some columns of the API keys table but never the column storing the key hash. Even a careless SELECT * couldn't return it.
-- Simplified illustration, not production code GRANT SELECT (id, name, status, created_at) ON accounts TO app_role; GRANT UPDATE (status, status_changed_at) ON accounts TO app_role; -- the audit trigger inserts as app_role, so it needs this too GRANT INSERT ON account_status_history TO app_role;
The first two lines give the application exactly the columns it needs. The third is the kind of grant I kept missing.
During a manual QA pass across six of my stories, I found three permission bugs. All three were missing grants. I fixed them with two migrations.

Things I didn't know needed privileges
Three rules caught me out.
A trigger runs as the role that caused it. My tenant status story used a trigger to write every status change into a history table. My Go code never inserted into that table directly, so I didn't think app_role needed access to it. But the trigger runs as whoever ran the UPDATE, which was app_role. Without an INSERT grant on the history table, every status change failed.
SELECT ... FOR UPDATE needs the UPDATE privilege. I used row locks to stop two concurrent status changes from racing. Locking a row counts as preparing to update it, so a read-only grant wasn't enough.
Columns in a WHERE clause need SELECT, even if you don't return them. Filtering on a column means reading it, so the role needs SELECT on that column.
Checking the wrong system view
When I first debugged a missing grant, I queried information_schema.role_table_grants, didn't see the SELECT I expected, and concluded it was missing.
That view only shows table-level grants. Column-level grants live in a different view:
SELECT grantee, column_name, privilege_type FROM information_schema.column_privileges WHERE table_name = 'api_keys' AND grantee = 'app_role';
This lists exactly which columns a role can read or write. That was the real source of truth for our setup.
Migrations are tracked by version, not content
goose records which migration versions have run. While fixing one grant, I edited a migration file that had already run locally, and goose didn't re-run it because it considered that version done.
The branch wasn't merged yet, so it was fixable. The lesson stuck anyway: once a migration has run anywhere that matters, fix it with a new migration, not an edit.
Tradeoffs
RLS isn't free, and I don't think it's always the right choice.
The failures are quiet. A missing tenant setting gives you zero rows, not an error. That's safe, but it's confusing to debug if you don't know the policy exists.
The logic is split. Part of the access rules live in Go and part live in SQL policies and grants. Someone new to the codebase, which was me, has to read both to understand why a query behaves the way it does.
Cross-tenant work needs a deliberate path. Anything that legitimately reads across tenants, like an internal admin report, needs a way around the policy. That way around then has to be secured too.
Performance depends on your schema. The policy condition is applied to every query. I didn't measure the cost on our system, so I won't put a number on it. It does mean tenant_id should be indexed on tables that get queried often.
It's not always needed. If each customer gets their own database, or the app is small enough that one person writes every query, the extra machinery may not pay for itself.
What I'd do differently
I'd write down the grants each story needs as part of the story, then check them against column_privileges before QA, not during it.
On day one, I'd check which role owns each table and whether FORCE ROW LEVEL SECURITY is set. I didn't check this during the internship. I only properly understood the owner-bypass rule while writing this post.
I'd also write one test whose only job is to set tenant A, query tenant B's rows, and expect nothing back.
What I took away
RLS changed how I think about a security rule. It's much stronger when the database enforces it than when every developer has to remember it.
But it didn't remove the need to understand privileges. It added a second layer, and my bugs lived in that layer.
The most useful thing I learned was to check what the database actually allows, not what I assumed a migration had granted.