Multi-tenant SaaS with PostgreSQL Row Level Security: separating customers in the database, not in code
In Courino every courier company's data lives in one PostgreSQL database. Why we left tenant isolation to Row Level Security instead of WHERE clauses, and the traps we hit setting it up.
Courino is the cloud management system we build for courier companies: orders, couriers, courier earnings, customer accounts. Every courier company is a tenant, and all of their data sits in one PostgreSQL database, in the same tables.
In this model the most expensive mistake is obvious: one company seeing another company's orders, or the phone number of one of its couriers. This post is about how we set out to make that mistake impossible.
The classic way: WHERE tenant_id = ? on every query
The most common approach in shared-schema multi-tenant systems is to put a tenant_id on every table and write the filter into every query:
SELECT * FROM orders WHERE tenant_id = $1 AND status = 'open';
It works, until someone forgets it in one query. A system with more than 150 tables has hundreds of queries: reports, bulk operations, background jobs, an export written in a hurry. Code review catches it most of the time, and "most of the time" is not good enough here. Security should not depend on every developer remembering it in every query.
So we turned the rule around: application code does not write the tenant filter; the database enforces it.
PostgreSQL Row Level Security
PostgreSQL's Row Level Security (RLS) lets you attach a policy to a table: who may see a row, who may write it. The database adds the policy to every query; the application does not need to know.
In Courino, every tenant table is isolated with a single helper:
CREATE FUNCTION current_tenant() RETURNS uuid
LANGUAGE sql STABLE AS $$
SELECT nullif(current_setting('app.tenant_id', true), '')::uuid
$$;
-- For every tenant table:
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_tenant())
WITH CHECK (tenant_id = current_tenant());
Those few lines hold four separate decisions:
USING: reads, updates and deletes only touch that tenant's rows. Another company's row never appears in a result, andUPDATEandDELETEcannot find it.WITH CHECK: thetenant_idof a row being written is checked too. If a bug tries toINSERTwith another company's ID, the database refuses.FORCE: by default RLS does not apply to the table's owner. WithFORCEthe owner is bound by the policy as well, so a mistake like connecting with the wrong role cannot quietly switch the protection off.- No setting means NULL: if no tenant is set, the function returns NULL.
tenant_id = NULLis never true, so the policy matches no rows. A forgotten setting means seeing nothing rather than seeing every company. That is the default that fails safe.
Then there is the role the application connects as: not a superuser, and without BYPASSRLS. It can read and write data; it cannot create or drop tables or change a policy. A separate role runs the migrations.
How the tenant gets to the query
The remaining question: how does the database know app.tenant_id?
Courino's backend is written in Go. When a request arrives, the authentication layer resolves the company from the session and puts it into Go's context.Context. Every piece of database work goes through this function:
func (db *DB) InTenantTx(ctx context.Context, fn func(pgx.Tx) error) error {
id, err := tenant.MustFromContext(ctx) // no tenant is an error, never a silent fallback
if err != nil {
return err
}
return db.inTx(ctx, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `select set_config('app.tenant_id', $1, true)`, id); err != nil {
return err
}
return fn(tx)
})
}
Repository code writes plain SQL inside it, with no WHERE tenant_id. Background jobs (sending notifications, scheduled tasks, building reports) carry the company's ID when they are queued, and the worker sets up the same context with the same function.
Trap 1: SET LOCAL takes no parameters
The first thing that comes to mind is:
SET LOCAL app.tenant_id = $1;
But SET is not a planned statement, so the driver (pgx for us) cannot bind a parameter to it. You would have to splice the value into the SQL text, which is an open door for SQL injection. Even with a value that came from an authenticated session, we did not want string concatenation inside the security layer itself.
The answer is the set_config() function: an ordinary function, so it takes parameters. With true as its third argument its effect is limited to the transaction: the same scope as SET LOCAL, but safe.
Trap 2: a setting left behind in the connection pool
This is the dangerous one. set_config(..., true) is local only inside an open transaction. Called on a bare pooled connection without a transaction, the setting stays on the connection. When the pool hands that connection to the next request, perhaps another company's, the previous company's ID is still there.
So:
- The tenant is set only inside
InTenantTx, which opens the transaction itself; callers cannot get a bare connection from it. - A test tries exactly this: it uses every connection in the pool for one company's queries, then checks with tenant-less queries that the setting is empty on every connection.
Trap 3: a foreign key can point at another company's record
RLS hides rows, but foreign key checks run past the policy. If price_list_cells.price_list_id referenced only price_lists(id), one company could guess the ID of another company's price list and add cells to it: unable to see the row, but able to link to it.
So foreign keys between tenant tables are composite:
FOREIGN KEY (tenant_id, price_list_id) REFERENCES price_lists (tenant_id, id)
The row's tenant_id is already locked to the company by WITH CHECK, so the record it points at must belong to the same company. An attempt to link to another company's record fails with a foreign key violation.
Making a machine check the rule
The right design alone is not enough; a table added six months from now must get the same protection. We have three checks for that:
- A catalog test. A test walks every table in the database catalog: does every table with a
tenant_idcolumn have RLS andFORCEon, and a policy? Tables without atenant_id(such as the company records themselves, or the nationwide holiday calendar) are listed with a reason. A new table withouttenant_idthat is not on the list breaks the test. - A role test. It checks that the application role is not a superuser, does not have
BYPASSRLSand cannot drop a table. - An architecture check. A script in CI forbids a hand-written
WHERE tenant_id =in module code, and running queries straight off the pool. A hand-written filter is a sign that someone is working in the wrong layer.
The isolation tests run against a real PostgreSQL too: they create two companies and try, one by one, counting, writing on behalf of the other company, updating and deleting its rows, and linking to its records through a foreign key.
The cost
RLS is not free, but it cost less than we expected:
- Indexes should start with
tenant_id. The policy addstenant_id = ...to every query, so frequently used indexes start with it, like(tenant_id, status, ...). Tables that others point at also carry a(tenant_id, id)unique key for the composite foreign keys. - Every unit of work is a transaction. Even a single read runs in one. For screens that combine several tables there is also a read-only, single-snapshot (
REPEATABLE READ) variant, so a screen never shows half old and half new data. - Platform work takes a separate path. Work across all companies (such as the platform admin console) is outside this rule, on a separate, audited path. We keep those exceptions few on purpose.
What we learned
- Tie security to the default, not to memory. When something is forgotten, the system should fail by showing nothing.
- Do not concatenate strings in the security layer. Parameterised
set_configinstead ofSET LOCAL. - Treat the connection pool as a threat. Any setting that outlives its transaction is a candidate to leak into the next request.
- Have tests and CI enforce the rule. "Enable RLS on every table" as a line in a document gets forgotten; a test that walks the catalog does not.
You can find out more about Courino and what it offers courier companies on the product's site.