Last active
April 9, 2023 16:48
-
-
Save mtorre4580/a0092e26c5055ad4917e058aa85a616f to your computer and use it in GitHub Desktop.
Example clustering mode in Node.js
This file contains 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
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