Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write PostgreSQL row-level security for a shared invoices table with a tenant_id column so that each connection only sees its tenant's rows, and show how a Spring service sets the tenant.

We enable row-level security on invoices and add a policy that compares tenant_id with current_setting('app.tenant_id')::uuid, using FORCE ROW LEVEL SECURITY if the application connects as the table owner. At the start of each transaction, Spring runs SELECT set_config('app.tenant_id', ?, true), so the setting is local to that transaction and cannot leak to the next user of a pooled connection, and we test that a missing tenant fails closed.

Why this question is asked

In a shared-table SaaS database, one missing WHERE tenant_id = ? clause shows a customer someone else's invoices. Code review cannot guarantee that every query in every service has the filter. Row-level security moves the rule into the database, so even a forgotten filter returns only the right tenant's rows. Interviewers ask this as a coding question because the details matter: who bypasses the policy, how the tenant reaches the database through a connection pool, and what happens when it is missing. In this answer, we will recap RLS, write the policy, set the tenant per transaction from Spring, see why session settings leak through pools, and write the tests.

1A Quick Recap of Row-Level Security

Row-level security, RLS, lets PostgreSQL filter rows per query according to policies on the table. Once it is enabled, every SELECT, UPDATE and DELETE behaves as if the policy's condition were added to its WHERE clause, and every INSERT or UPDATE is checked against it. If a table has RLS enabled and no policy matches, the user sees no rows at all.

A custom setting such as app.tenant_id is a configuration parameter we invent. Any name with a dot in it is allowed. set_config writes it and current_setting reads it, so the application can tell the database which tenant the current work is for.

2Writing the Policy

Here is the table, the policy and the two switches that make RLS apply.

SQL
CREATE TABLE invoices (
id bigint PRIMARY KEY,
tenant_id uuid NOT NULL,
amount numeric(19,4) NOT NULL
);
CREATE INDEX invoices_tenant_idx ON invoices (tenant_id, id);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- apply even to the table owner
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid);
-- no WITH CHECK given, so USING also checks inserted and updated rows

The reason for FORCE is that the table owner bypasses RLS by default. Many applications connect as the same role that ran the migrations and therefore owns the tables, and without FORCE the policy silently does nothing for them. Superusers and roles with BYPASSRLS skip policies regardless, so the application role must be neither. A cleaner setup uses a separate migration role that owns the tables and an application role that only has the privileges it needs.

Because the policy has only a USING clause and applies to all commands, PostgreSQL also uses it as the WITH CHECK condition. An INSERT of a row with another tenant's id fails with an error that the new row violates the row-level security policy.

3Setting the Tenant Per Transaction

Now the application must set app.tenant_id before its queries run. The third argument of set_config decides the scope. With true, the value is local to the current transaction and disappears at COMMIT or ROLLBACK. With false, it stays for the whole session, which with a connection pool means for whoever borrows that connection next.

SQL
BEGIN;
SELECT set_config('app.tenant_id', '7c0e...-a1', true);
SELECT count(*) FROM invoices; -- 120: only tenant a1's rows
COMMIT;
SELECT count(*) FROM invoices; -- ERROR: invalid input syntax for type uuid: ""
-- outside the transaction the setting is gone, so the query fails instead of showing rows
Step throughOne request through a pooled connection
ControllerTx managerPoolPostgreSQL
call service, tenant a1 in context
borrow connection
BEGIN
set_config('app.tenant_id', a1, true)
SELECT ... FROM invoices
only a1 rows
COMMIT: setting cleared
return clean connection

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

Notice the failure at the end. After a transaction-local setting ends, the parameter reverts to an empty string on that connection, and casting the empty string to uuid raises an error. On a connection that never set it, current_setting raises an 'unrecognized configuration parameter' error instead. Either way the query fails closed: no tenant means no data, never all data.

4Doing It in Spring

The hook must run inside the transaction, on the same connection the repositories will use, before any query. One reliable place is the transaction manager itself. We extend JpaTransactionManager so that right after it begins a transaction, it runs set_config through the transaction's EntityManager. The tenant comes from a request-scoped holder filled by a filter that reads it from the authenticated user, never from a header the client controls.

