Solutons Lounge

node.js – How to deal with objects creation per request with high RPM node applications


I’m trying to refactor an app to use Entity classes which are supposed to encapsulate business logic and make operations related to their domain.

For example, I have an AccountEntity which takes care of all account related logic and actions, and to create it I need to pass an accountId and other dependencies such as services, functions, and data. But many of these dependencies are created on each request, such as the accountId, feature flag functions and a ton of processed data.

Now the problem is that if I create these entities in each request I run into much higher CPU and memory utilization due to the high RPM (10k+) in the app and the garbage collector not being able to keep up with so many requests.

I tried solving the problem making the entities singletons (like we already do with services), but since entities have request dependencies (services are anaemic and only have a few instances for different tenants) I run into problems with concurrency where one request could use the instance with a set of dependencies which can be reassigned by another concurrent request during async operations.

So from what I see I’m left with only two options, pass dependencies by parameter in every method, which looks bad for me because I believe an AccountEntity should at least already have access to its own DTO, and the other option is to ignore the higher cost and create objects in every request, which is a more obvious bad idea in our case.

Another option would be to completely get rid of classes/objects and use only functions but then it’s again pretty much the same as passing the dependencies to each method in a singleton class.

I’m completely lost now on how to do this in a way that is both pleasing to the eyes and will not bring performance/cost issues. I feel like these are the only options I have, but I hope I’m wrong and some of you can share a better solution.

Thanks!



Source link

Exit mobile version