FRT Multi-Tenant Configuration

High-Level Configuration & Implementation Guide

1. Multi-Tenant Deployment Model

Chosen Architecture: One application instance is deployed for one customer/partner. The UI does not send brandId or partnerId. Tenant identity is maintained at deployment/application configuration level.

The same Spring Boot application/JAR can be deployed for multiple customers. Each deployment receives a different brandId and partnerId.

Deployment Brand ID Partner ID Meaning
Customer A 1 101 Customer A application instance
Customer B 1 102 Customer B application instance
Customer C 2 201 Another brand/customer deployment

2. High-Level Architecture

UI | | Normal requests | NO brandId / partnerId v API Gateway | v Spring Boot Application | +--------------------------------+ | Tenant Configuration | | | | FRT_BRAND_ID | | FRT_PARTNER_ID | +---------------+----------------+ | v TenantProperties | v TenantContext | +---------+---------+ | | | v v v Auth Package Test/Question Service Service Services | | | +---------+---------+ | v JPA Repository | v MySQL | brand_id + partner_id
Key Principle: Tenant identity is determined by the application instance, not by the UI request.

3. JVM / VM Configuration

Your existing JVM configuration can contain tenant properties in exactly the same way as your other -D properties.

Complete Example

-Dfrt.api.base-path=http://localhost:8082/
-Dfrt.api.db.url=jdbc:mysql://localhost:3306/frt_test_ser_dev?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
-Dspring.profiles.active=local
-Dfrt.tenant.brand-id=1
-Dfrt.tenant.partner-id=101

Recommended Property Names

Property Example Purpose
frt.tenant.brand-id 1 Brand assigned to this application instance
frt.tenant.partner-id 101 Partner/customer assigned to this application instance
Spring Boot automatically makes JVM -D system properties available through its Environment.

4. TenantProperties

Create one configuration class to centralize tenant properties.

package com.fortress.career.tech.tenant.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "frt.tenant")
public class TenantProperties {

    private Long brandId;

    private Long partnerId;

    public Long getBrandId() {
        return brandId;
    }

    public void setBrandId(Long brandId) {
        this.brandId = brandId;
    }

    public Long getPartnerId() {
        return partnerId;
    }

    public void setPartnerId(Long partnerId) {
        this.partnerId = partnerId;
    }
}

Spring maps:

-Dfrt.tenant.brand-id=1
-Dfrt.tenant.partner-id=101

to:

tenantProperties.getBrandId();    // 1
tenantProperties.getPartnerId();  // 101

5. TenantContext

TenantContext makes the current tenant available to the service/repository layer without adding tenant parameters to every controller request.

package com.fortress.career.tech.tenant;

public final class TenantContext {

    private static final ThreadLocal<TenantInfo> CURRENT_TENANT =
            new ThreadLocal<TenantInfo>();

    private TenantContext() {
    }

    public static void setTenant(
            Long brandId,
            Long partnerId) {

        CURRENT_TENANT.set(
                new TenantInfo(
                        brandId,
                        partnerId
                )
        );
    }

    public static Long getBrandId() {

        return CURRENT_TENANT
                .get()
                .getBrandId();
    }

    public static Long getPartnerId() {

        return CURRENT_TENANT
                .get()
                .getPartnerId();
    }

    public static void clear() {

        CURRENT_TENANT.remove();
    }
}

TenantInfo

package com.fortress.career.tech.tenant;

public class TenantInfo {

    private final Long brandId;

    private final Long partnerId;

    public TenantInfo(
            Long brandId,
            Long partnerId) {

        this.brandId = brandId;
        this.partnerId = partnerId;
    }

    public Long getBrandId() {
        return brandId;
    }

    public Long getPartnerId() {
        return partnerId;
    }
}

6. TenantContextFilter

For Spring Boot 2.7 and Java 11, use javax.servlet.

package com.fortress.career.tech.tenant;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fortress.career.tech.tenant.config.TenantProperties;