Java
public final class TenantContext {
private static final ThreadLocal<UUID> CURRENT = new ThreadLocal<>();
public static void set(UUID t) { CURRENT.set(t); }
public static void clear() { CURRENT.remove(); }
public static UUID require() {
UUID t = CURRENT.get();
if (t == null) throw new IllegalStateException("no tenant for this transaction");
return t;
}
}
public class TenantAwareTransactionManager extends JpaTransactionManager {
public TenantAwareTransactionManager(EntityManagerFactory emf) { super(emf); }
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
super.doBegin(transaction, definition);
EntityManager em = EntityManagerFactoryUtils.getTransactionalEntityManager(getEntityManagerFactory());
em.createNativeQuery("select set_config('app.tenant_id', :t, true)")
.setParameter("t", TenantContext.require().toString())
.getSingleResult(); // runs on the transaction's connection
}
}
@Bean
PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
return new TenantAwareTransactionManager(emf); // replaces Boot's default bean
}

Other designs work too, such as a DataSource wrapper or an aspect ordered to run inside the transactional advice. Whatever we choose, two rules hold: the call uses true for transaction scope, and the filter clears the ThreadLocal in a finally block so a pooled request thread does not carry one tenant into the next request. Code that runs without a transaction, such as a read with no @Transactional, would bypass this hook, so we either make all data access transactional or fail such reads with the error we saw above.

5Testing the Isolation

RLS is a security control, so we test it like one, against a real PostgreSQL started by Testcontainers and connected as the application role, not as a superuser.

Java
@Test void tenantSeesOnlyOwnInvoices() {
TenantContext.set(TENANT_A);
assertThat(invoiceService.countAll()).isEqualTo(2); // A has 2, B has 3
}
@Test void insertForOtherTenantIsRejected() {
TenantContext.set(TENANT_A);
assertThatThrownBy(() -> invoiceService.create(TENANT_B, new BigDecimal("10")))
.hasMessageContaining("row-level security");
}
@Test void missingTenantFailsClosed() {
TenantContext.clear();
assertThatThrownBy(() -> invoiceService.countAll())
.isInstanceOf(IllegalStateException.class); // never returns 5
}

A last test borrows the same pooled connection twice, first for tenant A and then without a tenant, to prove nothing leaks between transactions.

6Follow-up questions

Does RLS slow queries down?

The policy condition is added to each query, so with an index starting with tenant_id the cost is small. Keep the policy expression simple and stable; calling heavy functions or subqueries in a policy can hurt every query on the table.

Why not use SET app.tenant_id instead of set_config?

SET LOCAL app.tenant_id = '...' is equivalent to set_config with true, but SET cannot take a bind parameter, so we would have to build SQL by string concatenation. set_config accepts parameters and avoids injection.

Who should bypass RLS on purpose?

Only specific roles for migrations, backups or cross-tenant support tools, granted BYPASSRLS or separate policies, and used by separate, audited connections, never by the main application role.

7Conclusion

In this answer, we saw how to protect a shared invoices table with PostgreSQL row-level security: ENABLE ROW LEVEL SECURITY, a tenant_isolation policy comparing tenant_id with current_setting('app.tenant_id')::uuid, and FORCE ROW LEVEL SECURITY when the application role owns the table. Each transaction runs set_config('app.tenant_id', ?, true) so the value cannot leak through pooled connections, Spring sets it in a transaction-aware hook such as a custom transaction manager, and tests prove isolation, rejected cross-tenant writes, and that a missing tenant fails closed.

What to say in the interviewAbout 80 seconds aloud

Open with

I would enable row-level security on the invoices table and create a policy, say tenant_isolation, with USING tenant_id equals current_setting of app.tenant_id cast to uuid. Since no WITH CHECK is given, the same condition also checks inserts and updates, so nobody can write a row for another tenant.

Then, if they want more

If the application connects as the table owner I also need FORCE ROW LEVEL SECURITY, because owners bypass RLS by default, and the application role must not be a superuser or have BYPASSRLS. Ideally migrations run as a separate owner role. For setting the tenant, the key detail is connection pooling.

I run select set_config('app.tenant_id', the tenant, true) at the start of each transaction. The true makes it transaction-local, so at commit it is cleared and the next borrower of that connection cannot see the old tenant.

In Spring I would do it in a transaction-aware hook, for example a subclass of JpaTransactionManager that runs the set_config right after doBegin, taking the tenant from a context filled from the authenticated user and cleared after each request.

Then I would test with Testcontainers as the real application role: a tenant sees only its rows, cross-tenant inserts fail, and a missing tenant raises an error instead of returning everything.

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 shared invoices table with a tenant_id column...": https://scrivio-interview-library.netlify.app/databases/data-modeling/97cf980bf5/