
Implementation of Multi-Tenant Architecture using NodeJS & MongoDB
Introduction:
Multitenancy is a reference to the mode of operation of software where multiple independent instances of one or multiple applications operate in a shared environment. The instances (tenants) are logically isolated, but physically integrated.
The term “software multi-tenancy” refers to a software architecture in which a single instance of software runs on a server and serves multiple tenants.
Architecting a multi-tenant system is more complicated than architecting a multi-user system. There are two models of architecting a multi-tenant system:
- Instance Replication.

- Data Segregation.

In the data segregation model, the application is shared between tenants but the data of each tenant is stored in separate data stores. Separate data stores could be separate databases or separate schema within the same database.
Data Segregation is of two types
- One DB with different schemas for a different tenant.
- One DB per tenant.
separate schema i.e. different tables within one DB for each tenant.

In this article, we will discuss multitenancy with Data Segregation Model with a single DB per tenant.
Implementation:
The implementation of multitenant architecture with a data segregation model (single DB per tenant) is distributed into 4 main components
- Model Management
- JWT Verification
- Middleware & Connection Management
- Multitenant Manager
Model Management
JWT Verification
Middleware & Connection Management
Multitenant Manager
Summary:
This Architecture will help you to serve multiple clients with a single code base application, due to data integrity and data segregation this could be the best approach to separate the database concerning clients with a share application.
Problem
Implementation of multitenant architecture with a data segregation model can face high memory usage issues if the number of tenants will increase as the application will always have lots of open connections that will degrade performance, but it can be used in case you have fewer tenants and which will never grow dynamically.
Solution
Implementation of Redis Server for in-memory management can be the solution for the multitenant architecture with a data segregation model for high memory usage problems, but if we host our application in cloud infrastructure like; Azure(app Services), AWS(elastic beanstalk), GCP(app engine), then we will not face any problem like that due to it will manage by itself.
Reference
1. https://medium.com/@adeelsarwarblog/single-tenant-and-multi-tenant-architecture-7b204557ae8c
2. https://adhasmana.medium.com/how-we-implemented-multi-tenancy-in-our-node-js-app-cf9a2515969b
3. https://www.slideshare.net/EoinShanaghy/building-a-multitenanted-saas-with-nodejs
4. https://github.com/Aarul5/nodejs-mulitenant-mongodb
5. https://gist.github.com/alancasagrande/23e6284e24dadafce8c0