Non-zero exit code restart loop in PM2 process manager
0 reputation · 22 Mar 2023, 17:08 UTC
Automatic Restart Behavior and Idempotency
PM2 is configured to automatically restart Node.js processes that exit with a non-zero code. Because this mechanism re-executes the entry point script without preserving in-memory state, applications performing asynchronous write operations may face challenges regarding data duplication.
If a process crashes after a database write has been initiated but before the operation is fully acknowledged or recorded in a local state, the subsequent PM2 restart will trigger the logic again. PM2 provides max_restarts and restart-delay to manage the frequency of these cycles, but it does not offer transactional guarantees across process lifecycles.
Given these constraints, how can an application distinguish between a fresh start and a PM2-initiated restart to avoid duplicate writes? Is there a documented way to detect the restart trigger within the application logic to ensure idempotency?