Node.js Non-Blocking Nature

I am new to node.js and still trying to understand the philosophy behind it. As I found out, node.js works in one process only as opposed to php, which opens the process \ thread for each request. And although you can say that Node is β€œnon-blocking” for i / o, it blocks requests (requests accumulate because there is no new thread for every new request) and theoretically, if you wrote node.js, which does not work quickly with every request in which you find yourself.

My question is this: how can I determine if some request processing is too long to block all other requests for too long and interfere with the performance of my application?

I know that all the "heavy" actions on the server (db request, file system search) are performed by callbacks and therefore cannot block the node. However, what if all other operations that are performed synchronously by the server to process the request are too long?

For example, the server should write a lot of html for the response. What happens then?

How does a Node programmer know if he does too much with a certain request (in a blocking way), is it experience, intuition, or are there clear guidelines on how to do this?

+4
source share
1 answer

There is no clear indication as to where the limit between synchronous code and asynchronous code is, it depends more on the application flow. Asynchronous operations should be preferred as they allow Node.js to the main process to start processing other requests during this time.

However, simply using callbacks for each function is not a solution, as part of the code as such:

function sum(a, b, callback){ var sum = a + b; callback(sum); } sum(2,3, function(sum){ console.log(sum); } 

Still in sync. To make it asynchronous to process.nextTick , you can use as such:

 function sum(a, b, callback){ var sum = a + b; process.nextTick(function(){ callback(sum); }); } sum(2,3, function(sum){ console.log(sum); } 

The general rule is to avoid synchronous recursive computations, heavy loops, and I / O.

Searching if a request takes too much time and thus will hinder performance cannot be determined so that, as a rule, restrictions are application specific. These queries are located by running performance tests in the application.

+5
source

Source: https://habr.com/ru/post/1437361/


All Articles