In this lesson, you will learn how to gracefully shut down your Node.js server by stopping new traffic while allowing existing requests to complete safely.
Why We Need "Draining"
When you restart or deploy a new version of your server, simply killing the process can be disruptive. If a client is in the middle of a request, an abrupt stop results in an "ECONNRESET" error or a dropped connection. To prevent this, we implement a graceful drain interval. This is the period between when your server stops listening for new incoming connections and when it actually exits the process.
How it Works
When a shutdown signal (like SIGTERM) is received, your server performs two steps:
- Stop accepting new connections: The server stops the listener so no new requests can enter.
- Close remaining connections: The server waits for active requests to finish their work before closing the process.
By implementing a drain interval, you give the system a "buffer" to wrap up current business logic, write data to databases, or finalize stream processing without leaving the user hanging.
Implementation Pattern
In Node.js, we use the server.close() method to stop the server from accepting new traffic, and we can provide a callback to handle the final cleanup once existing connections are finished.
process.on('SIGTERM', () => {
console.log('Shutdown signal received: Starting graceful drain.');
// Stop accepting new requests
server.close((err) => {
if (err) {
console.error('Error during shutdown:', err);
process.exit(1);
}
console.log('All requests finished. Exiting process.');
process.exit(0);
});
});
In a production environment, you might also add a "timeout" mechanism. If the requests take too long to complete, you force the exit after a specific interval (e.g., 30 seconds) to ensure your deployment process isn't hung indefinitely by a stalled or zombie request. This balance ensures your infrastructure remains reliable during deployments while maintaining high availability for your users.
Key Takeaway: A graceful drain interval ensures zero-downtime deployments by allowing existing requests to finish processing after the server stops accepting new traffic.