Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have simple api, to which a user can send some data. The data is JSON array of objects. My goal is to know, how many objects are currently being processed by the api. I created a global counter, and for each request I receive I add the number of objects to that counter, and when I'm done with processing the object I deduct the number from the counter. My question, is this approach thread-safe? Meaning, can I have two requests - one which just finished being processed so a deduction happens, and another new request where I add the number of requests to the counter, sort of race condition?

Node.js is single threaded (even with web workers, each interpreter is single threaded) so there is no need to worry about thread safety slebetman Jan 31, 2019 at 12:53 Just to clarify, if I have two incoming requests, they enter the code one after another. they couldn't touch the same global element simultaneously? Keselme Jan 31, 2019 at 12:59

Even during concurrent requests, the counter will count requests as expected because Node JS is single threaded and Event Loop will care about it. However, if you have multiple servers, the method will not work because global variables are stored in each server's RAM. In that case, you should have some union database like Redis (It is a key-value database and it stores data in RAM so it is very fast) to store your counter.

I use AWS load balancer, which in turn directs the request to one of two servers, and each server performs fork() when it starts running (fork create 4 process). I guess that each of the process will have it's own counter, for the number of request that are being handled, am I right? Keselme Feb 3, 2019 at 9:20 No, you have more than 1 server, each your server will have its own counter. The great thing about NodeJS that you can have global variables but they are stored in RAM and when your NodeJS application is terminated you will lose that data, In order to avoid this, you can use Redis. It is also stored in RAM however it syncs all data on hard drive. In your case you should use Redis Database for counting, both servers should increment data in Redis. In Addition, I would like to mention that all queries inside Redis DB are atomic Gor Kotikyan Feb 4, 2019 at 3:00

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .