Best practice for singleton vs multiple MongoClients when you need to authenticate with different users

Hi, John,

Thank you for requesting clarification on our recommendations.

When architecting a multi-tenant application, you have two main choices for implementing security:

  1. Authenticate/authorize as a single application user and implement tenant authentication/authorization within the application level. This is often done by augmenting operations with a tenantId at the database, collection, or document level depending on your design.
  2. Authenticate/authorize each tenant as a unique database user and delegate access control to the database.

Each technique has its own advantages and disadvantages, which you’ve likely already considered. We generally recommend the first approach using a single application user as it allows drivers to effectively use connection pooling when connecting to the cluster.

If you want to use the second approach, then you have to use a MongoClient per unique tenant. If you have a large number of tenants, you should consider managing an LRU list of MongoClient instances and disposing of old clients (including their clusters and associated connection pools).

As Boris noted, ClusterRegistry.UnregisterAndDisposeCluster(client.Cluster) was not designed for this purpose and may have unintended bugs when the AppDomain is up for days, weeks, or months. This functionality is used by our test runner where the lifetime of an AppDomain is around 30-60 minutes - long enough to run our test suite against a given configuration. We are considering this scenario of a reliably disposable MongoClient (CSHARP-3431) for a future release.

Also worth noting is that connection pooling and monitoring is implemented per server and per cluster key. Changing credentials will change the cluster key and thus result in a different set of connection pools and monitoring connections. You will want to ensure that maxPoolSize is configured appropriately if you have a large number of tenants. You may want to consider modifying other connection pool options as well to account for the potentially large number of connection pools and monitoring connections.

Please let us know if you have any additional questions.

Sincerely,
James

1 Like