DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Establishing a Highly Available Kubernetes Cluster on AWS With Kops
  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • OpenShift Container Platform 4.11 Cluster Setup
  • A Beginner's Guide to Back-End Development

Trending

  • Introduction to Retrieval Augmented Generation (RAG)
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Security by Design: Building Full-Stack Applications With DevSecOps
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Multicore Programming in Node.js

Multicore Programming in Node.js

An explanation of how to use Node.js to take advantage of multicore CPUs with the Cluster API.

By 
Dursun Koç user avatar
Dursun Koç
DZone Core CORE ·
Nov. 09, 15 · Opinion
Likes (21)
Comment
Save
Tweet
Share
47.0K Views

Join the DZone community and get the full member experience.

Join For Free

Node.js is a single-threaded platform; if you want to take advantage of multicore CPUs, you need to fork multiple processes. This is called “clustering,” and is supported by the Node.js Cluster API. In this article you will see how the cluster module works.

The cluster module helps you to spawn new processes on the operating system. Each process works independently, so you cannot use shared state between child processes.

Each process communicates with the main process by IPC and pass server handles back and forth.

Cluster supports two types of load distribution:

  • The main process listens on a port, accepts new connection and assigns it to a child process in a round robin fashion.
  • The main process assigns the port to a child process and child process itself listen the port.

How Do You Use It?

We begin with creating the node project folder; and initialize it using npm.

$ mkdir clstr && cd clstr && npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (clstr)
version: (1.0.0)
description:
entry point: (index.js) app.js
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to d:\DEV\workspaces\learn\dzone\clstr\package.json:

{
"name": "clstr",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}


Is this ok? (yes)

Next step is to add the express framework to our project.

$npm install express --save

Project configuration is completed. Now we will create a simple express application that handles an HTTP-GET request.

$edit app.js
module.exports = function(cluster){
  var express = require('express')
  var app = express()
  app.get('/',function(req, res){
    console.log('Worker %d started!'+new Date(), cluster.worker.id);
    for(var i = 0; i < 999999999; i++) {}
    res.end('Hello from Worker ' + cluster.worker.id);
    console.log('Worker %d returned!'+new Date(), cluster.worker.id);
  });

  app.listen(8080,function(){
    console.log('Application started! Worker %d started!, process %d', cluster.worker.id, cluster.worker.process.pid);
  });
}

At line 6 simulating a heavy task that makes the CPU busy, so if another request comes, it will be assigned to another child process.

Next we will create our cluster application that manages multiple workers.

$edit cluster.js
var cluster = require('cluster');
var app = require('./app');

cluster.schedulingPolicy = cluster.SCHED_RR;
if(cluster.isMaster){
  var cpuCount = require('os').cpus().length;
  for (var i = 0; i < cpuCount; i += 1) {
    cluster.fork();
  }
}else{
  app(cluster);
}

cluster.on('fork', function(worker) {
console.log('forked -> Worker %d', worker.id);
});

At line 4 we set cluster schedulingPolicy to round-robin; if you want to rely on the operating system you can use cluster.SCHED_NONE. At line 5 checking if the current process is the main process, if so get the number of CPUs your machine has, and fork new child process for each CPU. Cluster will run the cluster.js as forking a new child process. As the “cluster.js” run for a child process at line 5 “cluster.isMaster” will return false, and application will be created for the child process which is a hello world express app.

Action time, let’s start our clustered application and see how it works.

$node cluster.js
forked -> Worker 1
forked -> Worker 2
forked -> Worker 3
forked -> Worker 4
forked -> Worker 5
forked -> Worker 6
forked -> Worker 7
forked -> Worker 8
Application started! Worker 2 started!, process 13716
Application started! Worker 4 started!, process 2444
Application started! Worker 5 started!, process 12656
Application started! Worker 6 started!, process 6276
Application started! Worker 3 started!, process 12044
Application started! Worker 8 started!, process 1100
Application started! Worker 1 started!, process 14756
Application started! Worker 7 started!, process 12268

I have opened 8 command windows and invoked localhost:8080/ in each, here is the result.

clients

And the server log is as follows:

Image title


Node.js cluster operating system

Opinions expressed by DZone contributors are their own.

Related

  • Establishing a Highly Available Kubernetes Cluster on AWS With Kops
  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • OpenShift Container Platform 4.11 Cluster Setup
  • A Beginner's Guide to Back-End Development

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!