In this lesson, you will learn how to catch system signals to ensure your application cleans up its resources before it stops running.
When you stop a Node.js process—like pressing Ctrl+C in your terminal or when a deployment system restarts your server—Node.js sends a "signal" to your application. By default, the process kills itself immediately. If you have an active database connection or a file being written, that sudden stop could lead to data corruption or lost tasks.
To prevent this, we use Signal Handlers. These are listeners that "catch" the termination signal, allow your code to perform cleanup tasks (like closing a database pool), and then exit the process manually.
Implementing a Signal Handler
The two most common signals you will listen for are SIGINT (sent by Ctrl+C) and SIGTERM (the signal sent by most cloud platforms or Docker to shut down a container).
Here is how you configure your application to listen for these signals:
const gracefulShutdown = (signal) => {
console.log(`Received ${signal}. Starting cleanup...`);
// Perform your cleanup tasks here:
// e.g., db.close(), server.close()
console.log('Cleanup complete. Exiting.');
process.exit(0); // 0 means the process exited successfully
};
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
Why this matters
When you write an application, you are responsible for the resources you open. If your app is the 13th factor of a twelve-factor application, it must be "disposable." This means it should start up quickly and shut down gracefully. By attaching these handlers, you give your application the chance to finish its current work, save its state, or log a final message before the environment fully terminates. Without this, your application is essentially "crashing" every time it is turned off, which can cause subtle, hard-to-debug issues in your production data.
Key Takeaway: Graceful shutdown strategies use signal handlers to intercept termination requests, ensuring that your application cleans up active connections and completes pending tasks before exiting cleanly.