Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write PostgreSQL row-level security for a multi-tenant table invoices(tenant_id, ...) so each application session only sees its tenant's rows, and show how a Java service sets the tenant per transaction.

We enable row-level security on invoices and add a policy that compares tenant_id with a custom setting, app.tenant_id, in both USING (rows we can see) and WITH CHECK (rows we may write). The Java service runs SELECT set_config('app.tenant_id', ?, true) at the start of every transaction, so the value is local to that transaction and disappears at commit, which keeps pooled connections clean. The application must connect as a non-owner role without BYPASSRLS, ideally with FORCE ROW LEVEL SECURITY, and tenant_id must be indexed.

Why this question is asked

Multi-tenant SaaS products usually keep all tenants in the same tables, and the biggest fear is a missing WHERE tenant_id = ? in one query showing one customer another customer's invoices. Row-level security moves that filter into the database, so even a forgotten condition cannot leak rows. Interviewers ask for the code because the details matter: the setting must be per transaction, the role must not bypass policies, and the empty-setting case must fail safely. In this answer, we will recap what row-level security is, write the policy, set the tenant from Java per transaction, close the bypass gaps, and test it.

1A Quick Recap of Row-Level Security

Row-level security, RLS, lets a table have policies, which are conditions PostgreSQL adds automatically to every query on that table. A USING expression decides which existing rows a query can see, update or delete. A WITH CHECK expression decides which new or changed rows a statement is allowed to write. When RLS is enabled and no policy matches, the default is to deny: the role sees no rows at all.

For tenant isolation we need a way to tell the policy which tenant the current request belongs to. PostgreSQL has custom settings, names with a dot such as app.tenant_id, that a session can set with set_config and read with current_setting. The policy compares each row's tenant_id with that setting.

2Writing the Policy

Here is the SQL, run by the table owner in a migration. The application connects as a separate role, app_rw, that has only DML grants.

SQL
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- applies even to the table owner
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
CREATE INDEX invoices_tenant_created ON invoices (tenant_id, created_at);

A few details here do real work. The second argument true in current_setting means missing is fine: if app.tenant_id was never set, it returns NULL instead of raising an error. NULLIF turns an empty string into NULL as well, which matters because after a transaction-local setting ends, the session remembers the name with an empty value. In both cases the comparison tenant_id = NULL is never true, so the query sees no rows. That is the safe failure we want: a bug that forgets the tenant shows nothing, not everything.

The WITH CHECK clause stops a tenant from inserting a row with someone else's tenant_id or moving a row to another tenant with UPDATE. The index starts with tenant_id because every query now includes the policy's condition, and without such an index the planner may scan the whole table for each tenant.

3Setting the Tenant per Transaction From Java

Now the service must set app.tenant_id on the same connection, inside the same transaction, as the queries it runs. In Spring, a JdbcTemplate call inside a @Transactional method uses the transaction's connection, so a small helper called at the start of each transactional method is enough.

Java
@Service
class InvoiceService {
private final JdbcTemplate jdbc;
private final InvoiceRepository invoices;
@Transactional(readOnly = true)
public List<Invoice> listInvoices() {
UUID tenant = TenantContext.current(); // from the authenticated request
jdbc.queryForObject("SELECT set_config('app.tenant_id', ?, true)",
String.class, tenant.toString()); // true = local to this transaction
return invoices.findAll(); // SELECT * FROM invoices -> only this tenant's rows
}
}
Step throughOne request with a pooled connection
RequestServiceHikari poolPostgreSQL
GET /invoices as tenant A
begin transaction, borrow connection
set_config('app.tenant_id', A, true)
SELECT * FROM invoices
rows of tenant A only
COMMIT: local setting is discarded
return connection, no tenant left on it

7 messages in order. Play them, or step through them one at a time.

The setting lives exactly as long as the transaction.

The third argument true to set_config is the same as SET LOCAL: the value lives until the transaction commits or rolls back, then it is gone. That is why this is safe with HikariCP. A pooled connection is returned to the pool after the transaction, and the next request that borrows it starts with no tenant, so it cannot accidentally inherit the previous tenant.

In a larger service we would not repeat these lines in every method. A common approach is an aspect or a TransactionSynchronization that runs set_config whenever a transaction begins, or a custom transaction manager that does it right after beginning the transaction. With JPA, the JdbcTemplate shares the JPA transaction's connection when the JpaTransactionManager is used with Hibernate, so the setting applies to the repository queries as well.

