What sequence of actions is necessary to properly stop an application without data loss or crashes?
sobes.tech AI
Answer from AI
To properly stop a Go application without data loss and crashes, the following steps are usually performed:
-
Handling OS signals — catch termination signals (
SIGINT,SIGTERM) using a channel andsignal.Notify. -
Initiate graceful shutdown — start a smooth termination process that stops accepting new requests and allows current ones to finish.
-
Cancel the context — use
context.Contextwith cancellation to signal all goroutines to stop. -
Close resources — close open database connections, files, network connections.
-
Wait for goroutines to finish — use
sync.WaitGroupor other mechanisms to wait until all operations are complete.
Example of handling signals and graceful shutdown:
import (
"context"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
// Start application work
wg.Add(1)
go func() {
defer wg.Done()
runApp(ctx) // main logic function
}()
// Handle signals
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
<-sigs // wait for signal
cancel() // cancel context, signaling goroutines
// Wait for completion
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// all finished
case <-time.After(10 * time.Second):
// timeout
}
}
This approach helps avoid data loss and improper shutdown.