More Node.js answers

by Danny
Published 2 min read

Listen for SIGTERM and SIGINT, stop accepting new connections, let in-flight requests finish and close resources before exiting. Learn the pattern and the Docker gotchas.

The short answer

#

Handle the SIGTERM and SIGINT signals. In the handler, call server.close() so no new connections are accepted, wait for open requests to finish, close database pools and other resources, then exit. Add a timeout so a stuck connection cannot block shutdown forever.


_23
import http from 'node:http';
_23
_23
const server = http.createServer(app);
_23
server.listen(3000);
_23
_23
function shutdown(signal) {
_23
console.log(`${signal} received, shutting down`);
_23
_23
server.close(async (error) => {
_23
await db.end();
_23
process.exit(error ? 1 : 0);
_23
});
_23
server.closeIdleConnections();
_23
_23
setTimeout(() => {
_23
console.error('Forcing shutdown');
_23
server.closeAllConnections();
_23
process.exit(1);
_23
}, 10_000).unref();
_23
}
_23
_23
process.once('SIGTERM', shutdown);
_23
process.once('SIGINT', shutdown);

Why it happens

#

When a platform stops your app, during a deploy, a scale-down or a restart, it sends SIGTERM first and gives the process time to finish. Docker, Kubernetes and most hosting platforms work this way. Pressing Ctrl+C in a terminal sends SIGINT.

If you do not handle the signal, Node.js exits straight away. Requests that were half way through get cut off, users see failed calls, and writes to the database or a queue may be left incomplete. If the process ignores the signal for too long, the platform sends SIGKILL, which cannot be caught, and the same thing happens anyway. Kubernetes, for example, waits 30 seconds by default.

How to fix it

#

Stop accepting work, then finish what is in flight

server.close() stops the server listening and calls its callback once every connection has closed. Keep-alive connections can stay open while idle, so server.closeIdleConnections() closes those without touching active requests. server.closeAllConnections() is the hard stop for the timeout path.

The unref() on the timer means the timer alone will not keep the process alive if everything else closes first.

Close everything else that holds the process open

Database pools, Redis clients, message consumers and intervals all keep the event loop busy. Close them in the shutdown path, in the reverse order you opened them. If the process does not exit on its own after that, something is still open.


_10
async function closeResources() {
_10
clearInterval(metricsTimer);
_10
await queueConsumer.stop();
_10
await db.end();
_10
}

Fail health checks while draining

Behind a load balancer, mark the instance as unhealthy as soon as shutdown starts, so traffic moves elsewhere while you finish existing requests.


_10
let shuttingDown = false;
_10
_10
app.get('/healthz', (req, res) => {
_10
res.status(shuttingDown ? 503 : 200).end();
_10
});

Make sure the signal reaches Node.js in Docker

Use the exec form of CMD so Node.js is the main process and receives signals directly. The shell form runs your command through /bin/sh, which does not pass SIGTERM on.


_10
# In a Dockerfile
_10
CMD ["node", "server.js"]

Running through npm start adds another process in between, which can also get in the way. Starting the container with docker run --init, or using a small init such as tini, handles signals and zombie processes properly.

Common pitfalls

#
  • Calling process.exit() at the top of the handler, which kills in-flight requests just as if you had no handler.
  • Registering with process.on and receiving the signal twice, so shutdown runs twice. process.once avoids that.
  • No timeout. One slow client or a leaked connection can hang the shutdown until the platform kills the process.
  • Testing only with Ctrl+C. Send SIGTERM with kill -TERM <pid> to test the path your platform actually uses.
  • Expecting SIGTERM handling on Windows. Windows does not support it in the same way; SIGINT from Ctrl+C does work.
#

Was this resource helpful?