Skip to content

Instantly share code, notes, and snippets.

@mtorre4580
Last active April 9, 2023 16:48
Show Gist options
  • Save mtorre4580/a0092e26c5055ad4917e058aa85a616f to your computer and use it in GitHub Desktop.
Save mtorre4580/a0092e26c5055ad4917e058aa85a616f to your computer and use it in GitHub Desktop.
Example clustering mode in Node.js
const express = require("express");
const cluster = require("cluster");
const os = require("os");
const PORT = process.env.PORT || 3001;
// Replace with your logger
const logger = console;
// If the current is master, create the fork for all the cpus
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
cluster.on("exit", (worker) => {
logger.error(`Worker has exit ${worker.process.pid}, creating another...`);
cluster.fork();
});
} else {
const app = express();
// Endpoint for health check API
app.get("/health", (_, res) => {
res.status(200).json({ message: "ok", process: process.pid });
});
app.listen(PORT, () => {
logger.info(`API listen in ${PORT} - process ${process.pid}`);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment