Graceful Shutdown
Connectum provides built-in graceful shutdown support that handles signal interception, connection draining, shutdown hooks with dependency ordering, and integration with Kubernetes lifecycle.
Quick Setup
import { createServer } from '@connectum/core';
import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck';
const server = createServer({
services: [routes],
protocols: [Healthcheck({ httpEnabled: true })],
shutdown: {
autoShutdown: true, // Handle SIGTERM/SIGINT automatically
timeout: 30000, // 30 seconds to drain connections
},
});
server.on('ready', () => {
healthcheckManager.update(ServingStatus.SERVING);
});
server.on('stopping', () => {
healthcheckManager.update(ServingStatus.NOT_SERVING);
});
server.on('error', (err) => {
console.error('Server error:', err);
});
await server.start();The error listener makes signal-triggered shutdown failures visible; exit-code policy belongs to your application.
Shutdown Options
The shutdown option in createServer() accepts a ShutdownOptions object:
interface ShutdownOptions {
/** Timeout in ms for graceful shutdown (default: 30000) */
timeout?: number;
/** Signals to listen for (default: ['SIGTERM', 'SIGINT']) */
signals?: NodeJS.Signals[];
/** Auto-handle signals (default: false) */
autoShutdown?: boolean;
/** Force close every client connection on timeout (default: true) */
forceCloseOnTimeout?: boolean;
}| Option | Default | Description |
|---|---|---|
timeout | 30000 | Maximum time (ms) to wait for in-flight requests. Bounds the connection drain only, not the shutdown hooks |
signals | ['SIGTERM', 'SIGINT'] | OS signals that trigger shutdown |
autoShutdown | false | Automatically install signal handlers when start() begins (signals during startup) |
forceCloseOnTimeout | true | Destroy every remaining client connection (HTTP/1.1, h2c, TLS) if the timeout is exceeded |
createServer() validates the shutdown options and throws instead of starting a server that would cut connections at once or never handle the signal:
timeoutmust be an integer from0to2147483647(the largest delay a Node.js timer accepts).0means "do not wait for in-flight requests". A number outside that range (NaN,Infinity, a negative or fractional number, a larger value) throws aRangeError; a value that is not a number throws aTypeError.forceCloseOnTimeoutmust be a boolean; anything else throws aTypeError.autoShutdownmust be a boolean; anything else (the string"yes", for example) throws aTypeError.signalsmust be a non-empty array of signal names the platform knows, such as'SIGTERM'or'SIGUSR2'. An empty list, a string in place of an array, an unknown or lowercase name, andSIGKILLandSIGSTOP(a process cannot handle them) throw aTypeErrororRangeErrorthat namesshutdown.signals, and the signal when one is unknown. The check also runs whileautoShutdownis off. Without it, such a value left no handler installed, andSIGTERMended the process without running the shutdown hooks.
Both error messages name the option and the rejected value, in the same form as the readMaxBytes check. Leaving an option out, or setting it to undefined, keeps the default.
Shutdown Sequence
When server.stop() is called (or a signal is received with autoShutdown: true), the following sequence executes:
1. STOPPING event -- Notify listeners (update health check to NOT_SERVING)
2. Abort signal -- Abort context.signal of every in-flight RPC, over HTTP and
in-process (localClient, ctx.call), and long-running operations
3. Transport close -- Stop accepting new connections, send GOAWAY to every HTTP/2 session
4. Timeout race -- Wait for in-flight requests OR timeout
5. Force close -- If timeout + forceCloseOnTimeout: destroy every remaining connection
6. Shutdown hooks -- Execute registered hooks in dependency order
7. Dispose -- Clean up internal state
8. STOP event -- Server is fully stoppedSteps 6 and 7 run even if closing the transport fails before the timeout, so your hooks always get to release their resources, and step 7 also runs if a hook fails. On this failure path the server emits error and then still emits stop, and stop() rejects with the error that occurred — or with an AggregateError carrying both when the transport close and a hook both failed. A close failure that only arrives after the timeout has already won is logged, not thrown: if the hooks succeed, stop() resolves normally.
A failing hook does not stop the others. Every hook runs and stop() waits for all of them before it emits stop and settles, because each hook releases a resource of its own and one failure says nothing about whether the rest can still succeed. A hook that depends on a failed hook runs once the failed one has finished. stop() then rejects with the failure itself when one hook failed, or with an AggregateError of all failures in registration order when several did (when the transport close failed as well, the AggregateError carries the close error and the hooks' error). A hook that never settles keeps stop() waiting, as it always has, so give hooks that talk to the network their own timeout.
Server streams
A server stream whose handler is still sending when step 2 aborts the signal is ended by the framework. The client receives the messages already sent and then an error:
| How the stream ends | What the client sees |
|---|---|
The handler ignores ctx.signal and stop() cuts the stream | unavailable ("the server is shutting down"), over Connect, gRPC and in-process alike |
| A deadline expires while the stream is sending | deadline_exceeded |
| The client aborts the call | canceled |
| The handler returns by itself after it sees the abort | A normal end: that is the handler's decision |
The handler converts the abort reason itself, for example throw ConnectError.from(ctx.signal.reason) | The error the handler raised: canceled |
A normal end of stream means "the list is complete" to a client, so a stream the server had to cut must not look like one. unavailable tells a client that the call can be retried against another instance. Upgrading from 1.2, where such a stream ended without an error: see Streams cut by stop().
In-process calls
Since 1.3.0, step 2 also covers in-process calls: context.signal is aborted for calls made through server.localClient(), server.client() for a local service, createLocalTransport(), and ctx.call / ctx.stream to a local service; every hop of a local ctx.call chain sees it directly. A handler or stream that rethrows the abort ends the call with canceled, as over HTTP, and an in-process stream whose handler ignores the signal is cut with unavailable exactly like an HTTP one (see Server streams).
Steps 4 and 5 act on connections, and an in-process call has none: stop() neither waits for it nor destroys it, so a handler that ignores the signal keeps running and still completes its call. A unary or client-streaming call made after stop() starts with an already-aborted signal and runs. A server-streaming or bidirectional call made after stop() has begun, from a shutdown hook for example, cannot be served: its first read fails with unavailable and the handler body does not start, so a hook never mistakes an empty list for a real answer.
A client-streaming or bidirectional handler that is waiting for the next request message is released when the caller cancels the call (its AbortSignal or a deadline): its for await over the requests ends and its finally runs, as over HTTP/2. stop() does not do that. It does not end an in-process call, so an upload that is still being sent keeps being read and the call completes, as it does over HTTP/2 within the shutdown timeout. Upgrading from 1.2: see In-process calls on shutdown.
EventBus
A bus passed as createServer({ eventBus }) is stopped by a shutdown hook named eventbus in step 6, after the timeout race. Its handler and publish drain budgets therefore add to the time stop() takes; they are not bounded by shutdown.timeout. See Shutdown drain.
The bus stops receiving earlier than that, at step 2: the abort of the shutdown signal ends its subscriptions, and a delivery that is still on its way is returned to the broker instead of starting a handler with an aborted ctx.signal. Handlers that are already running finish, may publish through ctx.publish, and are drained by the hook as before. Since 1.3.0; see Event bus stops receiving at the shutdown signal.
Closing a subscription can take time of its own. A Kafka consumer finishes stopping only when the fetch request it has open returns, which takes up to five seconds for an idle consumer; the consumers of a bus stop together, so the bus waits for the slowest one. Count it into the time the eventbus hook adds. See Stopping a consumer.
Shutdown Hooks
Shutdown hooks allow you to run cleanup logic during shutdown with dependency ordering. Register them via server.onShutdown().
Anonymous Hooks
server.onShutdown(async () => {
await db.close();
});
server.onShutdown(() => {
console.log('Cleanup complete');
});Named Hooks
Give hooks names for better logging and dependency management:
server.onShutdown('database', async () => {
await db.close();
console.log('Database connections closed');
});
server.onShutdown('cache', async () => {
await redis.quit();
console.log('Cache connections closed');
});Hooks with Dependency Ordering
Specify dependencies to control execution order. Dependencies execute first:
// Release the database before the dependent cleanup hooks below
server.onShutdown('database', async () => {
await db.close();
});
// Cache depends on database (database shuts down first)
server.onShutdown('cache', ['database'], async () => {
await redis.quit();
});
// Message queue depends on both database and cache
server.onShutdown('message-queue', ['database', 'cache'], async () => {
await mq.disconnect();
});Execution order follows the dependency edges:
Cycle detection
The shutdown manager detects dependency cycles at registration time. The call that closes the cycle throws and is not registered:
server.onShutdown('a', ['b'], () => {}); // Accepted: 'b' is not registered yet
server.onShutdown('b', ['a'], () => {});
// Throws: Adding shutdown handler "b" would create a dependency cycleArgument checks
A call that matches none of the three forms -- onShutdown(handler), onShutdown(name, handler), onShutdown(name, dependencies[], handler) -- throws a TypeError that starts with onShutdown( at registration. That covers a missing hook function, a module name that is not a string, dependencies that are not an array of strings, and a single name passed where the array belongs (onShutdown('x', 'db', fn)).
A dependency on a name that no hook registers is not an error: hooks may be registered in any order, so the name may be registered later. If it never is, the dependency is satisfied at once and the server logs a warning when it stops; see Dependency on an unregistered name.
Dependency on an unregistered name
A dependency on a name that no hook registered is not an error. Hooks can be added in any order, so the names are checked once, when the server stops. The hook that names a missing dependency still runs, and it runs at once because there is nothing to wait for. A misspelled name silently loses the ordering you meant, so the server reports it:
server.onShutdown('api', ['db'], async () => {
await api.drain();
});
// No hook named 'db' is ever registered.When the server stops, the logger receives one warning:
Shutdown hook "api" depends on "db", but no shutdown hook is registered under that name, so there is nothing to wait for. Check the name passed to onShutdown().- One warning per missing name. If several hooks depend on the same missing name, a single warning lists them:
Shutdown hooks "a", "b" depend on "db", .... Each different missing name gets its own warning. - A later registration is fine. A dependency registered after the hook that names it gives no warning, as long as it is registered before the hooks run. The ordering then applies as usual.
- The warning goes to the server logger. That is
console.warnunless you passloggertocreateServer().
Multiple Handlers per Module
You can register multiple handlers for the same named module. They run in parallel:
server.onShutdown('database', async () => {
await primaryDb.close();
});
server.onShutdown('database', async () => {
await replicaDb.close();
});
// Both database handlers run in parallel during shutdownAutomatic vs Manual Shutdown
Automatic Shutdown
With autoShutdown: true, the server installs signal handlers automatically:
const server = createServer({
services: [routes],
shutdown: {
autoShutdown: true,
signals: ['SIGTERM', 'SIGINT'], // default
timeout: 30000,
},
});
server.on('error', (err) => {
console.error('Server error:', err);
});
await server.start();
// Server stops cleanly on SIGTERM or SIGINT (Ctrl+C)The signal handlers are installed when start() begins and removed when the server stops or its start fails. All servers in a process share one process listener per signal, so a process (or a test suite) that hosts eleven or more servers with autoShutdown does not trigger Node.js's MaxListenersExceededWarning; each server still reacts to the signal on its own. See Signals during startup for what happens when the signal arrives before start() has finished.
Repeated signals
The first SIGTERM or SIGINT starts the graceful shutdown. A second signal that arrives while the server is still stopping ends the process at once, in the middle of the shutdown hooks, with the same result as Node.js gives a process that has no handler for the signal (the process is terminated by that signal). This is deliberate: it is how an operator ends a shutdown that hangs, for example on a hook that never settles (see Hooks run after the timeout) — a second Ctrl-C in a terminal, or kill again.
The server logs a warning before it does so:
Received SIGTERM again while the server is shutting down; the process is terminated now, without waiting for the remaining shutdown hooksThe hooks that have not finished are cut short, and the stop event is not emitted. Plan for this when a hook releases something that must not be left half-done.
If your application registers its own process.on('SIGTERM', ...) listener (a process.once listener is not counted once it has run, because Node.js removes it before calling it), or another server in the same process is running, the process is not terminated: the listener receives the signal, and the warning says that other listeners handle it. A signal that arrives after stop() has completed is not handled by the server at all.
Manual Shutdown
Without autoShutdown, call server.stop() yourself:
const server = createServer({
services: [routes],
// autoShutdown defaults to false
});
await server.start();
// Manual shutdown handler
process.on('SIGTERM', async () => {
console.log('Received SIGTERM');
healthcheckManager.update(ServingStatus.NOT_SERVING);
// Optional: wait for load balancers to drain
await new Promise(resolve => setTimeout(resolve, 5000));
await server.stop();
process.exit(0);
});When to use manual shutdown
Manual shutdown is useful when you need to perform actions before calling server.stop(), such as waiting for load balancer drain or notifying external services.
Repeated stop() calls
server.stop() is safe to call more than once, for example from a signal handler and from your own code:
- Concurrent calls while shutdown is in progress await the same shutdown operation and settle with its outcome, also when it fails.
- A call after the server has stopped resolves immediately. It does not run the shutdown hooks again and emits no events.
- A call on a server that was never started rejects: that is a lifecycle mistake, not a repeat. A rejected
stop()beforestart()leaves the server in thecreatedstate. - A call while
start()is still in progress is honoured, see Stop and signals during startup. server.onShutdown()on a server that has already stopped throws, because the hook could never run.
// Both resolve when the single shutdown completes
await Promise.all([
server.stop(),
server.stop(),
]);
await server.stop(); // already stopped: resolves, does nothingStop and signals during startup
Starting is the slowest phase when an eventBus connects to a broker, and a termination request is the one request an operator cannot repeat: Kubernetes sends SIGTERM once and follows with SIGKILL after the grace period. A request that arrives while start() is still in progress is therefore honoured, not dropped:
server.stop()waits for the start to settle and then stops the server, so the sequence isstart,ready,stopping,stop; the event bus and the shutdown hooks run as usual.start()resolves first, and the server is alreadystoppingwhen the caller ofstart()resumes.- Several
stop()calls made during startup all settle with the outcome of that one stop. - If the start fails,
start()rejects as before and the pendingstop()resolves, because the server is already stopped and there is nothing left to stop. - With
autoShutdown, the signal handlers exist from the momentstart()begins, so aSIGTERMorSIGINTduring startup follows the same path. Before 1.3 the handlers appeared only after the port was bound, and a signal during a slow startup ended the process with the default signal action (exit code 143 forSIGTERM) without running hooks or stopping the event bus.
The request waits for the start to settle. A start() that never settles (a broker connection without a timeout) keeps the stop pending as well, so give a startup step that can hang its own timeout. The process stays killable meanwhile: with autoShutdown, the first signal during the start releases the framework's signal handlers, so a second SIGTERM or SIGINT gets the default action and ends the process, the same as a repeated signal while a running server is stopping. A manual stop() has no such escape; end the process yourself if the start does not settle.
Kubernetes Integration
Recommended Configuration
For Kubernetes deployments, combine graceful shutdown with health checks and a pre-stop hook:
const server = createServer({
services: [routes],
protocols: [Healthcheck({ httpEnabled: true })],
shutdown: {
autoShutdown: true,
timeout: 25000, // Connection-drain budget; hooks need separate time
},
});
server.on('ready', () => {
healthcheckManager.update(ServingStatus.SERVING);
});
server.on('stopping', () => {
healthcheckManager.update(ServingStatus.NOT_SERVING);
});Pod Specification
apiVersion: v1
kind: Pod
spec:
# Set terminationGracePeriodSeconds from the shutdown budget below.
containers:
- name: my-service
image: my-service:latest
ports:
- containerPort: 5000
readinessProbe:
httpGet:
path: /healthz
port: 5000
periodSeconds: 5
lifecycle:
preStop:
exec:
# Give load balancers time to remove this pod
command: ["sleep", "5"]Shutdown Timeline
Critical
Kubernetes runs preStop before sending the termination signal, and the grace-period countdown includes the hook. See the Kubernetes container lifecycle hook documentation. Set terminationGracePeriodSeconds to cover the preStop delay, shutdown.timeout, the maximum time your hooks can take, and a safety margin: preStop + connection-drain timeout + maximum hook duration + margin. The value of shutdown.timeout bounds the connection-drain phase; it does not bound shutdown hooks. Keep hooks bounded so Kubernetes does not SIGKILL the process before they finish.
Hooks run after the timeout
shutdown.timeout limits the connection drain. It does not limit shutdown hooks: stop() waits for every hook, and a hook that never settles (a database client that does not close, a broker that does not answer) keeps stop() pending. Under Kubernetes the pod then runs until the grace period ends and the process is killed with SIGKILL.
The server does not cut hooks off, so a hang is made visible instead. When the timeout has elapsed and hooks are still running, the server writes one warning to its logger (the logger option of createServer(), console by default) naming the hooks that have not finished and the time since shutdown began:
Shutdown timeout (30000ms) has elapsed and shutdown hooks are still running after 30004ms: broker. The timeout does not bound shutdown hooks, so stop() keeps waiting for them. Make sure each hook settles, or the orchestrator will kill the process.- Only hooks that are executing are named. A hook that waits for a dependency is not listed, so the list points at the hook that is stuck rather than at the ones queued behind it.
- A hook registered without a name appears as
anonymous hook #N, N being its registration order starting from 0. Give hooks names to make this line readable. - If the connection drain itself used up the timeout, hooks get the same budget again from their own start before the warning appears, so a quick hook after a drain timeout produces no warning.
- Nothing about the shutdown changes: the warning appears once and
stop()keeps waiting. To end a shutdown that hangs, send the signal again (see Repeated signals) or bound the hook in your own code with a deadline of your choice.
Timeout and Force Close Behavior
With forceCloseOnTimeout: true (default)
Until the timeout, the server does not force-close any connection: HTTP/2 clients have been sent GOAWAY so they can finish and disconnect, and in-flight requests are allowed to complete. Handlers that observe the abort signal (step 2 above) — typically long-running streaming RPCs — are asked to stop at the start of shutdown and may end earlier than the timeout. When the timeout is exceeded, every connection that is still open is destroyed, on every transport — plaintext HTTP/1.1 (the default), h2c, and TLS, including connections that never finished a request or a TLS handshake. Requests still in flight at that moment are aborted.
shutdown: {
timeout: 30000,
forceCloseOnTimeout: true, // default
}This bounds the connection drain by the timeout even if a client holds its connection open (ignores GOAWAY, idles, or stalls mid-request), so no connection accepted by the server keeps the process alive afterwards. stop() runs the shutdown hooks as soon as every connection has closed or the timeout has won, whichever comes first, and completes when your hooks have finished — keep hooks fast. Connectum never calls process.exit(); anything your own code keeps open (timers, handlers that ignore the abort signal, other sockets) can still keep the process running.
With forceCloseOnTimeout: false
No connection is destroyed. Shutdown still moves on when every connection has closed or the timeout has won, whichever comes first: stop() runs the shutdown hooks and completes when they have finished (or rejects if one fails), exactly as with the default. Connections that clients keep open stay open, though, and keep the process alive until those clients close them:
shutdown: {
timeout: 30000,
forceCloseOnTimeout: false,
}WARNING
With forceCloseOnTimeout: false, the process may not exit if a client holds a connection open indefinitely. Use only when you control all clients and can guarantee they will close connections.
Complete Production Example
Use the Quickstart's greeterService and supply your connected db and redis clients. Initialize the OTel provider before starting this server; the hook below only shuts it down.
import { createServer } from '@connectum/core';
import { Healthcheck, healthcheckManager, ServingStatus } from '@connectum/healthcheck';
import { Reflection } from '@connectum/reflection';
import { createDefaultInterceptors } from '@connectum/interceptors';
import { shutdownProvider } from '@connectum/otel';
import { greeterService } from './services/greeterService.ts';
const server = createServer({
services: [greeterService],
port: 5000,
protocols: [Healthcheck({ httpEnabled: true }), Reflection()],
interceptors: createDefaultInterceptors(),
shutdown: {
autoShutdown: true,
timeout: 25000,
forceCloseOnTimeout: true,
},
});
// Register shutdown hooks with dependencies
server.onShutdown('database', async () => {
await db.close();
});
server.onShutdown('cache', async () => {
await redis.quit();
});
server.onShutdown('otel', ['database', 'cache'], async () => {
await shutdownProvider();
});
// Lifecycle hooks
server.on('ready', () => {
healthcheckManager.update(ServingStatus.SERVING);
});
server.on('stopping', () => {
healthcheckManager.update(ServingStatus.NOT_SERVING);
});
server.on('stop', () => {
console.log('Server stopped');
});
server.on('error', (err) => {
console.error('Server error:', err);
});
await server.start();Related
- Server Overview -- quick start and key concepts
- Lifecycle -- states, events, and the shutdownSignal
- Health Checks & Kubernetes -- configure health monitoring
- Configuration -- environment variables and TLS
- @connectum/core -- Package Guide
- @connectum/core API -- Full API Reference