Video in progress
What is Row-Level Security (RLS), and how do you use it in a multi-tenant Spring application?
RLS puts a policy on a table: for every query the database itself adds the condition tenant_id = current tenant. Even if the application forgets to write WHERE tenant_id, another tenant's data isn't visible. The current tenant is usually supplied at the start of the transaction with set_config.
📖 Answer
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY; -- apply it to the table owner too
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::bigint)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
USING filters the rows that are read and the rows being modified, and WITH CHECK forbids writing under another tenant's name.
On the Spring side you have to set the tenant at the start of every transaction:
@Transactional
public List<Invoice> list() {
jdbc.queryForObject("SELECT set_config('app.tenant_id', ?, true)",
String.class, TenantContext.current().toString());
return invoiceRepo.findAll();
}
The third argument true means the value applies only to this transaction (like SET LOCAL). That matters: a connection from the pool is handed to the next request with a different tenant. If you set it at the session level, one tenant's data can leak to another. In practice you don't write this in every method; you move it into an aspect or a component hooked into the start of the transaction.
Things to watch:
- superuser and
BYPASSRLSroles bypass the policy, so the application must not connect with such a role; - the column in the policy condition needs an index, otherwise every query is slow;
- migrations and admin scripts will need a separate role.
RLS doesn't replace the filter in the application; it's a second layer of protection.
Sign up to mark studied questions and save your progress.