Graceful shutdown on SIGTERM?

Can I get a code review on this? Am I generally doing the right thing?

Thanks!

3 Likes

Hi @cjbottaro!

What an application should do on shutdown is actually to shut down its supervision tree correctly. By default, this is largely done for you: all children are shutdown in the opposite order they started. But if you need to guarantee a worker/server does some clean up on shutdown, you typically call Process.flag(:trap_exit, true) on init and then implement the terminate callback.

The reason why this is preferred is because SIGTERM is just one of many ways to shutdown a system. For example, an app running releases will be terminated with System.stop, which won’t invoke your code. Also, the system using your application may change how signals work altogether. Therefore your best guarantee is to rely on OTP principles.

16 Likes

Ahh, so I should have my stage trap exits, and then have my supervisor start them with shutdown: 25_000, to accomplish the goal of “consumer stages have 25 seconds to finish handling the current event before being brutally killed and program stops”?

That is way easier than what I was trying to do, I’m super glad I asked… :+1:

Also, how do I initiate shutdown from within the application? Is it :init.stop()? Use case is that I have a heartbeat process that pings the server I’m fetching events from. The server can respond to a ping with a “shutdown now please” message.

Thanks a ton!

2 Likes

This will safely shut down the system properly instead of hard killing it yes.

4 Likes

You can use System.stop too, which is a wrapper to :init.stop. You can also send a SIGTERM, which is translated to a :init.stop by default.

3 Likes