Node.js Graceful Shutdown with Active Connection Draining
Production server teardown lifecycle handling SIGINT/SIGTERM, closing HTTP listeners, and terminating DB pools.
12345678910111213141516171819202122232425262728293031323334const 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')); }
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.
Client-Side AES-256-GCM Encryption with Web Crypto API
Production-ready recipe for client-side aes-256-gcm encryption with web crypto api. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Node.js Memory Leak Detector with Heap Snapshot Sampling
Production-ready recipe for node.js memory leak detector with heap snapshot sampling. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Node.js Cluster Mode Worker Spawner with Zero-Downtime Reload
Production-ready recipe for node.js cluster mode worker spawner with zero-downtime reload. Engineered for resilience, zero memory leaks, and sub-millisecond execution.
Node.js Streaming CSV Parser with Backpressure Throttle
Production-ready recipe for node.js streaming csv parser with backpressure throttle. Engineered for resilience, zero memory leaks, and sub-millisecond execution.