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?
–
–
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.
–
–
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
.