I have a NestJS application. I’m used to deploy my NodeJS application using PM2 in cluster mode (more than one instance running).
The thing is that NestJS uses Singleton pattern for it’s services. I’m relying on this feature for some of my features (using a service property that can be accessed globally and holding its value).
Am I going to have issues using the PM2 cluster mode? Does NestJS can share this Singleton through the instances?
Obs: I don’t want to add complexity for the project. Installing a Redis for holding the global data, for example.
2
Answers
Yes, you may face issues using PM2 cluster mode with NestJS if you will rely on the Singleton pattern for the global state. In cluster mode, each instance of your application runs in its own process. Singletons in NestJS are scoped to each application instance, so they won’t share state across different instances in a PM2 cluster. Each instance will have its independent version of any Singleton service, meaning that any global state held in these services will not be synchronized across your clustered instances.
To handle global state across clustered instances without adding external dependencies like Redis, consider using a shared database or file system for state persistence. By storing and retrieving the shared state from a common database or a file that all instances can access, you can ensure consistency across different instances in a PM2 cluster. However, this approach might introduce complexities related to data synchronization and performance
In a clustered environment with PM2, each cluster instance runs as a separate process, and they don’t share memory directly.
Because NestJS services are singletons within a single process, sharing data between instances isn’t straightforward.
If you rely on a singleton service within a single NestJS instance, you might face issues when using PM2 cluster mode because each instance operates independently, and changes in one instance won’t be reflected in others.
To address this without adding external complexity, you might consider using in-memory caching within your NestJS application. For example, you could use a caching library like
memory-cache
or the built-inCacheModule
provided by NestJS.This allows you to share some data between requests within the same instance.
Let me know if that helps, Will try to update with some code as well.