Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Created July 11, 2024 02:47
Show Gist options
  • Save kevboutin/507c6fd8fa3fc2b7e96c9cdd6c1598ae to your computer and use it in GitHub Desktop.
Save kevboutin/507c6fd8fa3fc2b7e96c9cdd6c1598ae to your computer and use it in GitHub Desktop.
Cluster mode example
/* This code utilizes the “cluster” module to create multiple worker processes,
* each handling incoming requests. This approach allows you to scale your
* application horizontally to handle increased traffic. Note that they all use
* the same port.
*/
const cluster = require('cluster');
if (cluster.isMaster) {
// Master process forks worker processes
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
} else {
// Worker process handles incoming requests
const server = http.createServer((req, res) => {
// ...
});
server.listen(PORT, () => {
console.log(`Worker process listening on port ${PORT}`);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment