Graceful Shutdown Handler
The Graceful Shutdown Handler ensures that your Express application terminates safely and predictably when the process receives termination signals (like SIGTERM or SIGINT).
It allows the server to:
- Stop accepting new connections.
- Complete all in-flight requests.
- Release resources (like database connections) before exiting.
Installation Guide
Install the component using the Servercn CLI:
npx servercn-cli add shutdown-handlerWhy Graceful Shutdown Matters
When an application is restarted or stopped (e.g., during a deployment or scaling event), it's important to finish current work. Without graceful shutdown:
- Active HTTP requests are abruptly terminated, leading to errors for users.
- Database connections might be left in a "hanging" state.
- Background tasks might be interrupted without saving progress.
Implementation
1. Utility Setup
The component provides a configureGracefulShutdown function that takes your HTTP server instance.
MVC Structure
src/utils/shutdown.ts
2. Usage in Server
Import and apply the shutdown handler in your main entry file (usually server.ts).
Best Practices
Release Database Connections
You should extend the server.close callback to include logic for closing your database connections.
Environment Signals
In modern cloud environments:
- SIGTERM: Sent by Kubernetes or Docker when a pod/container is being deleted.
- SIGINT: Sent when you press
Ctrl+Cin your terminal.
Both are handled by this component.
Summary
The Graceful Shutdown Handler is a critical component for production-ready applications, ensuring high availability and data integrity during process termination.