I'm looking for feedback on a graceful shutdown script I've written for my Express server. The script handles different signals like SIGTERM and SIGINT to gracefully manage shutdown, ensuring that active requests complete before closing down. It also includes functionality to close connections to Postgres and Redis, as well as to flush logs using the Pino logger. I've pasted the relevant server code and the functions for closing the database connections below. I've run it through various AIs but got conflicting opinions, so I'm hoping to get some insights from experienced Node.js developers. Does this script look good to you?
2 Answers
Just to add on, utilizing 'uncaughtException' and 'unhandledRejection' to perform async operations might cause errors to go unnoticed, and you really want the server to terminate properly in those scenarios. If you rely heavily on functions like gracefulShutdown, consider not using them in case of unhandled failures. It’s crucial to let the process crash visibly so that any monitoring systems can handle it appropriately.
Your script looks pretty solid overall, but I do have some concerns about handling 'uncaughtException'. According to the Node.js documentation, when this event occurs, the application's state might be undefined, so it’s not safe to continue executing your graceful shutdown process. Instead, you should just perform a synchronous cleanup and exit immediately. Regarding your database connections, it might be better to rely on the library to handle graceful shutdown, as manually doing it can sometimes cause issues you might not expect. Also, make sure you've set the Pino logger with the 'sync: false' option if you're using logger.flush().
Thanks for the pointers! I went through my logger definitions, and it turns out I'm not using 'sync: false'. Should I just remove the logger.flush call then, or is there any other option?
You could definitely remove it since it's not necessary in your case. It's usually best to keep things simpler!

You’re right! I hadn’t thought about how that could lead to issues. I’ll look into how to handle errors more effectively.