Making an existing Spring Boot app multi-tenant: one codebase, one database, two institutions

I work on an online exam portal: Spring Boot backend, Angular frontend, MySQL. Admins build question banks and exams, students take timed tests, and results come back to the admins. It was built for one institution. When a second institution wanted it, the quickest route was a copy: a second deployment with its own database.

That works for a while. Then every fix has to be made twice, the two copies slowly drift apart, and adding a third institution means a third copy. This post is about how I turned the existing app into one multi-tenant application: one codebase, one database, both institutions' real data moved in, and tests that prove neither can see the other.

Short version: a tenant_id column on every table, Hibernate 6's @TenantId to filter every query and stamp every insert automatically, a request filter that works out the tenant, and a test suite on a real MySQL container that tries to cross the boundary in every way I could think of. The careful part was the data: merging two live databases without a single ID or reference getting mixed up.

Where it started

  • Java 17, Spring Boot 3.5 (Hibernate 6.6), MySQL, Angular, 20 tables, 19 JPA entities.
  • Two copies, two databases. Same 20 tables in both. Comparing the dumps showed exactly one schema difference: a subject_name column was 50 characters and required in one copy, 100 and optional in the other.
  • Very different sizes. Institution A: about 60 students and 3,000 answer rows. Institution B: about 2,000 students, 6,600 questions and 215,000 answer rows.
  • No schema migrations. The schema had grown by hand. There was also a config typo: the ddl-auto property was under the wrong key, so Hibernate never checked the entities against the tables at all.
  • Things hardcoded for one customer: the "created by" admin on new exams was always admin id 1, and the institution's name was typed into the navbar and login page.

Picking the model

There are three common ways to separate tenants:

Shared tables + tenant_id Schema per tenant Database per tenant
New tenant insert a row create a schema, run migrations same as schema
Migrations run once run N times, can drift run N times
Isolation in the application strong strongest

I went with shared tables and a tenant_id column. The reasons were specific to this project:

  • In MySQL a schema is a database, so "schema per tenant" is just the setup we already had and wanted to leave.
  • The data is small (the biggest table is about 215k rows) and the expected number of tenants is in the tens.
  • It's one team with one deployment. One schema, one migration run and one connection pool is the least to look after.
  • If a customer ever asks for a dedicated database, that one tenant can be moved out later. The tenant_id column makes that export easier, not harder.

The cost is that isolation lives in the application, so a coding mistake can leak data. Most of the design below is about making that mistake hard to make and easy to catch.

Step 1: get the schema under control first

Before any tenant work, the database needed proper migrations. I added Flyway with the existing schema as V1__baseline.sql and baseline-on-migrate, so the running database is marked as version 1 and only new migrations run on it. A fresh test database builds from V1 upward.

I also fixed the config typo and set spring.jpa.hibernate.ddl-auto=validate. From then on, any mismatch between an entity and its table stops the app at start-up instead of failing later.

Then the tenant migrations:

  • V2: a tenants table (id, slug, name, status) and a tenant_domains table for mapping hostnames later.
  • V3: tenant_id BIGINT NOT NULL DEFAULT 1 on all 20 tables, with an index and a foreign key to tenants. The DEFAULT 1 means every existing row becomes tenant 1 in place, and the old single-tenant build can still run against the new schema, which is the rollback plan.
  • V4: unique keys per tenant. This one is easy to miss. email, roll_number, exam_code and subject_code were unique across the whole table. With two institutions in one table, both can have a student with the same roll number. Every one of those became (tenant_id, column):
ALTER TABLE students DROP INDEX uk_students_roll_number;
ALTER TABLE students ADD CONSTRAINT uk_students_tenant_roll UNIQUE (tenant_id, roll_number);

I took the exact constraint names from SHOW CREATE TABLE instead of guessing them, and updated the @Table(uniqueConstraints = ...) on the entities to match, so validate keeps them in step. - V5: widened subject_name to the larger of the two versions, so both datasets fit.

Step 2: move the second institution's data in

Institution A's data stays where it is, with its IDs unchanged (that will matter for the production migration). Institution B's data comes in as tenant 2 from its own dump. The problem is that both databases have, say, an exam with id 42.

The fix is an ID offset: every primary key and every column that refers to an ID in B's data gets +1,000,000. B's largest id was about 286,000, so there is no overlap.

INSERT INTO exam360.exam_questions (id, exam_id, question_id, marks, tenant_id)
SELECT id + 1000000, exam_id + 1000000, question_id + 1000000, marks, 2
FROM   stage_b.exam_questions;

