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
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 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.