Describe a scenario where a Spring Boot application needs to dynamically switch between multiple data sources at runtime based on the request context.

Dynamic multi-tenant data source routing lets a Spring Boot application switch between multiple databases at runtime based on request context, commonly implemented with Spring's AbstractRoutingDataSource.

Key Points: • AbstractRoutingDataSource selects the actual DataSource to use per request based on a lookup key. • A ThreadLocal or request-scoped holder stores the current tenant or region identifier, set early in a filter or interceptor. • determineCurrentLookupKey() in the routing data source reads that holder to pick the correct underlying database. • Each target DataSource, such as one per region, is registered in a map passed to setTargetDataSources(). • The ThreadLocal must be cleared after the request completes to avoid leaking context between requests on pooled threads.

Example: A request from a user in Europe sets a "region=EU" context value in a filter; the routing data source reads that value and directs all JPA queries for that request to the EU database instance, while an Asia-based request is routed to a separate database automatically.

Code Example:

public class TenantRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getCurrentTenant();
    }
}

Interview Tip: A concise interview answer is:

"I'd implement this with AbstractRoutingDataSource, which picks the actual database per request based on a lookup key. A filter sets the tenant or region into a ThreadLocal early in the request, determineCurrentLookupKey reads it to route to the right DataSource, and I make sure to clear the ThreadLocal afterward."