DEV Community

Aayush Ghimire
Aayush Ghimire

Posted on

Simplifying PostgreSQL RLS in JPA with JPA Postgres RLS

Bringing PostgreSQL Row-Level Security to JPA
I’ve been working on a lightweight Spring Boot library to simplify data isolation. JPA Postgres RLS automates PostgreSQL Row-Level Security (RLS) binding for JPA entities.
The challenge: keeping the application context and the database session in sync.
JPA Postgres RLS solves this by:
Validating RLS rules at application startup
Using Spring AOP to bind session variables via custom annotations
Ensuring type-safe mapping from Java objects to SQL session settings
Key features:
Automatic @RlsSession binding
Fail-fast startup validation for missing policies or variables
Transaction-scoped session variables
Built with Java 21 and Spring Boot 3.4, this library is ideal for multi-tenant SaaS applications. I’d love your feedback and contributions!

Why I made this:
While working with PostgreSQL RLS, I often forgot to create policies or enable row-level security. Simple mistakes like these or mismatched session variable names, could break an app at runtime. There was no way to catch these issues automatically, and no one would notice until something suddenly failed.

So, I decided to build a core library with startup validation and automatic session binding. The project grew as I added more ideas, and I made it open-source so others facing the same challenges can benefit.

Lessons from version 1:

Initially, I tried automatic policy creation and RLS enabling, but working with DDL proved error-prone. For version 2, I focused on validation and auto-filling session variables instead.

Check out the code: https://github.com/aayushghimirey/jpa-postgres-rls.git

Top comments (0)