Operations note · lifecycle
How do you gracefully stop a Node.js server?
Short answer
First stop accepting new work, then wait for active requests and connections only until an explicit deadline, then close the transport and external resources. Do not mix the graceful path with an emergency close: in swm-core, shutdown(timeout) waits for active work while close() ends the server immediately.
- drain
- active work
- deadline
- explicit timeout
- close()
- emergency path
Scope
The sequence describes @swarmmachina/swm-core 5.1.2 server lifecycle for Node.js 22/24. A real deadline must account for orchestration grace time, the reverse proxy, and your background-work duration.
Graceful shutdown order
| Stage | Action | Check |
|---|---|---|
| 1. Signal | Receive the stop signal and fix an absolute deadline, rather than waiting without a limit. | A process test proves that a second signal cannot start a competing shutdown race. |
| 2. Admission | Remove the instance from discovery or stop accepting new requests and upgrades. | A new HTTP request and WebSocket upgrade receive the expected refusal during drain. |
| 3. Drain | Give existing handlers time to finish within the shutdown timeout. | A long request either completes normally or reaches the deadline in a controlled way. |
| 4. Connections | For WebSocket, decide a close code, notification window, and the fate of undelivered messages. | A client test records the close event and reconnect path. |
| 5. Resources | After incoming work stops, close the logger, client pools, and background workers. | An integration test checks the final log event and resource completion. |
| 6. Fallback | After the deadline, use an immediate close and a non-zero operational signal when the platform requires it. | The test leaves no process or listening socket alive past the limit. |
Rules that prevent a hanging shutdown
- 01
The orchestrator grants a short stopping window
Agree on one time budgetThe application timeout must leave time for proxy removal, process termination, and fallback.
- 02
There are long-lived WebSockets
Define a connection policyWithout a close reason and reconnect behavior, graceful is only a name.
- 03
You need immediate termination
Call a distinct close pathIt must be explicit so an emergency stop cannot be mistaken for a successful drain.
What graceful shutdown does not do by itself
- It does not make an interrupted request idempotent or eliminate the need for a retry protocol.
- It does not guarantee WebSocket message delivery after close without an external durable layer.
- It does not replace readiness, liveness, or environment timeout policy.
Primary sources
The server API and related logging order can be checked in the fixed sources for the releases.