Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created November 4, 2024 20:35
Show Gist options
  • Save ali-master/f66bda352832aba2201c63f41b35e0bf to your computer and use it in GitHub Desktop.
Save ali-master/f66bda352832aba2201c63f41b35e0bf to your computer and use it in GitHub Desktop.
NestJS clustering via NodeJS workers
import cluster from "node:cluster";
import { Injectable } from "@nestjs/common";
import { cpuCountSync } from "node-cpu-count";
const numCPUs = cpuCountSync();
@Injectable()
export class AppClusterService {
static register(callback: () => void): void {
if (cluster.isPrimary) {
console.log(`Master server started on ${process.pid}`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on("exit", (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died. Restarting`);
console.log({
code,
signal,
});
cluster.fork();
});
} else {
console.log(`Cluster server started on ${process.pid}`);
callback();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment