DevPath
Senior lesson · 16 min

Shut down a busy Go service safely

Stop accepting work, finish bounded in-flight tasks, and report leftovers.

Define the shutdown contract

A server receiving a termination signal should stop accepting new requests, give existing requests a bounded period to finish, and cancel work after that deadline. Queue workers need a similar rule for messages already leased. Decide what state is durable and safe to retry before implementing signal handling.

Coordinate components

Create a shutdown context with a deadline and call the HTTP server's graceful shutdown path. Stop producers before closing work channels, wait for workers, and do not close a channel while another goroutine can send to it. Preserve idempotency because a process can still be killed after the grace period.

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil { log.Printf("shutdown: %v", err) }

Rehearse under load

Start requests and queued jobs, signal termination, and verify that no new work begins while in-flight work either completes or becomes safely retryable. Check that health checks turn unhealthy at the right time. Record unfinished operation IDs so operators can reconcile them after restart.

Check your understanding

Why does graceful shutdown still require idempotent jobs?

Show explanation

The process can be killed after its grace period or crash mid-effect, so unfinished work may be delivered again.

You can read for free. Create an account to save your progress.

← Previous lesson: Keep a Go package contract stable

Try it at senior level

Design shutdown for an HTTP server and worker queue with a ten-second deadline. Lay out the order of admission, draining, and final reporting.

Check your work

No new work is accepted after shutdown begins; in-flight work has a bounded finish window; unfinished jobs remain retryable.

Self-guided practice. This does not record assessed mastery.

Put this lesson into practice

A related activity in this module at mid level.

Try: Fan out with a bounded worker pool

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.