0Pricing
Go Academy · Lesson

Graceful Shutdown

Stop workers cleanly.

Graceful Shutdown is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Graceful Shutdown

Long-running goroutines must be told when to stop. Graceful shutdown lets workers finish current work, release resources, and exit without leaking or losing data.

  • No goroutine leaks
  • No half-finished writes
  • Clean process exit

The done Channel Pattern

A classic approach is a done channel. Closing it broadcasts a stop signal to all goroutines listening on it, because a closed channel returns immediately on receive.

done := make(chan struct{})
// ... later
close(done)

select for Stop Signals

A worker uses select to either process a job or notice the done channel. When done closes, the case fires and the worker returns.

for {
    select {
    case <-done:
        return
    case j := <-jobs:
        process(j)
    }
}

context.Context

The idiomatic modern tool is context. context.WithCancel gives you a context and a cancel function. Calling cancel closes the contexts Done channel.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

Listening on ctx.Done()

Workers select on ctx.Done(). When cancel is called or a deadline passes, the channel closes and the worker exits.

select {
case <-ctx.Done():
    return ctx.Err()
case j := <-jobs:
    process(j)
}

Waiting for Workers

Signaling stop is not enough; you must wait for workers to actually finish. A sync.WaitGroup tracks them so main can block until the count reaches zero.

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    runWorker(ctx)
}()
// ... later
cancel()
wg.Wait()

Timeouts with context

context.WithTimeout cancels automatically after a duration. This bounds how long shutdown can take before you force exit.

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

A Complete Graceful Shutdown

This program runs two workers, cancels the context, and waits for both to exit cleanly before printing done.

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func worker(ctx context.Context, id int, wg *sync.WaitGroup) {
    defer wg.Done()
    for {
        select {
        case <-ctx.Done():
            fmt.Printf("worker %d stopping\n", id)
            return
        case <-time.After(50 * time.Millisecond):
        }
    }
}

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    var wg sync.WaitGroup
    for i := 1; i <= 2; i++ {
        wg.Add(1)
        go worker(ctx, i, &wg)
    }
    time.Sleep(120 * time.Millisecond)
    cancel()
    wg.Wait()
    fmt.Println("all workers stopped")
}

Draining In-Flight Work

On shutdown you often want workers to finish what they already started. Read remaining jobs in a final loop, or stop accepting new jobs while letting current ones complete.

Catching OS Signals

In real servers, signal.NotifyContext ties cancellation to SIGINT and SIGTERM. Pressing Ctrl+C then triggers the same graceful path as a manual cancel.

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()

Never Forget cancel()

Always defer cancel() even when using WithTimeout. Failing to call cancel leaks the contexts internal goroutine and timer until the deadline fires.

Quick Check

Test your shutdown knowledge.

Recap

You learned graceful shutdown:

  • Use context.WithCancel or a done channel to signal stop
  • Workers select on ctx.Done()
  • WaitGroup ensures all workers actually exit
  • Tie cancellation to OS signals for real servers
  • Always defer cancel()

Frequently asked questions

Is the “Graceful Shutdown” lesson free?

Yes — the full text of “Graceful Shutdown” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Graceful Shutdown”?

Stop workers cleanly. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Graceful Shutdown” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Worker Pool Pattern
  2. Fan-Out Fan-In
  3. Pipeline Stages
  4. Graceful Shutdown
← Back to Go Academy