Be Graceful My Friend

Sweelam
3 min readMar 23, 2021

One of the key points of making your software reliable is to make it graceful to shutdown signals, but What is Graceful Shutdown? suppose you have an application runs on some application server, this service could be handling REST or SOAP, and your application for some reason needs to be restarted or stopped!

Should you close the server immediately? of course, it depends on the business type of that application, but if we ask Logic (assume he was a human) he will say “Sorry I can’t do that now, I still have some work to finish”; This is a typical example of Graceful Shutdown, your server shouldn’t accept new requests, but he should finish what he has on hand before closing the connection.

Let’s see a quick example of that in Java using Spring boot which is a great framework heavily used today, and provides almost all types of technical requirements with just a few configurations. To make it simple we will not configure the full project and instead share the code in just only one class.

The code simulates a rest endpoint which makes a delay of 10 seconds, and we are going to use this delay to stop the server manually and see the result, so let’s try the first attempt and see. the server will start, and we will send a request to that API, and immediately stop the server before the delay time finish, you will notice, the server will not reply and close the connection immediately.

If you have important services which are running in the backend, this will make a problem for you, and you may need to handle that using fault tolerance scenario like rollback script or something similar to recover the state. But if you made your system graceful, you will avoid such kinds of issues, so let us see how we can achieve that.

First, let’s configure that in the application config file which is application.properties in spring boot with the following property.

server.shutdown=graceful

Then let’s try the same scenario and see if the server can reply or not!

The application could handle that, and it is clear in the last 3 lines that the application starts the graceful period and waits till finishing the work he has before closing the connection.

This was a quick example to understand what is Graceful shutdown and how to implement it, so be smart and avoid recovering state for what you lost by the sudden shutdown, and adapt your system to be graceful my friend.

--

--

Sweelam

Software Engineer and Software Architecture Fan