Go Academy · Lesson

Graceful Shutdown

Stop workers cleanly.

Lesson 4 of 413 steps

Graceful Shutdown is a free Go Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

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()
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Graceful Shutdown” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Graceful Shutdown”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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