Today we will look into Node JS Architecture and Single Threaded Event Loop model. In our previous posts, we have discussed about Node JS Basics, Node JS Components and Node JS installation.
Before starting some Node JS programming examples, it’s important to have an idea about Node JS architecture. We will discuss about “How Node JS works under-the-hood, what type of processing model it is following, How Node JS handles concurrent request with Single-Threaded model” etc. in this post.
As we have already discussed, Node JS applications uses “Single Threaded Event Loop Model” architecture to handle multiple concurrent clients. There are many web application technologies like JSP, Spring MVC, ASP.NET, HTML, Ajax, jQuery etc. But all these technologies follow “Multi-Threaded Request-Response” architecture to handle multiple concurrent clients. We are already familiar with “Multi-Threaded Request-Response” architecture because it’s used by most of the web application frameworks. But why Node JS Platform has chosen different architecture to develop web applications. What is the major differences between multithreaded and single threaded event loop architecture. Any web developer can learn Node JS and develop applications very easily. However without understanding Node JS Internals, we cannot design and develop Node JS Applications very well. So before starting developing Node JS Applications, first we will learn Node JS Platform internals.
Node JS Platform uses “Single Threaded Event Loop” architecture to handle multiple concurrent clients. Then how it really handles concurrent client requests without using multiple threads. What is Event Loop model? We will discuss these concepts one by one. Before discussing “Single Threaded Event Loop” architecture, first we will go through famous “Multi-Threaded Request-Response” architecture.
Any Web Application developed without Node JS, typically follows “Multi-Threaded Request-Response” model. Simply we can call this model as Request/Response Model. Client sends request to the server, then server do some processing based on clients request, prepare response and send it back to the client. This model uses HTTP protocol. As HTTP is a Stateless Protocol, this Request/Response model is also Stateless Model. So we can call this as Request/Response Stateless Model. However, this model uses Multiple Threads to handle concurrent client requests. Before discussing this model internals, first go through the diagram below. Request/Response Model Processing Steps:
Server waits in Infinite loop and performs all sub-steps as mentioned above for all n clients. That means this model creates one Thread per Client request. If more clients requests require Blocking IO Operations, then almost all threads are busy in preparing their responses. Then remaining clients Requests should wait for longer time. Diagram Description:
Here “n” number of Clients Send request to Web Server. Let us assume they are accessing our Web Application concurrently.
Let us assume, our Clients are Client-1, Client-2… and Client-n.
Web Server internally maintains a Limited Thread pool. Let us assume “m” number of Threads in Thread pool.
Web Server receives those requests one by one.
Web Server pickup Client-1 Request-1, Pickup one Thread T-1 from Thread pool and assign this request to Thread T-1
Web Server pickup another Client-2 Request-2, Pickup one Thread T-2 from Thread pool and assign this request to Thread T-2
Web Server pickup another Client-n Request-n, Pickup one Thread T-n from Thread pool and assign this request to Thread T-n
Once Threads are free in Thread Pool and available for next tasks, Server pickup those threads and assign them to remaining Client Requests.
Each Thread utilizes many resources like memory etc. So before going those Threads from busy state to waiting state, they should release all acquired resources.
Drawbacks of Request/Response Stateless Model:
Node JS Platform does not follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded with Event Loop Model. Node JS Processing model mainly based on Javascript Event based model with Javascript callback mechanism. You should have some good knowledge about how Javascript events and callback mechanism works. If you don’t know, Please go through those posts or tutorials first and get some idea before moving to the next step in this post. As Node JS follows this architecture, it can handle more and more concurrent client requests very easily. Before discussing this model internals, first go through the diagram below. I tried to design this diagram to explain each and every point of Node JS Internals. The main heart of Node JS Processing model is “Event Loop”. If we understand this, then it is very easy to understand the Node JS Internals. Single Threaded Event Loop Model Processing Steps:
Here Client Request is a call to one or more Java Script Functions. Java Script Functions may call other functions or may utilize its Callback functions nature. So Each Client Request looks like as shown below: For Example:
function1(function2,callback1);
function2(function3,callback2);
function3(input-params);
NOTE: -
As I’m a Java Developer, I will try to explain “How Event Loop works” in Java terminology. It is not in pure Java code, I guess everyone can understand this. If you face any issues in understanding this, please drop me a comment.
public class EventLoop {
while(true){
if(Event Queue receives a JavaScript Function Call){
ClientRequest request = EventQueue.getClientRequest();
If(request requires BlokingIO or takes more computation time)
Assign request to Thread T1
Else
Process and Prepare response
}
}
}
That’s all for Node JS Architecture and Node JS single threaded event loop.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Great article!! I am a full stack developer(fresher) and I did not know this node architecture before. I got rejected in an important interview because I didn’t know this. Now I understand everything. Thank you for your awesome job Pankaj :)
- Balavignesh
Nice article… It is clearly explained… Comparison with Muti-threaded model helped me to understand node.js very well… Thank your very much…
- Kittu
Great article, thanks!
- Johnny
Great article, thanks , for sharing your knowledge.
- Avishek Biswas
Thank you for this article and this explanation of how node works, but still i’m some how confused abut this, let’s say that our web server do this operation (none IO operation), for example (loop statement that needs 3 seconds to finish or complex validation on data(MVC model)) what will happened if i have let’s say 1000 concurrent requests? does the first request will block the remaining requests until it’s finished. and how node determain that this operation(none IO operation) is complex or not? thanks, and i hope if we can chat using Skype to discuss it.
- Abdallah Al-Barmawi
Good question. Did you find a response to this? If yes please share. Thanks,S
- Sushant
Hi, I will update this post soon by answering your questions.
- Rambabu Posa
Yes, the remaining requests will have to wait till the first request is finished. The way in which the calls are implemented is what decides if it is going to be executed on the main thread or not. You yourself can implement a module that maps internally to non-blocking OS calls and then listen for its completion. Then you would have to queue the corresponding callback in the queue for the event loop to handle.
- Jimmy George Thomas
Its an indeed a great article, But I would like to know - 1.the answer of above comment by Abdallah Al-Barmawi 2.Can you explain how does clusters work with respect to above explain single threaded model of nodejs. https://nodejs.org/api/cluster.html.
- Bron1010
Hi, I will update this post soon by answering your questions
- Rambabu Posa
Nice Article, thanks , for sharing your knowledge we us. i need more knowledge of how to build application using node js in PHP or any language … pls help
- vivek
Nice Article,but i need more knowledge of how to build application using node js in PHP or any language … pls help
- vivek
Good article. Thanks for sharing this. It will be nice if you add ode related to how threads (blocking IO) responds back to event queue in your pseudo code
- Raju
Very Helpfull :-).
- Vinod Kumar Marupu
I am still very confusing on NodeJs event loop as different articles seem to explain things differently. The confusion is when the thread that serves the request finishes processing the request, does it send the response back to the Event loop or to the Event queue instead? If we take a look at the JS event loop, it seems to indeed send the callback to the Task queue and Event loop then picks up the task (callback) from the Task queue.
- Tat Sean
Yes, you are correct. The thread queues the callback in the task queue from which the event loop picks it up and proceeds.
- Jimmy George Thomas
Very helpful article. But I have one doubt. Let suppose we have n concurrent requests coming to our web server. m out of n is non blocking so event loop will process them smoothly. But n-m requests are blocking. And as mentioned it will also maintain a thread pool. Let suppose thread pool contains T threads. Suppose T=n-m Now a new request is coming to web server and it is blocking request. So in this scenario how event loop will be non blocking? Wouldn’t new request have to wait till one of threads to be free? Is this rare case?
- Jai
Yes, the new request would have to wait till a thread becomes available.
- Jimmy George Thomas
Thanks a lot. The pictorial depiction does explain things clearly.
- Paddy
Thanks you very helpful
- HooRang
Thank you! I am very new to Node and did not understand the logic behind a single thread…thanks again!
- Crystal A.
thanks for all your node.js articles, really has helped me get started. one question i have is how does event loop find if the request is blocking or non-blocking, and send it to thread accordingly?
- rachna
Hi Rambabu, The post is very well explained. I have one question on the thread pool of the webserver itself not the NodeJS internal threadpool that kicks in when the type of the operation is blocking. “Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.” Can you please let me know where to change the thread pool setting of the webserver? What’s the default pool size? Because I think this is so crucial in handling multiple concurrent client requests and placing them on the Event Queue. I tried looking up I cannot find anything on the threadpool of the webserver and how to change and tune them? Please throw some light on this if you can.
- Rakesh
The article is very helpful and thank you for sharing this. I have a doubt, when multiple requests come which all need Blocking IO task the server uses multiple threads right? then how we can say Node is single threaded?
- Vineesh
if node js has internally m threads and if i get n blocking io requests what will happen when n>m?
- Jithendranath Gupta Y
I have the same question…
- abby
As far as event loop is concerned it is explained well… But … connection of thread performing blocking i/o to libuv calling the callback once event received is not explained which is the heart of node.js
- Lalit Kumar
yes
- ashutosh.ningot
I am still very confusing on NodeJs event loop as different articles seem to explain things differently. The confusion is when the thread that serves the request finishes processing the request, does it send the response back to the Event loop or to the Event queue instead? If we take a look at the JS event loop, it seems to indeed send the callback to the Task queue and Event loop then picks up the task (callback) from the Task queue.
- Tat Sean
Yes, you are correct. The thread queues the callback in the task queue from which the event loop picks it up and proceeds.
- Jimmy George Thomas
Very helpful article. But I have one doubt. Let suppose we have n concurrent requests coming to our web server. m out of n is non blocking so event loop will process them smoothly. But n-m requests are blocking. And as mentioned it will also maintain a thread pool. Let suppose thread pool contains T threads. Suppose T=n-m Now a new request is coming to web server and it is blocking request. So in this scenario how event loop will be non blocking? Wouldn’t new request have to wait till one of threads to be free? Is this rare case?
- Jai
Yes, the new request would have to wait till a thread becomes available.
- Jimmy George Thomas
Thanks a lot. The pictorial depiction does explain things clearly.
- Paddy
Thanks you very helpful
- HooRang
Thank you! I am very new to Node and did not understand the logic behind a single thread…thanks again!
- Crystal A.
thanks for all your node.js articles, really has helped me get started. one question i have is how does event loop find if the request is blocking or non-blocking, and send it to thread accordingly?
- rachna
Hi Rambabu, The post is very well explained. I have one question on the thread pool of the webserver itself not the NodeJS internal threadpool that kicks in when the type of the operation is blocking. “Node JS Web Server internally maintains a Limited Thread pool to provide services to the Client Requests.” Can you please let me know where to change the thread pool setting of the webserver? What’s the default pool size? Because I think this is so crucial in handling multiple concurrent client requests and placing them on the Event Queue. I tried looking up I cannot find anything on the threadpool of the webserver and how to change and tune them? Please throw some light on this if you can.
- Rakesh
The article is very helpful and thank you for sharing this. I have a doubt, when multiple requests come which all need Blocking IO task the server uses multiple threads right? then how we can say Node is single threaded?
- Vineesh
if node js has internally m threads and if i get n blocking io requests what will happen when n>m?
- Jithendranath Gupta Y
I have the same question…
- abby
As far as event loop is concerned it is explained well… But … connection of thread performing blocking i/o to libuv calling the callback once event received is not explained which is the heart of node.js
- Lalit Kumar
yes
- ashutosh.ningot