@zukhruf/shutdown
v0.8.199
Published
A graceful shutdown for a Node.js program: SIGINT, SIGTERM, SIGHUP and crashes abort one AbortSignal, the program runs its cleanup, and then the process dies by the termination signal, so a shell, Docker or Kubernetes sees an interrupted process.
Maintainers
Readme
@zukhruf/shutdown
A graceful shutdown for a Node.js program. When the user presses Ctrl-C, or Docker stops the container, the program does not end at once. Its work stops when the signal aborts, its cleanup runs, and then the process ends by the same termination signal. Thus the shell, Docker or Kubernetes sees an interrupted process, not a process that completed its work. The package has no dependencies.
The words in these documents have one meaning each. See the glossary in CONTEXT.md.
Use it
npm install @zukhruf/shutdownStop the work at a termination signal
Make one Shutdown at the start of the entry point, before the first await. Then a termination signal during the start also stops the work. Give the signal to the work:
import { Shutdown } from '@zukhruf/shutdown';
using shutdown = new Shutdown();
using warehouse = new Warehouse('credits.sqlite');
await pipeline.run({ signal: shutdown.signal });The user presses Ctrl-C while the pipeline runs. Then:
- The signal aborts. Its reason is a
DOMExceptionwith the nameAbortErrorand the messageThe process received SIGINT. - The pipeline stops at its next check of the signal, and
run()returns. - The
usingscopes end in reverse order:warehousecloses, thenshutdown. - The event loop has no more work. Node.js emits
'exit'. - The package removes each listener for SIGINT and sends SIGINT to its own process. The process dies by SIGINT.
SIGINT, SIGTERM and SIGHUP start a shutdown. SIGQUIT does not: Ctrl-\ keeps its default action, which ends the process and writes a core dump.
Read what the parent sees
| Cause of the shutdown | Exit status | | ---------------------------------------------- | ---------------------------------------------------- | | A termination signal | The process dies by that signal | | A termination signal, and the process is PID 1 | Exit code 128 + the number of the signal (143) | | A crash | Exit code 1, or the exit code the program set | | No stop request | The exit code of the program, as without the package |
An exit code of 130 is not the same as a death by SIGINT. A Bash script stops its loop only when the child died by SIGINT. In a terminal, node app.js && next runs next after Ctrl-C when app.js exits with 0. When app.js dies by SIGINT, zsh stops the whole line. A parent that calls waitpid() sees the difference too: Node.js gives signal: 'SIGINT', not code: 130.
Handle a second stop request
The first stop request removes the termination signal listeners of the package. Thus a second termination signal gets the default action, and the process ends at once. Use this when the cleanup does not end. For example, a read from a pipe that no program writes waits in the thread pool of Node.js, and no signal can stop it. The second Ctrl-C ends the process.
The package has no timer. The supervisor owns the deadline of a shutdown:
| Supervisor | Deadline |
| ---------- | ---------------------------------------------------- |
| A terminal | The user presses Ctrl-C again |
| Docker | 10 s, then SIGKILL (stop_grace_period in Compose) |
| Kubernetes | 30 s, then SIGKILL (terminationGracePeriodSeconds) |
| systemd | 90 s, then SIGKILL (TimeoutStopSec) |
| Nx | 5 s, then SIGKILL (NX_PROCESS_KILL_GRACE_PERIOD) |
Handle a crash
A crash is an exception that no code catches, or a rejection that no code handles. Without the package, Node.js writes the error and ends the process at once. With the package, a crash is a stop request:
- The package writes the error to standard error.
- The signal aborts. Its reason is the error of the crash.
- The work stops, and the cleanup runs, as for a termination signal.
- The process exits with code 1.
A second crash gets the default of Node.js: it writes the error and ends the process at once. A termination signal after the crash also ends the process at once.
The exit status always follows the cause. A crash during the cleanup of a SIGINT shutdown ends the process at once, and the process dies by SIGINT. For this case the package keeps its crash listeners after a termination signal: it writes the error, and then it sends SIGINT to its own process. The default of Node.js cannot do it, because Node.js emits 'exit' before it writes the error of a crash.
Stop at the end of a scope
When the using scope of a Shutdown ends, the package removes its listeners and aborts the signal. Its reason is a DOMException with the name AbortError and the message The shutdown scope ended. This is not a stop request: the process does not die by a termination signal. After this, a termination signal gets the default action, and a crash gets the default of Node.js.
A stop request that came before the end of the scope stays. Then the end of the scope removes no listener, and the process still ends by its cause.
Run in a container
When the image starts the program with CMD ["node", "main.js"], Node.js is PID 1. The kernel does not apply the default action of a signal to PID 1, so the process cannot die by the termination signal. Then the package sets the exit code to 128 + the number of the signal. Docker reports Exited (143) for SIGTERM.
Give the container an init process to make the process die by the signal:
services:
app:
image: app
init: true
stop_grace_period: 10sWith init: true, tini is PID 1. The program dies by the signal, and tini gives that exit status to Docker.
Stop an HTTP server
The package does not stop a server. Node.js does most of it. An http.Server is AsyncDisposable, and server.close() stops new connections and closes the idle ones:
import { once } from 'node:events';
import { Shutdown } from '@zukhruf/shutdown';
using shutdown = new Shutdown();
await using server = serve({ fetch: app.fetch, port });
if (!shutdown.signal.aborted) {
await once(shutdown.signal, 'abort');
}
setTimeout(() => server.closeAllConnections(), 1_000).unref();Check signal.aborted before the wait. A signal that aborted before the call emits no 'abort' event again, so events.once(signal, 'abort') alone waits forever.
Do not wait with util.aborted(signal, resource) on a resource that nothing else holds. util.aborted() holds its resource weakly: when a garbage collection takes the resource before the signal aborts, the promise never settles (Node.js docs). In #3929, the websets app of context-compiler waited with util.aborted(ends, collections), and after a garbage collection took the array, the process stayed alive until a second SIGINT. The fix waits on the signal itself (context-compiler commit 2d8c016). The recipe Stop an HTTP server at a termination signal shows a full program.
A probe on Node.js 26.10.0 compared this with stoppable, which @godaddy/terminus uses:
| Case | stoppable (grace 1000 ms) | await using server | With closeAllConnections() after 1 s |
| -------------------------------- | --------------------------- | -------------------- | -------------------------------------- |
| An idle keep-alive connection | 0 ms | 0 ms | 0 ms |
| A request that answers in 300 ms | 251 ms | 6254 ms | 1001 ms |
| A request that does not answer | 1001 ms | open after 3000 ms | 1001 ms |
| A new client after the stop | refused | refused | refused |
Node.js keeps a connection that becomes idle after the call to close() until keepAliveTimeout (5000 ms). It keeps a request that does not answer until requestTimeout (300 s). A server that must close faster needs a drainer that ends each connection after its last response, as stoppable does.
What the package does not do
- Stop an HTTP server, or make a health check answer 503 during a shutdown. Node.js and the HTTP framework do these. See Stop an HTTP server.
- Run cleanup hooks.
using,await usingandAsyncDisposableStackrun the cleanup, in reverse order. - Stop the work for other causes.
AbortSignal.any([shutdown.signal, failed.signal])gives a signal that also aborts when the program stops itself. - Set a deadline. The supervisor sets it.
- Stop child processes.
@zukhruf/coprocessstops them. - A choice of termination signals. A program that must live on after its terminal closes runs under a supervisor or in tmux, not under
nohup: a listener for SIGHUP replaces the ignore ofnohup. - Windows. Windows has no POSIX signals.
Who uses it
Each consumer below is an entry point that makes one Shutdown. The package itself is backlog #3579.
| Consumer | How | Record |
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- |
| context-compiler: logful (apps/logful/src/main.ts) | pipeline.run({ signal: shutdown.signal }). It replaced an AbortController for the termination signals that exited with code 0. | #3580, context-compiler commit 9ea2c89 |
| context-compiler: startup-credits | AbortSignal.any([shutdown.signal, failed.signal]) is the signal of its loops. It throws the failure when only failed aborted. It replaced the same AbortController. | #3580, context-compiler commit 9ea2c89 |
| context-compiler: what-is-going-on | await aborted(shutdown.signal, server), then server.close(). It replaced the same AbortController. | #3580, context-compiler commit 9ea2c89 |
| context-compiler: the MCP server of the Codex plugin | new Shutdown() for the life of the process, with no dispose. A listener for 'abort' on shutdown.signal calls mcpServer.close(). It replaced the same AbortController. | #3580, context-compiler commit 9ea2c89 |
| context-compiler: websets | AbortSignal.any([shutdown.signal, failed.signal]) is the signal of its queue jobs and its loops. await aborted(watching, server), then server.close(). | context-compiler commit e9350c6, #3929 |
| context-compiler: ambient (apps/ambient/src/server.ts) | Promise.race([aborted(shutdown.signal, server), observer.failure]), then server.close() in a finally block. | context-compiler commit 673c1ae |
| context-compiler: ipay | pipeline.watch({ signal: shutdown.signal }). | context-compiler commit e30e754 |
| elt: the proactive app | pipeline.run({ signal: shutdown.signal }) and automations.run(shutdown.signal). Its await using stack closes the Postgres clients before the process dies by the signal. It replaced an AbortController. | #3581, elt commit aed72903 |
The same concepts in other systems
| Concept | Other systems |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Termination signals that cancel the work | signal.NotifyContext of Go; CancellationToken and ctrl_c of tokio; ApplicationStopping of the .NET Generic Host |
| Death by the signal after the cleanup | Proper handling of SIGINT/SIGQUIT (Cracauer); Termination in Handler of the GNU C Library; signal-exit; exitAsInterrupted() of Nx |
| The default action for a second signal | stop() of Go's NotifyContext; the SIGINT watcher of Playwright |
| A crash that starts a graceful shutdown | close-with-grace, which the eject server templates of fastify-cli use |
| An init process in a container | docker run --init and tini |
API
export class Shutdown implements Disposable {
/** Listens for SIGINT, SIGTERM, SIGHUP, uncaught exceptions and unhandled rejections. */
constructor();
/** Aborts at the first stop request. Its reason is the cause. */
readonly signal: AbortSignal;
/** Removes the listeners and aborts the signal. A stop request that came before stays. */
[Symbol.dispose](): void;
}| Call or event | What the package does |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| new Shutdown() | process.on() for SIGINT, SIGTERM, SIGHUP, 'uncaughtException', 'unhandledRejection' and 'exit' |
| The first termination signal | process.off() for each termination signal listener of the package, then AbortController.abort() with the AbortError |
| The first crash | console.error() of the error, process.off() for each termination signal and crash listener of the package, then abort() with the error |
| A crash after a termination signal | console.error() of the error, then process.exit(). The 'exit' listener then ends the process by the signal |
| 'exit' after a termination signal | process.removeAllListeners() for that termination signal, then process.kill(process.pid, signal). When the process still runs: process.exitCode = 128 + n (util.convertProcessSignalToExitCode()) |
| 'exit' after a crash | process.exitCode \|\|= 1: exit code 1, unless the program set a failure code |
| [Symbol.dispose]() | With no stop request: process.off() for each listener of the package, 'exit' too, then abort(). After a stop request: nothing |
Documentation
Recipes
- Stop an HTTP server at a termination signal
- Stop the work at a termination signal or at a failure of the program
Decisions
