Video in progress

Senior 🌱 Spring

In an application where each customer (tenant) has its own database, how do you pick the DataSource in Spring?

With AbstractRoutingDataSource: each time a connection is requested, it reads the current tenant key from a ThreadLocal and returns the matching DataSource. The key point is to set the tenant context at the start of the request, before the transaction, and clear it at the end.

📖 Answer

public class TenantRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.get(); // ThreadLocal<String>
    }
}

@Bean
DataSource dataSource(Map<String, DataSource> tenantDataSources) {
    var r = new TenantRoutingDataSource();
    r.setTargetDataSources(new HashMap<>(tenantDataSources));
    r.setLenientFallback(false); // an unknown tenant is an error, it must not fall through to another database
    r.afterPropertiesSet();
    return r;
}

A filter takes the tenant from the JWT or subdomain at the start of the request and clears it in a finally block.

The traps:

  • Timing. The connection is acquired when the transaction starts, and changing the tenant after that has no effect. If you work with two tenants in one request, use separate transactions.
  • ThreadLocal doesn't propagate to @Async and schedulers. Background jobs have to iterate over the tenants themselves.
  • Number of pools: 500 tenants × 10 connections = 5000. Make the pools small, create them lazily and close them for rarely active tenants, or move to schema-per-tenant / a shared schema.
  • Flyway is applied to each tenant database separately; think ahead about what to do if one of them fails.
  • The biggest risk is one tenant's data becoming visible to another. Have no default tenant, and have tests check that two tenants' data never mix.