How would a Spring Boot application switch between multiple data sources at runtime based on the request?

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

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.

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.

Last updated: 11 November 2026

Previous question: What strategies would you use to optimize the performance of a Spring Boot application?

Next question: How would you add a GraphQL API to an existing Spring Boot REST service?

More Spring Boot - Level III (Scenario Based) interview questions

All Spring Boot - Level III (Scenario Based) questions