Cluster

August 25, 2018 - 2 minute read -
Web

싱글쓰레드 기반의 Node js는 태생적으로 하나의 인스턴스가 하나의 cpu만 사용하게 된다. 여기서 멀티프로세서의 자원을 모두 사용하기 위해서 사용 되는 것이 Cluster다 .

쉽게 말하면 cluster는 새끼 낳는 모듈이다.

const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} died`);
    });
} else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    http.createServer((req, res) => {
    res.writeHead(200);
    res.end('hello world\n');
    }).listen(8000);

    console.log(`Worker ${process.pid} started`);
}

위는 공식 문서에 나와있는 예시이다. 마스터 클러스터에서 cpu 수 만큼 자식 프로세스를 fork하고, 마스터가 아닌 worker 클러스터에서는 해야 할 일을 코딩한다.

클러스터 모듈은 들어오는 연결을 각각의 클러스터들에게 분배 할 때 두 가지 방법을 지원한다.

첫 번 째는 Round-Robin기법을 기반으로, 마스터 클러스터가 자식 클러스터들에게 균등하게 일을 배분하는 것이다.

두번 째는, 마스터클러스터가 listen socket을 생성하고 워커들에게 보낸다. 워커들은 이 소켓을 통해 들어오는 연결들을 직접적으로 핸들링하게 된다. 이 방법은 분배를 OS측에서 맡게 되는데, 이론 상으로는 가장 좋은 퍼포먼스를 보이지만, 한 쪽에 치우친 분배가 일어날 수 있는 문제가 있다.

Resource

https://nodejs.org/api/cluster.html