4Closing the Bypass Gaps

Policies do not apply to everyone. The table owner bypasses RLS by default, which is why we connect as app_rw rather than as the owner and also add FORCE ROW LEVEL SECURITY so the owner is covered too. Superusers and roles with the BYPASSRLS attribute always skip policies, so the application role must have neither. A quick check prevents surprises.

SQL
SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolname = 'app_rw';
-- app_rw | f | f
SELECT relrowsecurity, relforcerowsecurity FROM pg_class WHERE relname = 'invoices';
-- t | t

5Testing That Isolation Holds

RLS is a security control, so it deserves tests that run against a real PostgreSQL, for example with Testcontainers. We insert invoices for two tenants as the owner, then connect as app_rw and check three cases: with tenant A set we see only A's rows, with no setting we see zero rows, and inserting a row for tenant B while tenant A is set fails with a policy violation.

SQL
-- as app_rw, no tenant set
SELECT count(*) FROM invoices; -- 0
BEGIN; SELECT set_config('app.tenant_id', 'aaaaaaaa-0000-0000-0000-000000000001', true);
SELECT count(*) FROM invoices; -- 3 (tenant A only)
INSERT INTO invoices (tenant_id, amount) VALUES ('bbbbbbbb-0000-0000-0000-000000000002', 10);
-- ERROR: new row violates row-level security policy for table "invoices"
ROLLBACK;

The empty-setting test is the most important one, because it proves that the most likely bug, a code path that forgets to set the tenant, fails closed.

6Follow-up questions

What happens if the setting is set at session level instead?

With set_config(..., false) or a plain SET, the value stays on the connection after the transaction ends. Because HikariCP reuses connections, the next request that borrows that connection starts with the previous tenant's id, and if that code path forgets to set its own tenant, it sees another tenant's invoices. That turns the safe failure into a data leak, so the setting must always be transaction-local.

Can a malicious query inside the application change app.tenant_id?

Yes, any SQL the application role runs can call set_config, so RLS protects against forgotten filters and bugs, not against an attacker who can run arbitrary SQL as app_rw. For stronger guarantees some teams use a separate database role per tenant or sign the tenant value, but for most services the transaction-local setting plus the absence of SQL injection is the practical balance.

Does RLS replace tenant checks in the application?

It complements them. The application still decides which tenant the request belongs to from the authenticated user, and it often still filters by tenant for clarity and plan stability. RLS is the safety net that catches the query where someone forgot.

7Conclusion

In this answer, we enabled row-level security on invoices with a policy that compares tenant_id to app.tenant_id in both USING and WITH CHECK, using current_setting with missing_ok and NULLIF so a missing tenant returns no rows. The Java service sets the tenant with set_config(..., true) inside each transaction, which is safe with connection pools because the value is discarded at commit. We connected as a non-owner role without BYPASSRLS, added FORCE ROW LEVEL SECURITY, indexed tenant_id, and tested that a query without the setting sees nothing.

What to say in the interviewAbout 90 seconds aloud

Open with

I would enable row-level security on invoices and also FORCE it, so even the owner is subject to it. The policy compares tenant_id with a custom setting, current_setting of app.tenant_id with the missing-ok flag, wrapped in NULLIF so an empty value becomes NULL, cast to uuid.

Then, if they want more

I use the same expression in USING, which filters reads, updates and deletes, and in WITH CHECK, which stops writing rows for another tenant. If the tenant is not set, the comparison is never true and the query returns no rows, so it fails closed.

In the Java service, at the start of each transaction I run SELECT set_config('app.tenant_id', tenant, true). The true makes it transaction-local, like SET LOCAL, so it disappears at commit, which matters with HikariCP: the next request on that connection does not inherit the tenant.

In Spring I would put that in an aspect or transaction synchronization so every transactional method gets it, and JdbcTemplate shares the JPA transaction's connection. The application must connect as a non-owner role without superuser or BYPASSRLS, because those skip policies. I index tenant_id, usually as the first column of composite indexes, so the policy does not cause scans.

And I test against real PostgreSQL that a query without the setting returns zero rows and that inserting another tenant's row fails.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write PostgreSQL row-level security for a multi-tenant table invoices(tenant_id, ...) so...": https://scrivio-interview-library.netlify.app/databases/database-security/234d18f2a1/