How multiple requests are handled by node.js

As we all know, In node.js we run JavaScript and JavaScript language don't have a concept of multiple threads then how do we achieve that? I am going to tell you how node.js(single threaded) handles multiple requests.

When a client sends a request to the node server, the server further sends that request to other server and waits for the response and in the meantime, if there comes another request then the client have to wait for some time(seconds). Node.js is a single threaded application that is it can only accept requests. Node.js can handle multiple requests but it will not wait for other server to respond. Therefore single thread will not be blocked for single client.

How it will do it?

Node.js uses two concepts

  • Non-blocking I/O
  • Asynchronous

Non-Blocking I/O

node-server (2).jpg

Whenever a client sends a request the single thread will send that request to someone else(i.e. to workers). The current thread will not be busy working with that request. There are workers working for the server. The server sends the request to the worker, the worker further sends it to the other server and waits for the response. In the meantime if there is another request the thread will send it to another worker and the worker will wait for the response from the another server.

In this way the single thread will always be available to take the requests from the client. It will not block the requests.

Asynchronous

What if client one sends request to the server and it further sends to the worker and then this single thread is accessing client two. What if the response of client one comes from other server? How it will execute the remaining statements?

The solution for the above question is using Asynchronous method. The moment you get response from the other server/database the node server will execute a callback() function which is basically an event loop.

If node.js doesn't support multiple threads then how we are able to get this workers? What are they?

To implement this node uses a concept of libuv. It is a cross-platform support library built for node, it provides concept of non-blocking I/O.

libuv (2).jpg

libuv is built in C language which uses system kernal and kernal has multiple threads.

So in node.js you are not using multiple threads but behind the scene your kernal is implementing multiple threads.

So when you send request to the server,node.js will be single threaded but behind the scene they are using multiple threads and that's what makes node.js fast and flexible.