Sobes.tech
Middle — Middle+

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:

  1. Handling OS signals — catch termination signals (SIGINT, SIGTERM) using a channel and signal.Notify.

  2. Initiate graceful shutdown — start a smooth termination process that stops accepting new requests and allows current ones to finish.

  3. Cancel the context — use context.Context with cancellation to signal all goroutines to stop.

  4. Close resources — close open database connections, files, network connections.

  5. Wait for goroutines to finish — use sync.WaitGroup or 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.

What sequence of actions is necessary to properly… - sobes.tech