Advance

Dưới đây là giải thích chi tiết các câu hỏi của bạn về Cluster module, triển khai Node.js lên cloud, và quản lý tài nguyên, từ góc nhìn của một Senior Backend Developer:


🔸 1. Cluster module trong Node.js là gì và tại sao cần sử dụng?

✅ Mục tiêu:

Node.js chạy trên một luồng đơn (single-threaded) → không tận dụng hết sức mạnh CPU đa nhân.

✅ Cluster là gì?

Cluster module cho phép tạo ra nhiều tiến trình con (worker processes) chia sẻ cùng một server port, nhờ đó:

  • Tận dụng đa nhân CPU

  • Xử lý nhiều request song song

  • Cải thiện hiệu năng và khả năng mở rộng


✅ Khi nào nên dùng?

  • Ứng dụng CPU-intensive hoặc high-concurrency (chat, API server)

  • Khi bạn muốn zero-downtime restarts (thường kết hợp với PM2)


✅ Cách sử dụng:

const cluster = require('cluster');
const http = require('http');
const os = require('os');

if (cluster.isMaster) {
  const numCPUs = os.cpus().length;

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

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

  // Restart worker nếu bị crash
  cluster.on('exit', (worker) => {
    console.log(`Worker ${worker.process.pid} died`);
    cluster.fork();
  });

} else {
  // Workers share the TCP connection
  http.createServer((req, res) => {
    res.writeHead(200);
    res.end(`Handled by process ${process.pid}`);
  }).listen(3000);

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

🔸 2. Cách triển khai Node.js lên AWS hoặc Heroku

✅ Heroku (simple + fast)

Bước 1: Cài Heroku CLI và đăng nhập

heroku login

Bước 2: Tạo file Procfile

web: node index.js

Bước 3: Deploy

git init
heroku create my-app-name
git add .
git commit -m "Deploy to Heroku"
git push heroku master

Heroku sẽ tự động:

  • Cài dependencies (npm install)

  • Chạy server qua Procfile

  • Gán port qua process.env.PORT


✅ AWS EC2 (manual control)

Bước 1: Tạo EC2 Instance (Ubuntu)

  • SSH vào server

ssh -i key.pem ubuntu@your-ec2-ip

Bước 2: Cài Node.js, Git

curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs git

Bước 3: Clone repo & chạy

git clone https://github.com/your/repo.git
cd repo
npm install
node index.js

Bước 4: Dùng pm2 để quản lý tiến trình

npm install -g pm2
pm2 start index.js
pm2 startup
pm2 save

Bước 5: Mở port 80 hoặc 3000 qua security group


🔸 3. Quản lý và tối ưu tài nguyên trong Node.js

✅ Bộ nhớ:

  • Tránh lưu state lớn trong RAM (chuyển sang Redis hoặc DB)

  • Dọn bộ nhớ không cần thiết – tránh giữ references không dùng

  • Giới hạn bộ nhớ tối đa:

node --max-old-space-size=1024 index.js  # 1 GB heap limit

✅ Theo dõi memory leaks:

  • Dùng clinic, heapdump, memwatch-next để phân tích memory snapshot

  • Dùng process.memoryUsage() để log định kỳ RAM tiêu thụ


✅ Sử dụng công cụ:

  • PM2: Tự động restart app, cluster, monitoring

  • New Relic / Datadog / Prometheus: giám sát tài nguyên thật-time


✅ Tối ưu code:

  • Tránh synchronous I/O (dùng async/await hoặc stream)

  • Sử dụng caching (Redis, in-memory LRU)

  • Tránh deep clone, JSON.parse/stringify thường xuyên

  • Sử dụng Buffer thay vì string nếu làm việc với binary data


✅ Tóm tắt:

Chủ đề
Giải pháp

Cluster module

Dùng để scale app theo CPU cores

Triển khai lên cloud

Heroku (dễ), AWS EC2 (mạnh & tùy biến cao)

Quản lý tài nguyên

PM2, async code, caching, memory profiling


Last updated