PM2 Zero‑Instance Scaling: Auto‑Stop Timeout Configuration
0 reputation · 09 May 2024, 15:00 UTC
0 reputation · 09 May 2024, 15:00 UTC
Reduce hosting costs by allowing a Node.js application managed by PM2 to automatically stop all instances when traffic drops to zero.
PM2 lacks a built‑in mechanism to trigger a stop after a configurable period of inactivity. Users must rely on external scripts that monitor request rates and invoke pm2 stop or pm2 delete.
It is unclear whether a future PM2 version will expose a native auto‑stop option, and how permission boundaries affect the ability of monitoring scripts to control PM2 processes on shared hosting environments.
pm2 stop versus pm2 delete impact restart latency and environment variable re‑initialization when scaling to zero?32275 reputation · 09 May 2024, 15:13 UTC
PM2 does not have a built-in configuration option or flag to automatically stop instances based on an idle timeout or lack of traffic. To achieve "scale-to-zero" behavior, you must implement an external monitoring mechanism that tracks request rates and invokes the PM2 CLI when thresholds are met.
To safely invoke management commands on behalf of an application, the monitoring daemon must operate under the same user context as the PM2 process owner. Because PM2 manages processes via a local daemon (God Daemon) tied to a specific user's home directory (typically ~/.pm2), a daemon running as a different user or a restricted service account will not see the process list unless it is explicitly granted access to the PM2 socket and home directory.
pm2 binary.sudo -u [user] pm2 stop [app] to ensure it interacts with the correct daemon instance.When scaling to zero, the choice between pm2 stop and pm2 delete significantly affects the "cold start" latency and configuration persistence.
| Action | State Persistence | Restart Latency | Env Variables |
|---|---|---|---|
pm2 stop |
Preserved in list | Lower (Fast start) | Retained in memory |
pm2 delete |
Removed from list | Higher (Full init) | Must be re-loaded |
Recommendation: Use pm2 stop for scaling to zero. This maintains the process definition and environment variables within the PM2 daemon, allowing for a faster transition back to an active state via pm2 start [app].
You can verify the difference in state by running these commands in sequence:
# Stop the app and check if it remains in the list
pm2 stop app-name
pm2 list
# Delete the app and confirm it is gone
pm2 delete app-name
pm2 list
Diagnostic Detail Required: Are you using a ecosystem.config.js file for deployment? If so, pm2 delete requires a full pm2 start ecosystem.config.js to restore the environment, whereas pm2 stop allows a simple name-based restart.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.