A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, the user will sometimes want to launch a cluster of Node.js processes to handle the load.
The cluster module allows easy creation of child processes that all share server ports.
Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with and fully supports TypeScript (yet still enables developers to code in pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).
Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!
Nest provides a level of abstraction above these common Node.js frameworks (Express/Fastify), but also exposes their APIs directly to the developer. This gives developers the freedom to use the myriad of third-party modules which are available for the underlying platform.
// cluster.ts
import * as cluster from 'cluster';
import * as os from 'os';
export class Cluster {
static register(workers: Number, callback: Function): void {
if (cluster.isMaster) {
console.log(`Master server started on ${process.pid}`);
//ensure workers exit cleanly
process.on('SIGINT', function () {
console.log('Cluster shutting down...');
for (var id in cluster.workers) {
cluster.workers[id].kill();
}
// exit the master process
process.exit(0);
});
var cpus = os.cpus().length;
if (workers > cpus)
workers = cpus;
for (let i = 0; i < workers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker %s is online', worker.process.pid);
});
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Restarting`);
cluster.fork();
})
} else {
callback();
}
}
}
Now call it
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Cluster } from './cluster';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
// use 4 workers
Cluster.register(4, bootstrap);
Happy coding!
#nestjs #node #typescript