javascriptnode.jssingle-threadedsinglethreadmodel

Node JS multiple concurrent requests to backend API


This is my node js backend API method.

apiRouter.route('/makeComment')
        .post((req, res) => {

            consoleLogger.info("Inside makeComment API..");
            logger.info("Inside makeComment");

            let timestamp = new Date().getTime();

            let latestCommentID = timestamp.toString();

            console.log("comment ID generated is "+latestCommentID);


            res.json({
                                'makeComment': 'success',
                                'commentid':latestCommentID
                 });

        });

Now, if multiple concurrent requests come to this API, what will happen?

As per my understanding, NodeJS will maintain a Event Queue for the requests and process requests one by one.

So, it is impossible to get the same timestamp for two different requests.

Please let me know if my understanding is correct?


Edit 1:

After googling for some time, got this link, which clearly explains some of the concepts.


Solution

  • There is no possibility of concurrency here. As you have correctly studied, Node.js runs in a single-threaded environment (unless you use clusters, the worker API, or other related Node.js modules that facilitate IPC). As such, the line

    let timestamp = new Date().getTime();
    

    cannot be concurrently invoked by two simultaneously running threads, excluding the exceptions noted above.

    However, Date.prototype.getTime() only has millisecond resolution, so it's remotely possible that the callback to apiRouter.route('/makeComment').post() might be sequentially invoked by the event loop from two pending asynchronous requests within the same millisecond.