2 min read

Graceful shutdown of a Spring application

Graceful shutdown of a Spring application
“We shall all shutdown gracefully some day.” – Thánatos Barotis

Basically, there are two ways to turn off a computer or a piece of software.
1. Hard shutdown
2. Graceful shutdown

Hard shutdown
Hard shutdown closes all the processes immediately. While this process is considered faster than the alternative it might cause unexpected problems, data loss or even boot failure.

Graceful shutdown
A graceful shutdown gives your application a grace period to safely shut down processes and connections. During the grace period, no new requests are accepted by the server. The grace period will be respected in all cases of an application shutdown except of course a global hardware failure. This approach takes a bit more time but it helps prevent accidental data loss and other unexpected problems. Springs default grace period is 30 sec. It is important to understand that the grace period does not fully protect you from data loss or unexpected behaviors caused by unfinished processes, since processes that wont be completed during the grace period will be terminated.  

Example:
Lets say your application is up and running some user requests which involve reading and writing data to your app database. Suddenly, your app receives an unexpected termination signal (e.g SIGINT, SIGTERM, SIGQUIT,SIGKILL). With a graceful shutdown mechanism enabled, you make sure that current running processes writing data to the app database will have a grace period of timeto  finish their job before the app actually terminated.  

Enabling graceful shutdown in a Spring application  

All we have to do in order to enable graceful shutdown in our application is  to add this property to the application .properties or .yaml file.

.yaml file:

server:
  shutdown: graceful

.properties file:

server.shutdown=graceful

Terminating the application will yield

08:16:27.985 [SpringContextShutdownHook] INFO - Commencing graceful shutdown. Waiting for active requests to complete
08:16:31.996 [tomcat-shutdown] INFO  - Graceful shutdown complete

If the default 30 sec value is not enough for you application you can change it adding this property

.yaml file:

spring:
  lifecycle:
    timeout-per-shutdown-phase: "90s"

.properties file:

spring.lifecycle.timeout-per-shutdown-phase=90s

In this short article, we learned the reasons why would like to add a graceful shutdown mechanism to our application and how we enable it on a Spring application.