Node js - Internals

Node js: Single-threaded, Non-blocking IO, And Event Driven ♻️

  • Node js uses only one thread to do the tasks. It makes use of asynchronous programming to handle concurrency.

  • Non-blocking: refers to the program that does not block the execution of further operations. Non-Blocking methods are executed asynchronously.

  • Event-driven: 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.

  • 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 ♻️⚡:

  • When the client sends a request to the server, this request is called an event. All these requests get stored in an event queue. The single thread in the event loop assigns this request to one of the threads in the internal thread pool.

  • A thread from the internal thread pool 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 event loop. The event loop sends this response back to the respective client.

  • The Internal thread pool has access to a library called libuv, which is written in C language. So with its help, the internal threads are able to perform all the blocking operations like making DB requests, etc.

  • Internal thread pool size = size of CPU core

  • 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.


The End!

Linkedin github 🚀☁️🖤