DEV Community

Alex Yaroslavsky
Alex Yaroslavsky

Posted on

Spring Boot and Graceful Service Shutdown

Imagine your service running in Kubernetes, having the time of its life, and then suddenly you push a new version through the pipeline. Before starting the new version, Kubernetes needs to stop the old one. It first asks your service nicely to exit (SIGTERM), if your service doesn't respond to that it will be violently killed (SIGKILL) after several seconds. So if you want to close various resources correctly and exit gracefully, there are some steps you must take.

Below is an example of a generic skeleton for a Spring Boot Service that wants to handle shutdowns gracefully.

The main idea:

  • Start a separate thread with main application logic
  • Wait for application closing event (called upon SIGTERM)
  • Interrupt the main application logic thread and exit
  • PROFIT;

P.S. Don't forget to eat destroy your Beans, for Beans that implement the AutoClosable interface this is extremely simple:
@Bean(destroyMethod = "close")

Top comments (0)