To keep this article simple and short I would not be dwelling into what is graceful shutdown and why this is so important when it comes to K8s. You can read this blog on medium to understand the details.
I am going to explain about how to enable this feature specifically for spring boot applications in this article.
You need to have Sprint boot version 2.3.x for the below to work. This latest version of spring boot supports the graceful shutdown out of the box. You need literally 0 code changes to achieve this and save some embarrassment :)
Here are the 2 properties you need to define as part of your configuration.
The default value for server.shutdown is “immediate” (Not sure why). However, you can override that by defining this as part of your application configuration.
The 2nd configuration tells spring to wait for x amount of time before it tear downs all the threads and eventually your application server. The default value for this configuration is 30s which should be enough for any production application deployed in K8s.
I would recommend to have this value driven from some cloud configuration so that you have better control over this change it during runtime.
Thats it. enjoy and live stress free life :)