I'm running a multi tenancy application that uses one database per tenant. My application currently serves around 2k tenants. I create one MongoClient (using Spring's MongoTemplate) per tenant and cache all MongoClients in a local HashMap.
This has some serious drawbacks as the number of threads and connections rises with every new tenant.
I stumpled upon some great slides that explain a clever approach when developing a multi tenancy application that uses MongoDB:
The author uses one Mongo instance (singleton) that acts as a connection pool for instances of MongoTemplate that are created on the fly. This is possible because MongoDB completely separates the actions of connect and authenticate. The number of threads and connection is reduced to a minimum.
Unfortunately this feature of "lazy authentication" was dropped with version 3.0 and above. An instance of MongoClient (which is the successor of the deprecated Mongo) needs the credentials for connecting to database at construction time and cannot be changed afterwards.
I'm currently running into trouble as the "instantiate one MongoClient per tenant" doesn't scale well and I'm forced to add more machines to reduce the number of threads per jvm.
Is there a better solution than "instantiate one MongoClient per tenant"? Is there an easy way to extend the Driver to support "lazy authentication" again?