Coordinate graceful shutdown
Coordinate graceful shutdown
Graceful shutdown stops accepting new work, finishes or cancels accepted work according to policy, releases resources and waits within a deadline. A shutdown signal is not proof that work has stopped. This simulation closes ingress and waits for a final total.
package main
import ( "context" "fmt" "time")
func drain(jobs <-chan int, done chan<- int) { total := 0 for n := range jobs { total += n } done <- total}func finish(ctx context.Context, done <-chan int) (int, error) { select { case n := <-done: return n, nil case <-ctx.Done(): return 0, ctx.Err() }}func main() { jobs := make(chan int, 3) done := make(chan int, 1) go drain(jobs, done) jobs <- 2 jobs <- 3 close(jobs) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() n, err := finish(ctx, done) fmt.Println(n, err == nil)}The sole producer closes jobs; buffered work remains readable. The one-item report channel lets this worker report even if the caller times out. Real services must coordinate all producers before closure and use a fresh shutdown context rather than an already canceled request context.
Expected output:
5 trueHandle cancellation while waiting
package main
import ( "context" "errors" "fmt")
func drain(jobs <-chan int, done chan<- int) { total := 0 for n := range jobs { total += n } done <- total}func finish(ctx context.Context, done <-chan int) (int, error) { select { case n := <-done: return n, nil case <-ctx.Done(): return 0, ctx.Err() }}func main() { ctx, cancel := context.WithCancel(context.Background()) cancel() done := make(chan int) _, err := finish(ctx, done) fmt.Println(errors.Is(err, context.Canceled))}No result is ready in this fixture, so cancellation wins. If both cases are ready, either may win. A deadline bounds waiting, not necessarily worker lifetime. Production work must support cooperative stop and report unfinished work. No OS signals or HTTP servers are used here.
Expected output:
trueTry it locally
Drain an already closed empty jobs channel and report total 0 and nil error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 07: Coordinate graceful shutdown
Check the lesson objective before moving on.
What comes first in a drain policy?
Does timeout prove workers stopped?