Member-only story
Multi-Tenancy Support With Spring Boot, Liquibase, and PostgreSQL
A step-by-step guide on how to implement multi-tenancy

Multi-Tenancy Models
There are multiple models to achieve multi-tenancy in a microservice:
- Database per Tenant: Each tenant has its own database and is isolated from other tenants.
- Shared database, Separate Schema: All tenants share a database, but have their own database schemas and their own tables.
- Shared Database, Shared Schema: All tenants share the same database and schema. Shared tables have a column with the tenant identifier, which shows the owner of the row.
Each model has its pros and cons. For this story, we are going to focus on the third model, shared database, shared schema, shared tables having a discriminator column with the tenant identifier. See diagram below.

Multi-Tenancy Implementation in Database
Data Isolation: PostgreSQL Row Level Security (RLS)
For data isolation, we are going to use PostgreSQL Row Level Security (RLS). RLS is a PostgreSQL security feature which allows database administrators to define policies to control how specific rows of data display and operate for one or more roles. RLS is, in essence, an additional filter we can apply to a PostgreSQL database table. When a user tries to perform an action on a table, this filter is applied before the query criteria or other filtering, and the data is narrowed or rejected according to the security policy. We can create row level security policies for specific commands like SELECT, INSERT, UPDATE, and DELETE.
Add a discriminator column
A discriminator column, say tenant_id
, needs to be added in tables where multi-tenancy support is needed. We are going to use a demo Spring Boot microservice named customer-service as example. It’s a simple microservice which handles customer CRUD operations. Let’s assume we need multi-tenancy support…