I have a multitenant Quarkus application. For each process, I need to store context information about the tenant that owns the process. This information is necessary for the HibernateTenantResolver and other multitenant-specific implementations to determine the appropriate context for handling the data.
Currently, I am using a @RequestScoped bean to store the tenant information. Whenever I run an asynchronous operation, I ensure that I create a new request scope on the async thread and copy the tenant information.
I initially chose the request scope because all @RequestScoped beans are destroyed after the scope ends. This approach eliminates the need to worry about thread reuse and accidentally writing into another tenant's database.
However, implementing this approach requires some tinkering (e.g. a UniInterceptor), and I have some doubts.
An alternative idea is to directly use a ThreadLocal reference instead of a @RequestScoped bean to store the tenant information. I am aware that Smallrye supports thread-local context propagation, which could eliminate the need for tinkering with request scopes.
Nevertheless, I have concerns about setting a ThreadLocal reference on a thread that might get reused, potentially leading to accessing the wrong tenant's database.
Are these doubts reasonable? Which approach is better? Should I stick with my @RequestScoped approach, or can I reliably solve this using ThreadLocal?
Using
@RequestScopewith Context Propagation is the way to go. Dealing withThreadLocalmanually is going to be very error prone.