Using Clustering to Improve Node.js Performance

Discover how to leverage clustering to enhance the performance and scalability of your Node.js applications.

0 likes
4 views

Rule Content

{
  "title": "Using Clustering to Improve Node.js Performance",
  "description": "Discover how to leverage clustering to enhance the performance and scalability of your Node.js applications.",
  "category": "Node.js Cursor Rules",
  "rules": [
    {
      "id": "nodejs-clustering-implementation",
      "description": "Implement clustering in your Node.js application to utilize all available CPU cores, enhancing performance and scalability.",
      "recommendation": "Use the built-in 'cluster' module to create multiple worker processes that share the same server port, allowing the application to handle more concurrent requests efficiently.",
      "codeExample": "const cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n  cluster.on('exit', (worker, code, signal) => {\n    console.log(`Worker ${worker.process.pid} died`);\n    cluster.fork();\n  });\n} else {\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end('Hello World\\n');\n  }).listen(8000);\n}"
    },
    {
      "id": "nodejs-clustering-process-manager",
      "description": "Utilize a process manager to manage your clustered Node.js application effectively.",
      "recommendation": "Employ tools like PM2 to handle process management tasks such as monitoring, automatic restarts, and load balancing, ensuring high availability and reliability.",
      "codeExample": "module.exports = {\n  apps: [\n    {\n      name: 'app-name',\n      script: 'app.js',\n      instances: 'max',\n      exec_mode: 'cluster',\n      autorestart: true,\n      watch: false,\n      max_memory_restart: '1G',\n      env: {\n        NODE_ENV: 'production'\n      }\n    }\n  ]\n};"
    },
    {
      "id": "nodejs-clustering-sticky-sessions",
      "description": "Implement sticky sessions to ensure consistent session handling across clustered Node.js applications.",
      "recommendation": "Configure your load balancer to use sticky sessions, directing requests from the same client to the same worker process, which is essential for applications that rely on in-memory session data.",
      "codeExample": "const session = require('express-session');\nconst RedisStore = require('connect-redis')(session);\n\napp.use(session({\n  store: new RedisStore({\n    host: 'localhost',\n    port: 6379\n  }),\n  secret: 'your-secret-key',\n  resave: false,\n  saveUninitialized: false\n}));"
    },
    {
      "id": "nodejs-clustering-monitoring",
      "description": "Monitor the health and performance of your clustered Node.js application.",
      "recommendation": "Implement monitoring tools to track metrics such as CPU and memory usage, response times, and error rates across all worker processes to ensure optimal performance and stability.",
      "codeExample": "const express = require('express');\nconst app = express();\n\napp.get('/status', (req, res) => {\n  res.json({\n    memoryUsage: process.memoryUsage(),\n    uptime: process.uptime()\n  });\n});\n\napp.listen(3000);"
    },
    {
      "id": "nodejs-clustering-error-handling",
      "description": "Implement robust error handling and automatic recovery mechanisms in your clustered Node.js application.",
      "recommendation": "Set up listeners for worker process exit events to automatically restart failed workers, ensuring continuous availability of your application.",
      "codeExample": "const cluster = require('cluster');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  for (let i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n  cluster.on('exit', (worker, code, signal) => {\n    console.log(`Worker ${worker.process.pid} died. Restarting...`);\n    cluster.fork();\n  });\n} else {\n  // Worker code\n}"
    }
  ]
}