Created
November 4, 2024 20:35
-
-
Save ali-master/f66bda352832aba2201c63f41b35e0bf to your computer and use it in GitHub Desktop.
NestJS clustering via NodeJS workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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