Skip to content

Gracefully Shutdown your Go Application

Programming, Go3 min read

A Common Problem

Common Deployment Issue

Every time you deploy your code changes

Looks familiar? I hope it doesn’t. But if it does, you may need to diagnose and debunk your application further. The image above describes a common problem that most web server applications may have encountered. Every time we deploy new code changes, the services will be terminated first to have the new changes up & running. The problem happens when in that timeframe, the service is serving ongoing requests, and those requests will be responded with error as those requests aren’t processed if the application isn’t shutting down gracefully.

Beyond that specific problem, this article aims to extend it to broad use cases for any Go applications.

What should we do?

Before we dive into how do we address this problem, let’s define what Graceful Shutdown in a process is.

A graceful shutdown in a process is when a process is turned off by the operating system (OS) is allowed to perform its tasks of safely shutting down processes and closing connections

So it means that any cleanup task should be done before the application exits, whether it’s a server completing the on-going requests, removing temporary files, etc.

Graceful shutdown is also one of The Twelve-Factor App, which is Disposability.

To be able to achieve that, we have to listen to termination signals are sent to the application by the process manager, and act accordingly. This means that your app should not terminate itself immediately when the process manager orders it to do a graceful shutdown.

So with all information that we have right now, what we want to do is basically:

  1. Listen for the termination signal/s from the process manager like SIGTERM
  2. We block the main function until the signal is received
  3. After we received the signal, we will do clean-ups on our app and wait until those clean-up operations are done.
  4. We also need to have a timeout to ensure that the operation won’t hang up the system.

The Code

Talk is cheap. Show me the code. — Linus Torvalds

Enough theory, let’s see how the previous steps could be turned into a working sample code (gist URL).

graceful_shutdown.go
1package main
2
3// operation is a clean up function on shutting down
4type operation func(ctx context.Context) error
5
6// gracefulShutdown waits for termination syscalls and doing clean up operations after received it
7func gracefulShutdown(ctx context.Context, timeout time.Duration, ops map[string]operation) <-chan struct{} {
8 wait := make(chan struct{})
9 go func() {
10 s := make(chan os.Signal, 1)
11
12 // add any other syscalls that you want to be notified with
13 signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
14 <-s
15
16 log.Println("shutting down")
17
18 // set timeout for the ops to be done to prevent system hang
19 timeoutFunc := time.AfterFunc(timeout, func() {
20 log.Printf("timeout %d ms has been elapsed, force exit", timeout.Milliseconds())
21 os.Exit(0)
22 })
23
24 defer timeoutFunc.Stop()
25
26 var wg sync.WaitGroup
27
28 // Do the operations asynchronously to save time
29 for key, op := range ops {
30 wg.Add(1)
31 innerOp := op
32 innerKey := key
33 go func() {
34 defer wg.Done()
35
36 log.Printf("cleaning up: %s", innerKey)
37 if err := innerOp(ctx); err != nil {
38 log.Printf("%s: clean up failed: %s", innerKey, err.Error())
39 return
40 }
41
42 log.Printf("%s was shutdown gracefully", innerKey)
43 }()
44 }
45
46 wg.Wait()
47
48 close(wait)
49 }()
50
51 return wait
52}

main.go
1package main
2
3func main() {
4 // initialize some resources
5 // e.g:
6 // db, err := database.Initialize()
7 // server, err := http.Initialize()
8
9 // wait for termination signal and register database & http server clean-up operations
10 wait := gracefulShutdown(context.Background(), 2 * time.Second, map[string]operation{
11 "database": func(ctx context.Context) error {
12 return db.Shutdown()
13 },
14 "http-server": func(ctx context.Context) error {
15 return server.Shutdown()
16 },
17 // Add other cleanup operations here
18 })
19
20 <-wait
21}

The code itself is pretty straightforward. The main benefit of this approach is that it’s reusable, scalable, and easy to maintain when our application grows.

The code checks up all of the previous lists that need to be done to have a graceful shutdown application. Let’s break it down:

  • Listen for the termination signal/s from the process manager like SIGTERM
graceful_shutdown.go
1s := make(chan os.Signal, 1)
2// add any other syscalls that you want to be notified with
3signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
4<-s

It could be only one termination signal or multiple, it really depends on your app behavior, common apps may at least need to listen on SIGTERM.

  • We block the main function until the signal is received
main.go
1// wait for termination signal and register database & http server clean-up operations
2wait := gracefulShutdown(context.Background(), 2 * time.Second, map[string]operation{
3 "database": func(ctx context.Context) error {
4 return db.Shutdown()
5 },
6 "http-server": func(ctx context.Context) error {
7 return server.Shutdown()
8 },
9 // Add other cleanup operations here
10})
11
12<-wait

This code could also be extended for doing other clean-up or utility operations, e.g.: Closing Redis Connections, Send post-serving metrics, release any resource that was being used for profiling & diagnostic of the application, etc. Please refer to resource links that I put in the last section of this article for some common use cases.

  • After we received the signal, we will do clean-ups on our app and wait until those clean-up operations are done.
graceful_shutdown.go
1var wg sync.WaitGroup
2
3// Do the operations asynchronously to save time
4for key, op := range ops {
5 wg.Add(1)
6 innerOp := op
7 innerKey := key
8 go func() {
9 defer wg.Done()
10
11 log.Printf("cleaning up: %s", innerKey)
12 if err := innerOp(ctx); err != nil {
13 log.Printf("%s: clean up failed: %s", innerKey, err.Error())
14 return
15 }
16
17 log.Printf("%s was shutdown gracefully", innerKey)
18 }()
19}
20
21wg.Wait()

We want to be as fast as possible when doing cleanup operations at shutdown time, that’s why we spawn goroutine for doing every operation.

One thing to remember for this part is that we have to make sure that there’s no resource sharing between cleanup operations, otherwise it may lead to race condition due to concurrency happening here.

  • We also need to have a timeout to ensure that the operation won’t hang up the system.
graceful_shutdown.go
1// set timeout for the ops to be done to prevent system hang
2timeoutFunc := time.AfterFunc(timeout, func() {
3 log.Printf("timeout %d ms has been elapsed, force exit", timeout.Milliseconds())
4 os.Exit(0)
5})
6
7defer timeoutFunc.Stop()

So that’s graceful shutdown implementation for general Go Applications. The sample code implementation is written in Go, but the core idea can be applied to other languages as well.

Conclusion

Graceful shutdown is only one of many things that you need to implement to have a resilient & robust application.

Besides, we may also still need to figure out how to route incoming requests/new tasks to the application that has the latest version of our code when we’re having a deployment. This may need its own article that I might write in the future, so stay tuned!

These are the related external resources that you might find important to learn further on how to handle specific resource cleanup:

I hope you found this article useful. If you do, please share it with others who may need it.

Thanks for reading! Looking forward to hearing your feedback & suggestions.

© 2021 by Alfian Dhimas.
Personal Site