What is the recommended way to implement "database per tenant" for a multitenant application? #13265
-
For a "Database per tenant" multitenancy approach. I could find two solutions:
Which one of these approaches is the recommended approach? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I doubt somehow that you have a mongoserver per database. The Mongo Driver itself already uses a connection pool. You probably hit then the maximum amount of connections when using multiple connection pools. So if you want to use multiple databases, then you probably should use useDB and switch the database every time. On the other hand, it makes maybe more sense to not separate the data on database level but on collection level. So every tenant has its own specific collections. Also it makes maybe more sense to already think about sharding. E.g. shard by tenant id. If you separate the tenant data by database or collection, than maybe then you probably already have no way to use sharding in a purposeful manner. |
Beta Was this translation helpful? Give feedback.
@sadeghhosseini depends on your use case. If you have a relatively small number of tenants (say less than 100) and you're not worried about contention between the tenants, then
useDb()
is fine.useDb()
is easier to implement and work with, and ends up opening fewer connections to MongoDB.But
useDb()
means one slow tenant can slow down the other tenants due to slow trains. That's why, for large multi-tenant setups or setups that are performance sensitive, we recommend a separate connection per tenant.