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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A clean shutdown lets in-flight requests finish while refusing new work, avoiding dropped responses.
- 2Track live sockets yourself so you can force-close stragglers when a drain deadline passes.
- 3Always pair a graceful drain with a hard timeout so a hung request can't block the process forever.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
python
import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent
How a Django settings module is wired
configuration
environment-variables
middleware
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/graceful-shutdown-in-an-express-server-explained-javascript-37cf/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.