Back to Digest
SnippetsNode.js Graceful Shutdown with Active Connection Draining
javascriptAdvancedCopied 347 times

Node.js Graceful Shutdown with Active Connection Draining

Production server teardown lifecycle handling SIGINT/SIGTERM, closing HTTP listeners, and terminating DB pools.

javascript•
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const http = require('http'); function setupGracefulShutdown(server, dbPool, timeoutMs = 10000) { let isShuttingDown = false; const shutdown = (signal) => { if (isShuttingDown) return; isShuttingDown = true; console.log(`Received ${signal}. Initiating graceful drainage...`); const forceKill = setTimeout(() => { console.error('Graceful shutdown timeout exceeded. Forcing termination.'); process.exit(1); }, timeoutMs); server.close(async () => { try { console.log('HTTP connections drained. Closing database connection pool...'); if (dbPool && typeof dbPool.end === 'function') { await dbPool.end(); } clearTimeout(forceKill); console.log('Cleanup complete. Process exiting gracefully.'); process.exit(0); } catch (err) { console.error('Error during teardown:', err); process.exit(1); } }); }; process.on('SIGTERM', () => shutdown('SIGTERM')); process.on('SIGINT', () => shutdown('SIGINT')); }
34 lines • 1041 charactersUsed by 347 developers

Usage & Production Best Practices

This implementation is specifically optimized for high-throughput production environments. When integrating this pattern into your codebase:

  • Ensure all asynchronous handles or listeners are cleaned up within the parent lifecycle.
  • Avoid unbounded memory allocation by pinning cache buffers and queue capacities.
  • Pair with automated unit tests to guarantee zero regressions under edge-case concurrency.
Featured Resourcein Node.js / DevOps
Curated Tool