The important words are "every column that refers to an ID". The database had 28 foreign keys, but some ID columns had none (exam attempts, for example). A list built from the foreign keys alone would have missed them, and those rows would then point at the wrong records in the other institution. So I built the column list from both the entity classes and the dump. NULL references stay NULL, because NULL + 1000000 is NULL in MySQL.

The import is a script, not a Flyway migration, because it runs once. A separate verify script then checks:

  • row counts per table: B's staging copy equals tenant_id = 2 in the merged database, and A's counts equal the snapshot taken before migrating;
  • no reference crosses tenants, for every reference column:
SELECT COUNT(*) FROM exam_questions eq
JOIN questions q ON q.question_id = eq.question_id
WHERE q.tenant_id <> eq.tenant_id;      -- must be 0

Everything came back clean except some exam attempts pointing at exams and students that no longer existed. I checked the original dumps: those orphans were already there, from records deleted in the old app, and the table has no foreign key to stop that. They weren't caused by the import, and the runbook says so, so nobody spends an hour on them later. The whole import runs in about 23 seconds locally.

Step 3: the tenant in every request

Working out the tenant. A servlet filter runs on every /api/ request. It takes the tenant from the hostname's subdomain (a.example.com), or from an X-Tenant header that the Angular app sends. If both are present they must agree. No tenant gives 400, an unknown one 404, a suspended one 403. The tenant goes into a ThreadLocal and into the logging MDC, so every log line shows which tenant it belongs to, and both are cleared in a finally block. Servlet threads are reused, and a tenant left behind by one request must never leak into the next.

Letting Hibernate do the filtering. Every tenant entity extends one base class:

@MappedSuperclass
public abstract class TenantScopedEntity {
    @TenantId
    @Column(name = "tenant_id", nullable = false, updatable = false)
    private Long tenantId;
}

With @TenantId, Hibernate adds tenant_id = ? to queries and fills in tenant_id on insert by itself. It asks a resolver for the current tenant:

@Component
public class TenantIdentifierResolver
        implements CurrentTenantIdentifierResolver<Long>, HibernatePropertiesCustomizer {

    static final Long NO_TENANT = -1L;

    @Override
    public Long resolveCurrentTenantIdentifier() {
        Long id = TenantContext.get();
        return id != null ? id : NO_TENANT;     // never "all tenants"
    }

    @Override
    public boolean validateExistingCurrentSessions() { return true; }

    @Override
    public void customize(Map<String, Object> props) {
        props.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
    }
}

The -1 is the fail-closed part. Hibernate can call the resolver outside a request (at start-up, for example), so throwing there causes trouble. Returning a tenant that doesn't exist means a read with no tenant finds nothing, and an insert with no tenant breaks the foreign key to tenants. A missing tenant can never turn into "show everything".

I chose this over the alternatives on purpose. Adding a tenant parameter to around 70 repository methods by hand means one forgotten method is a leak. A Hibernate @Filter has to be switched on for every session and doesn't cover inserts. @TenantId covers reads and writes with the smallest amount of code to get wrong.

Step 4: the gap the ORM doesn't close

This is the one I'd most like other developers to take away. @TenantId filters what you load. It does nothing for an ID you store without loading.

Creating an exam takes a list of questionIds from the request body and saves them in a link table. If tenant A sends one of tenant B's question ids, the database foreign key is perfectly happy, because the question exists. A foreign key checks that a row exists, not who it belongs to. Tenant A's exam would now include tenant B's question.

The fix is a small helper that every such ID goes through:

public static <ID> void requireExists(CrudRepository<?, ID> repo, ID id, String name) {
    if (id != null && !repo.existsById(id)) {           // tenant-filtered by @TenantId
        throw new ResourceNotFoundException(name + " not found with id: " + id);
    }
}

Because the lookup is tenant-filtered, another tenant's id simply comes back as "not found" (404), the same as an id that doesn't exist. I listed every place a service saves a raw ID (question, subject, topic, class, academic year and student ids in exam setup and assignment; exam, student, question and attempt ids in the exam-taking flow) and put the check in each one.

The hardcoded "admin 1" was the same kind of problem: after the merge, every exam that tenant B created would have belonged to tenant A's admin. For now it uses the current tenant's first active admin, which the tenant filter picks automatically, with a TODO to use the logged-in admin once proper authentication is in.

Step 5: the frontend

One small Angular HttpInterceptorFn reads the first part of the hostname and adds X-Tenant to every API call. For local testing I used a.localhost:4200 and b.localhost:4200. Chrome and Firefox send any *.localhost name to 127.0.0.1 without editing /etc/hosts, and each name gets its own session storage, so I could stay logged in to both tenants in two windows at once. The navbar and login page now show the tenant's name from a public /api/public/tenant endpoint instead of a hardcoded one, which also makes it obvious which tenant you are testing.

