← Docs

Recipe: Graceful shutdown handler design

A production pattern for draining connections, flushing state, and exiting cleanly under SIGTERM, CTRL_CLOSE_EVENT, or service stop signals.

Core contract

Every long-lived process must register a shutdown handler that:

  • Accepts a deadline context (e.g. 30s max).
  • Stops accepting new work immediately.
  • Drains in-flight requests with bounded grace.
  • Flushes buffers, closes handles, exits with code 0.

Windows service pattern

Register a console control handler via SetConsoleCtrlHandler. On CTRL_CLOSE_EVENT orCTRL_SHUTDOWN_EVENT, signal an event object that your main loop awaits. The handler must return within 5 seconds; use it only to flip an atomic flag, then let the worker thread perform the actual drain.

Circuit breaker integration

Before draining, open all circuit breakers so upstream callers receive immediate rejection rather than hanging. This prevents cascading timeouts during the shutdown window. Reject with a typed ErrShuttingDown sentinel.

Checklist

  • Signal handler flips atomic, returns fast.
  • Main loop stops accept() / poll() immediately.
  • In-flight work gets a deadline derived from the global shutdown deadline.
  • State flushed to disk / KV before final exit.
  • Exit code 0 on clean shutdown, non-zero on forced kill.
Meridian docs — production patterns for commercial Windows software.