javascript 53 lines · 9 steps

Graceful shutdown in an Express server

How to drain in-flight requests and reject new ones when an Express process receives a termination signal.

Explained by highlit
1const express = require('express');
2const app = express();
3 
4app.get('/health', (req, res) => res.json({ status: 'ok' }));
5 
6app.get('/slow', async (req, res) => {
7 await new Promise((r) => setTimeout(r, 5000));
8 res.json({ done: true });
9});
10 
11const server = app.listen(process.env.PORT || 3000, () => {
12 console.log(`Listening on ${server.address().port}`);
13});
14 
15const connections = new Set();
16server.on('connection', (socket) => {
17 connections.add(socket);
18 socket.on('close', () => connections.delete(socket));
19});
20 
21let shuttingDown = false;
22 
23app.use((req, res, next) => {
24 if (shuttingDown) {
25 res.set('Connection', 'close');
26 return res.status(503).json({ error: 'Server is shutting down' });
27 }
28 next();
29});
30 
31function shutdown(signal) {
32 if (shuttingDown) return;
33 shuttingDown = true;
34 console.log(`${signal} received, draining connections...`);
35 
36 server.close((err) => {
37 if (err) {
38 console.error('Error during shutdown', err);
39 process.exit(1);
40 }
41 console.log('All connections drained, exiting cleanly');
42 process.exit(0);
43 });
44 
45 const forceTimer = setTimeout(() => {
46 console.warn('Drain timeout exceeded, forcing socket close');
47 for (const socket of connections) socket.destroy();
48 }, 10_000);
49 forceTimer.unref();
50}
51 
52process.on('SIGTERM', () => shutdown('SIGTERM'));
53process.on('SIGINT', () => shutdown('SIGINT'));
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A clean shutdown lets in-flight requests finish while refusing new work, avoiding dropped responses.
  2. 2Track live sockets yourself so you can force-close stragglers when a drain deadline passes.
  3. 3Always pair a graceful drain with a hard timeout so a hung request can't block the process forever.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Graceful shutdown in an Express server — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code