Video in progress
In a multi-tenant system, if you choose a separate database per tenant with `AbstractRoutingDataSource`, what risks do you run into?
The tenant is usually kept in a ThreadLocal, and it can be lost in async calls or leak into the wrong tenant. On top of that, the connection is chosen once at the start of a transaction, and each tenant's own pool multiplies the total number of connections.
📖 Answer
The mechanism: AbstractRoutingDataSource is a proxy/strategy. On every getConnection() call, it picks the real DataSource based on determineCurrentLookupKey().
public class TenantRoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TenantContext.current(); // ThreadLocal or ScopedValue
}
}
Problems that show up on prod:
Context leaks. A filter calls TenantContext.set(...) but doesn't clear it in finally. The Tomcat thread starts the next request with the old tenant, and you get another customer's data. This is the most dangerous bug. In @Async, CompletableFuture and Kafka listeners the context isn't propagated at all; you need a TaskDecorator or a context-propagation library.
Timing of the choice. The connection is taken when the @Transactional method starts and stays the same until the transaction ends. Changing the tenant inside the method does nothing: the data is written to the other tenant's database.
Number of connections. 200 tenants × a pool of 10 connections × 6 pods = 12,000 connections. PostgreSQL can't take that. Options: small pools and PgBouncer, or grouping tenants into shards (several tenants in one database, by schema or tenant_id).
Caches. If the Hibernate second-level cache and the Spring cache keys don't include the tenant, data gets mixed between tenants.
Migrations. Running Flyway against 200 databases, and deciding what to do when it fails on one of them, needs a separate process.
How I choose: if the isolation requirement is strict (banking, healthcare, by contract), a separate database, but only when there are tens of tenants. With hundreds or thousands of tenants, a shared table with a tenant_id column and PostgreSQL row level security, and at the code level Hibernate 6's @TenantId filter. In both cases an automated test that checks for tenant mixing (create two tenants and verify that one's data isn't visible to the other) is mandatory.
Sign up to mark studied questions and save your progress.