Step 6: prove it

Mocked tests can't show that one tenant can't see another's data, so the tests run against a real MySQL 8 in Testcontainers. Flyway builds the schema from V1, and a seed script creates two tenants with deliberately identical emails, roll numbers, exam codes and subject codes, so anything that ignores the tenant shows up.

Every test goes both ways, A → B and B → A:

Case Expected
list endpoints only your own rows
get another tenant's record by id 404, never the data
update, publish or delete another tenant's record 404, and their row is unchanged
derived deleteBy... methods only touch the current tenant
create something row gets the request's tenant, and that tenant's admin
same email / roll number in both tenants allowed; a duplicate inside one tenant is rejected
log in with A's credentials on B fails
put B's question / student / class ids into A's exam rejected, nothing saved
A's student starts or answers B's exam rejected
missing, unknown or suspended tenant; host and header disagree 400 / 404 / 403
a request that throws, then the next request on the same thread correct tenant, nothing left over

There is also a rules test that reads the code itself:

  • every @Entity must extend TenantScopedEntity (with a short allowlist for global tables like tenants);
  • no native SQL anywhere in src/main: no nativeQuery = true, no createNativeQuery, no JdbcTemplate. Hibernate's tenant filter doesn't touch native SQL, so one native query would quietly bypass everything above.

The suite is at 38 tests, all passing. The same rules are written in the project's contributor notes: extend the base class, no native SQL, guard every stored ID, unique keys per tenant, and a new isolation test with every new feature.

Same problem, different answer: the admissions ERP

I've also worked on tenant scoping in an admissions ERP, and there I made the opposite choice: a Hibernate @Filter instead of @TenantId. That wasn't inconsistency. The two domains are different:

Exam portal Admissions ERP
A user belongs to exactly one tenant a set of colleges (a group admin reaches all colleges in the group; some staff work for two or three)
Fits @TenantId: one id per session, filters reads and stamps inserts @Filter with a list parameter (college_id in (:collegeIds)), switched on by one Spring aspect around every service method
Single-record loads covered by @TenantId (checked by test) @Filter doesn't apply to findById, so per-record guards stay as a second layer

Hibernate's built-in multi-tenancy assumes one tenant id per session. In the exam portal that's exactly the model, so the built-in feature is the simplest correct answer. In the ERP it isn't, and forcing it would have meant faking a single tenant for users who really have several. Both decisions are written down in the projects' design notes with the reasons, so the next developer doesn't have to rediscover them.

What's not done yet

I want to be clear about this: the merged version isn't in production yet. Right now the tenant comes from the hostname or a header that the client controls, and the API doesn't have proper authentication yet. With two separate databases that was a smaller risk. With one shared database it would be a real one. So the order is:

  1. JWT authentication with the tenant id inside the signed token, and a check that it matches the hostname's tenant on every request. That's the pre-condition for going live.
  2. A rehearsed production migration from the runbook (drop, reload, migrate, import, verify), timed for a downtime estimate.
  3. Per-tenant file storage. Uploaded question images aren't separated by tenant yet.
  4. Composite foreign keys like (tenant_id, question_id) → questions(tenant_id, question_id), so the database itself refuses a cross-tenant reference, and dropping the DEFAULT 1 from tenant_id so an insert with no tenant fails at the database too.

What I took away

  • Fix the foundations before the feature. Flyway, ddl-auto=validate and a config typo came before any tenant code, and they made every later step safer.
  • Pick the tenancy model from your data and your team, not from what sounds most isolated.
  • Use the ORM's feature when it fits your model, and know where it stops. @TenantId covers what you load. IDs you store without loading need their own check, and native SQL bypasses it completely.
  • Unique keys have to become per-tenant. Otherwise the second institution can't add a student with a roll number the first one already used.
  • When merging databases, remap every ID column, not just the foreign keys, and verify with counts and cross-tenant reference checks, not by eye.
  • Fail closed. No tenant means no rows, never all rows.
  • Test the boundary on a real database, in both directions, with data designed to collide.

Stack: Java 17, Spring Boot 3.5, Hibernate 6.6 (@TenantId, CurrentTenantIdentifierResolver), Spring Data JPA, MySQL 8, Flyway, Testcontainers, JUnit 5, Angular (functional HTTP interceptors).

Related: Access control in a multi-tenant Spring Boot ERP · Authentication in a multi-tenant Spring Boot ERP. More on the Projects page.

Comments

Popular posts from this blog

Load-testing an IoT platform with 3,000 simulated energy meters

Two years of freelancing: what shipping software for paying users taught me

Making prepaid recharges safe: row locks and idempotency keys in Spring Boot