@Component
public class TenantContextFilter
        extends OncePerRequestFilter {

    private final TenantProperties tenantProperties;

    public TenantContextFilter(
            TenantProperties tenantProperties) {

        this.tenantProperties =
                tenantProperties;
    }

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain)
            throws ServletException, IOException {

        try {

            TenantContext.setTenant(
                    tenantProperties.getBrandId(),
                    tenantProperties.getPartnerId()
            );

            filterChain.doFilter(
                    request,
                    response
            );

        } finally {

            TenantContext.clear();
        }
    }
}
Important: Always clear the ThreadLocal in finally. Servlet container threads are reused, so failing to clear the context can cause tenant information to leak between requests.

7. Database Design

Tenant-owned tables contain:

brand_id
partner_id

Example

CREATE TABLE test (

    test_id BIGINT NOT NULL,

    brand_id BIGINT NOT NULL,

    partner_id BIGINT NOT NULL,

    test_name VARCHAR(255)

);

Logical Data Organization

Brand 1 | +-- Partner 101 | +-- Users | +-- Packages | +-- Tests | +-- Questions | +-- Attempts | +-- Results | +-- Payments | +-- Partner 102 +-- Users +-- Packages +-- Tests +-- Questions +-- Attempts +-- Results +-- Payments

Recommended Indexes

CREATE INDEX idx_test_tenant
ON test (
    brand_id,
    partner_id
);

CREATE INDEX idx_test_tenant_id
ON test (
    brand_id,
    partner_id,
    test_id
);

8. Entity Design

Use a common TenantAwareEntity for tenant-owned entities.

@MappedSuperclass
public abstract class TenantAwareEntity
        extends BaseAuditEntity {

    @Column(
        name = "brand_id",
        nullable = false
    )
    private Long brandId;

    @Column(
        name = "partner_id",
        nullable = false
    )
    private Long partnerId;

    public Long getBrandId() {
        return brandId;
    }

    public void setBrandId(Long brandId) {
        this.brandId = brandId;
    }

    public Long getPartnerId() {
        return partnerId;
    }

    public void setPartnerId(Long partnerId) {
        this.partnerId = partnerId;
    }
}

Example Entity

@Entity
@Table(name = "test")
public class TestEntity
        extends TenantAwareEntity {

    @Id
    @GeneratedValue(
        strategy = GenerationType.IDENTITY
    )
    @Column(name = "test_id")
    private Long testId;

    // Existing fields...
}
Global/master entities such as Brand, Partner and appropriate role/master tables do not need to inherit from TenantAwareEntity.

9. Service Layer

Controllers and DTOs should generally remain unchanged. Services obtain tenant information internally.

@Service
public class TestService {

    private final TestRepository repository;

    public TestService(
            TestRepository repository) {

        this.repository = repository;
    }

    public List<TestEntity> getTests() {

        Long brandId =
                TenantContext.getBrandId();

        Long partnerId =
                TenantContext.getPartnerId();

        return repository
                .findByBrandIdAndPartnerId(
                        brandId,
                        partnerId
                );
    }
}

Controller Remains Clean

@GetMapping("/tests")
public ResponseEntity<?> getTests() {

    return ResponseEntity.ok(
            testService.getTests()
    );
}
The UI does not need to know or send brandId or partnerId.

10. Repository Layer

SELECT - All Tenant Records

List<TestEntity>
findByBrandIdAndPartnerId(
        Long brandId,
        Long partnerId
);

SELECT - One Record

Optional<TestEntity>
findByTestIdAndBrandIdAndPartnerId(
        Long testId,
        Long brandId,
        Long partnerId
);

UPDATE

@Modifying
@Query("""
    UPDATE TestEntity t
       SET t.testName = :testName
     WHERE t.testId = :testId
       AND t.brandId = :brandId
       AND t.partnerId = :partnerId
""")
int updateTest(

        @Param("testId")
        Long testId,

        @Param("testName")
        String testName,

        @Param("brandId")
        Long brandId,

        @Param("partnerId")
        Long partnerId
);

DELETE

@Modifying
@Query("""
    DELETE FROM TestEntity t
     WHERE t.testId = :testId
       AND t.brandId = :brandId
       AND t.partnerId = :partnerId
""")
int deleteTest(

        @Param("testId")
        Long testId,

        @Param("brandId")
        Long brandId,

        @Param("partnerId")
        Long partnerId
);

Avoid Blindly Using

repository.findAll();

repository.findById(id);

repository.deleteById(id);

repository.existsById(id);

For tenant-owned entities, prefer tenant-aware equivalents.

11. Authentication and JWT

With one application instance per customer, tenant identity does not need to be supplied by the UI and does not need to be stored in JWT merely for tenant resolution.
UI | +-- username +-- password | v Authentication | v Existing UserDetailsService | v JWT | +-- username +-- roles | v Subsequent Requests Tenant Identity | v Application Configuration | v TenantProperties | v TenantContext

Your existing UserDetailsServiceImpl can therefore remain largely unchanged.

Recommended Tenant-Aware Credential Lookup

findByCredentialNameAndBrandIdAndPartnerId(

        username,

        TenantContext.getBrandId(),

        TenantContext.getPartnerId()

);

This prevents authentication queries from crossing customer boundaries.

12. Deployment Configuration

Local IntelliJ / STS

-Dspring.profiles.active=local
-Dfrt.tenant.brand-id=1
-Dfrt.tenant.partner-id=101

Customer A

FRT_BRAND_ID=1
FRT_PARTNER_ID=101

Customer B

FRT_BRAND_ID=1
FRT_PARTNER_ID=102

Production application.yml Option

frt:
  tenant:
    brand-id: ${FRT_BRAND_ID}
    partner-id: ${FRT_PARTNER_ID}
Item Customer A Customer B
Application JAR Same Same
Source Code Same Same
Brand ID 1 1
Partner ID 101 102

13. Complete Request Flow

1. User opens Customer A application | v 2. HTTP request reaches Spring Boot | v 3. TenantContextFilter executes | v 4. TenantProperties brandId = 1 partnerId = 101 | v 5. TenantContext initialized | v 6. Controller | v 7. Service | v 8. Repository | v 9. Query includes: brand_id = 1 partner_id = 101 | v 10. MySQL returns Customer A data | v 11. TenantContext.clear() | v 12. Response

14. Customer Isolation Example

Customer A

-Dfrt.tenant.brand-id=1
-Dfrt.tenant.partner-id=101
SELECT *
FROM test
WHERE brand_id = 1
  AND partner_id = 101;

Customer B

-Dfrt.tenant.brand-id=1
-Dfrt.tenant.partner-id=102
SELECT *
FROM test
WHERE brand_id = 1
  AND partner_id = 102;
Same JAR + same source code + different configuration = isolated customer data.

15. What Not to Do

Don't Reason
Send brandId from UI UI should not determine database tenant scope.
Send partnerId from UI Tenant is deployment configuration.
Put tenant IDs in every DTO Creates unnecessary API complexity.
Use findById() blindly Can bypass tenant filtering.
Use findAll() blindly Can retrieve another customer's records.
Forget TenantContext.clear() Can leak ThreadLocal state between reused threads.
Hardcode production tenant IDs in source Deployment-specific configuration should remain external.

16. Implementation Checklist

17. Final Architecture Summary

DEPLOYMENT | +-----------+-----------+ | | FRT_BRAND_ID FRT_PARTNER_ID | | +-----------+-----------+ | v TenantProperties | v TenantContextFilter | v TenantContext / \ brandId partnerId \ / \ / v v Services | v Repositories | v MySQL | brand_id + partner_id | v Customer-isolated data
Final Principle: Tenant identity is deployment configuration. Application code retrieves it from TenantContext. Tenant-owned database operations are scoped by both brand_id and partner_id.