Nâng CaoNode.js iconNode.js

Clustering trong Node.js là gì? Tại sao cần thiết?

Node.js single-threaded chỉ dùng một CPU core — server 16-core lãng phí 15 cores.

  • Cluster module: master process fork N worker processes (thường = số CPU cores: os.cpus().length), mỗi worker là Node.js process độc lập, share cùng port.
  • Connection distribution: Linux dùng round-robin (master nhận connection rồi distribute), Windows dùng OS scheduling.
  • IPC communication: process.send(msg) từ worker, worker.on('message', handler) ở master — dùng để share state nhỏ như worker health.
  • Shared nothing architecture: workers không share memory, mỗi worker có heap riêng — session/cache phải dùng Redis thay vì in-memory.
  • Sticky sessions: cần khi dùng WebSocket — load balancer phải route cùng client đến cùng worker (nginx ip_hash).
  • PM2 cluster mode: pm2 start app.js -i max tự động quản lý cluster với zero-downtime reload (pm2 reload app) — reload từng worker một thay vì restart toàn bộ.
  • Khi nào dùng cluster vs reverse proxy: cluster cho vertical scaling trên một server, Nginx/HAProxy cho horizontal scaling nhiều servers.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js