Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsafe tenant identifier for concurrent requests in jpa multitenancy example #686

Closed
TamimEhsan opened this issue Aug 10, 2024 · 1 comment
Assignees
Labels
type: documentation A documentation update

Comments

@TamimEhsan
Copy link

TamimEhsan commented Aug 10, 2024

The currentTenant value in the TenantIdentifierResolver.java file is not thread-safe, which can lead to issues in a multi-threaded environment where concurrent requests are handled.

Problem:
The currentTenant variable is shared across multiple threads, which can cause race conditions and inconsistent behavior when multiple requests are processed concurrently.

private String currentTenant = "unknown";
public void setCurrentTenant(String tenant) {
currentTenant = tenant;
}
@Override
public String resolveCurrentTenantIdentifier() {
return currentTenant;
}

Steps to Reproduce:
Deploy the application in a multi-threaded environment.
Send multiple concurrent requests that rely on the currentTenant value.

Expected Result:
Each request should have its own isolated currentTenant value.

Actual Result:
The currentTenant value is shared across threads, leading to potential data corruption and inconsistent behavior.

Suggested Fix:
Consider using a ThreadLocal variable to store the currentTenant value for each thread independently. This will ensure that each request has its own isolated currentTenant value.

Example:

private static final ThreadLocal<String> currentTenant = ThreadLocal.withInitial(() -> "public");

public void setCurrentTenant(String tenant) {
    currentTenant.set(tenant);
}

public String getCurrentTenant() {
    return currentTenant.get();
}
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged label Aug 10, 2024
@schauder
Copy link
Contributor

This is purely an example how to integrate Hibernate multi tenancy features with Spring Data JPA. I assumed it would be obvious that for a real application one needs do decide on the appropriate scope of the currentTenant. I'll add a comment to that effect to the readme.

@schauder schauder added type: documentation A documentation update and removed status: waiting-for-triage An issue we've not yet triaged labels Aug 12, 2024
@schauder schauder self-assigned this Aug 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: documentation A documentation update
Projects
None yet
Development

No branches or pull requests

3 participants