What is the difference in behavior between the 'primary' and 'worker' role in Node's cluster module regarding which code paths execute?
Short answer
A script using the cluster module is re-executed by every forked worker as well as the primary -- code branches on cluster.isPrimary (true only in the original process), typically containing only forking/management logic, while cluster.isWorker guards the actual application…
Advertisement
AModel answer
A script using the cluster module is re-executed by every forked worker as well as the primary -- code branches on cluster.isPrimary (true only in the original process), typically containing only forking/management logic, while cluster.isWorker guards the actual application logic, ensuring the primary never also runs a full server copy.
if (cluster.isPrimary) {
for (let i = 0; i < 4; i++) cluster.fork();
cluster.on('exit', () => cluster.fork());
} else {
require('./app').listen(3000);
}Real-world example
A misconfigured cluster setup that started the server inside both branches got an 'address already in use' error, resolved by keeping server-starting code only in the isWorker branch.
Likely follow-ups
- Why does having the primary only manage workers (rather than also serving requests) improve reliability?
- How many workers does the primary count as when calculating total request capacity?
Related topics