I have a graceful shutdown script for my Express server, and I want to make sure it's solid. I'm sharing the code below, which includes several imports I'll explain.
I'm using `http` and `http-terminator` to handle server management, and I also have connections to Postgres and Redis that need to close gracefully. The script handles signals like `SIGTERM` and `SIGINT`, and aims to cleanly shut things down. I even have proper logging in place using the pino logger.
Before posting, I ran this script through several AI tools and received mixed feedback. I'd really appreciate any insights or advice from experienced Node.js developers about whether this script is good to go or if there are any potential issues I should address!
2 Answers
Looks like you’ve put a lot of thought into this script! One major concern I see is that combining graceful shutdown with `uncaughtException` isn’t safe. If an uncaught exception happens, your app is in a messed-up state. Instead of trying to gracefully shut down, it’s better to just terminate everything right away.
Also, for your database and Redis shutdowns, you might not need to do that manually - they usually handle it well on their end. And just a heads up, check if you really need `logger.flush()`, since that's usually only for certain setups. Overall, it's crucial to make sure your app isn't trying to run with an undefined state after an error!
Absolutely! You should do synchronous cleanup, but skip calling `gracefulShutdown()` there. Instead, just exit the process. You want it to stop immediately on uncaught exceptions.
Great job on the script, but I'd recommend not waiting for async functions inside your `uncaughtException` and `unhandledRejection` handlers. If an unhandled failure occurs, try not to keep the process going—just let it exit. This prevents memory leaks and other issues. It's about keeping things clean and avoiding complications after serious errors.

Thanks for your feedback! Could you clarify what to do instead of attaching a shutdown to `uncaughtException`? Should I just remove that section completely?