GardenCloud & systems

PM2 cluster mode and the state between workers

An older ecosystem configuration for two Node workers, with readiness, shutdown, and shared-state assumptions.

Cluster mode runs several Node application workers behind PM2’s process management. The old note paired this with a stateless application: state that must be shared cannot live only in one worker’s memory.

Make sure your application is stateless: share database/cache, cronjob

The earlier ecosystem file

// https://pm2.keymetrics.io/docs/usage/application-declaration/
// # Start all applications
// pm2 start ecosystem.config.js
//
// # Stop all
// pm2 stop ecosystem.config.js
//
// # Restart all
// pm2 restart ecosystem.config.js
//
// # Reload all
// pm2 reload ecosystem.config.js
//
// # Delete all
// pm2 delete ecosystem.config.js
module.exports = {
  apps: [{
    name: "nestjs-prod",
    script: "./dist/main.js", // cluster mode run with node only, not npm
    args: "",
    exec_mode : "cluster", // default fork
    instances: 2, //"max",
    kill_timeout : 4000,
    wait_ready: true,
    autorestart: true,
    watch: false,
    max_memory_restart: "1G",
    log_date_format : "YYYY-MM-DD HH:mm Z",
    env: {
      NODE_ENV: "prod"
    },
  }]
};

This starts two workers, disables file watching, and sets a four-second kill timeout. wait_ready assumes the application sends the readiness signal PM2 expects; declaring it does not create that signal. The recorded NODE_ENV value is prod, which is application-specific and should not silently be treated as production.

What clustering does not coordinate

A process-local session, lock, cache, or counter remains local. A scheduled job can also run once per worker unless its ownership is deliberately coordinated. Shared storage solves access to data, but does not by itself establish single execution of background work.

Readiness and graceful shutdown need to cover real in-flight work. A process manager reporting two online workers is not evidence that requests succeed under load. The companion JMeter note describes a separate measurement step. No workers were launched for this revision.

References: PM2 cluster mode and the earlier NestJS template.

← Back to the garden