[Node.js] MultiThreading & Worker Threads

1) NodeJS is single threaded, right?

Prior to the introduction of worker threads (in ver.10.5.0), the answer is - Kind of. NodeJS run things in parallel, but programmatically,  the developer doesn't implement threads. Threads are automatically managed by libuv when we execute asynchronous operations, eg. I/O operations. Together with the use of callback functions, NodeJS achieves concurrency.

2) So what is the problem? CPU-intensive tasks

The single-threaded model is great if all we do is asynchronous operations. Without worker thread support, any high CPU-intensive tasks will block the single-threaded event loop, because it is single-threaded - meaning it will wait for 1 task to complete before executing the next one. This scenario makes NodeJS not concurrent.

3) Multi-Processing

Actually, it is technically possible to do multi-threading without worker threads. We can spawn child processes by forking to achieve multi-threading (arguably). But processes are expensive and don't share memory - this is not a good solution.

4) Worker Threads

It is like threads without shared memory and thus eliminating the problem of race conditions. It is recommended to create a pool of workers to limit resource usage. Other important details are:
  1. As of 12.2.0, Worker threads are still experimental API - meaning it is subjected to changes. 
  2. You need to use the experimental-worker flag ("node --experimental-worker index.js")
  3. Worker threads communicate with parent thread via event-driven listeners and callbacks.

5) When to use Worker Threads?

High CPU-intensive tasks only! - such as crypto, compressing/decompressing, image manipulation, computer vision (eg. face recognition), etc.

It is highly recommended not to use Worker Threads for I/O-intensive tasks because NodeJS' built-in asynchronous I/O operations re more efficient than workers can be.

6) Are Web Workers the same thing?

No. They are a more mature API for the web, and well supported by modern browsers. They do solve similar problems in the browser runtime.

Resource

https://blog.logrocket.com/node-js-multithreading-what-are-worker-threads-and-why-do-they-matter-48ab102f8b10
https://medium.com/tech-tajawal/threading-in-nodejs-5d966a3b9858
https://medium.com/lazy-engineering/node-worker-threads-b57a32d84845

Comments

Post a Comment

Popular posts from this blog

[Redis] Redis Cluster vs Redis Sentinel

[Unit Testing] Test Doubles (Stubs, Mocks....etc)

[Node.js] Pending HTTP requests lead to unresponsive nodeJS