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

StageActionCheck
1. SignalReceive 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. AdmissionRemove 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. DrainGive existing handlers time to finish within the shutdown timeout.A long request either completes normally or reaches the deadline in a controlled way.
4. ConnectionsFor WebSocket, decide a close code, notification window, and the fate of undelivered messages.A client test records the close event and reconnect path.
5. ResourcesAfter incoming work stops, close the logger, client pools, and background workers.An integration test checks the final log event and resource completion.
6. FallbackAfter 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

  1. 01

    The orchestrator grants a short stopping window

    Agree on one time budget

    The application timeout must leave time for proxy removal, process termination, and fallback.

  2. 02

    There are long-lived WebSockets

    Define a connection policy

    Without a close reason and reconnect behavior, graceful is only a name.

  3. 03

    You need immediate termination

    Call a distinct close path

    It 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.