Oh God! Are you guys still using C? 🙈
and although you may have heard that Node.js is single threaded and you can’t get performance like Django or Golang with it – we’re going to look at how you can improve the performance significantly.
Under the hood, Node uses libUV to abstract non-blocking I/O operations. LibUV is based on C and is used to provide a Pool Of Thread!
So, the secret about Node.js is that, even though it is single-threaded by default, you can achieve multi-threading and parallel programming with a few simple steps. 🥳
By default LibUV provides 4 worker threads and it can be increased to match the number of CPU cores on your machine. For example, suppose you have an 8 core CPU with each core capable of running 2 threads, this gives you 8 * 2 = 16 threads
By the way, you don’t need to do the calculation. ✌🏻 Node will do it for you with a simple line of code.
2 . Cluster
One of the parts I love the most in Node is Cluster. So what does Cluster really do?
It allows you to create a copy of your server with the number of worker threads left after pooling in LibUV and a server with an internal load balance on your chosen port.
3. Child Process
Child process is similar to libUV – but there are some important distinctions. While libUV can assign a worker thread by itself, a child process is implemented by the developer. Child processes have a different method to do a certain task it is most useful in time-consuming tasks.
Let’s take an example. Suppose that your order API takes 2 minutes to complete to perform because of some calculation and in that meantime the server receives another request, it would be on hold until the order API finishes. In that case, child processes come into the picture to bypass this issue.
Child processes are of different types like exec, spawn, fork. You can find a complete reference for the different kind of child processes here. Reference for the child process
The last point is that Node.js is synchronous non-blocking I/O driven it is not designed to perform CPU-intensive tasks.
Awsome✌🏻 Finally we are done here with performance optimization.
Let’s Summarize all topics discussed-
1. LibUV – We can change the Pool of Threads according to our requirement but we don’t have much control over their system will handle execution of thread.
2. Cluster – Which also uses Threads to Create a Replica Set of Server internally using Threads.
3. Child Process – It is used to process Time-consuming tasks with an assigned thread so that It won’t block the server for others as well.
Congratulation 🎉 Now you Know how to do Optimization in Node Js