Open In App

How the single threaded non blocking IO model works in NodeJS ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Node.js is a JavaScript runtime environment that runs on the Chrome V8 engine and is used for server-side scripting. It takes requests from users, processes those requests, and returns responses to the corresponding users.

Some important Node.js features are:

  • It is based on single-threaded architecture: Since node.js gets multiple requests from multiple users it executes one command at a time. Due to this it can handle concurrent client requests very effectively and has good performance.
  • It uses an event-driven non-blocking-based IO model: Whenever the node server is started, it initiates certain variables and functions and then waits for events to occur, whenever an event is detected a callback function is assigned to that particular event. Event-driven architecture makes the server highly scalable and it does not wait for an API to return data, it moves to the next API immediately for the next request. Non-blocking operation means the server will not block itself for one request. Non-blocking call only initiates the operation and the response is provided later, meanwhile, it can continue with other client requests.

Example: If we get requests from two users A and B. With non-blocking IO we can initiate the request for A and then immediately for B without waiting for the response to the request of A. Hence we can say with the help of non-blocking IO we can eliminate the use of multi-threading since the node server can handle multiple requests simultaneously.

Working of single-threaded non-blocking IO:

  • When the client sends a request to the server, this request is called an event. These all requests get stored in an event queue. The single thread present in the event loop assigns this request to one of the threads present in the internal thread pool.
  • This thread reads the client request, processes the request, performs any blocking IO operations if needed, and prepares the final response to be sent back to the server. The event loop sends this response back to the respective client.
  • The event loop infinitely receives requests and processes them.
  • There is no need for multiple threads because of Event Loop. Because of this event loop and concept of single threading, node.js uses lesser resources and memory.

Reference: https://www.geeksforgeeks.org/introduction-to-nodejs/


Last Updated : 05 Feb, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads