WittCode💻

Is Node Bad at Heavy Computations?

By

Learn if Node is the right choice for running heavy computations. We will learn about Node's architecture, child processes, worker threads, and C++ addons.

Table of Contents 📖

Node and Heavy Computation

Node is not ideal for CPU-heavy operations because it is single-threaded. This means that computationally intensive tasks can block the main thread (event loop). If the event loop is blocked, the application will not be able to handle other requests. Consider the following Express app. Making a GET request to /quadratic will stop any other request from being handled while it is calculating the result.

app.get('/quadratic', (req, res) => {
  console.log('o(n^2)');
  const n = req.query.n as number;
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      console.log(i, j);
    }
  }
  return res.send('o(n^2)');
});

Handling Heavy Computations with Node

However, Node does provide a few ways to handle heavy computations while avoiding blocking the main thread. One way is to fork processes. Forking in Node creates child processes to run tasks parallelly. By forking processes, you can offload work to separate processes, ensuring the main application remains responsive to other requests. This can be done with the native child_process module.

import {fork} from 'child_process';

app.get('/quadratic', (req, res) => {
  console.log('o(n^2)');
  fork('/Users/wittcode/Desktop/my-app/src/heavyComp.js');
  return res.send('o(n^2)');
});
console.log('Calculating heavy computation...');
for (let i = 0; i < 1000; i++) {
  for (let j = 0; j < 1000; j++) {
    // hi
    console.log('Calculating');
  }
}
console.log('Done with heavy computation');

ERROR: This is purely an example. You should not create a child process to handle each HTTP request as the overload would be huge and could easily be DDOS attacked using a fork bomb.

Each child process is completely independent of the main process and has its own event loop, memory, and V8 engine instance. Node also provides the worker_threads module to enable multi-threaded computation. Worker threads are lighter than child processes and share memory. Node even allows us to write C++ add-ons to handle computationally heavy tasks.

Is Node Bad at Heavy Computations?