Implement graceful shutdown in a Go service so HTTP, gRPC, and background workers drain cleanly on termination signals.
## CONTEXT My Go service needs to shut down gracefully when the platform sends a termination signal, so in-flight requests finish, background work drains, and resources close cleanly. I want a coordinated shutdown across HTTP, gRPC, and worker goroutines with a bounded timeout. Assume container orchestration in 2026. ## ROLE Act as a Go reliability engineer who has prevented dropped requests during deploys. You coordinate shutdown across all components with context, respect a deadline, and ensure no goroutine or connection leaks on exit. ## RESPONSE GUIDELINES - Listen for termination signals and trigger a coordinated shutdown. - Bound the shutdown with a deadline so it cannot hang forever. - Drain in-flight work before closing shared resources. - Close resources in the correct dependency order. ## TASK CRITERIA ### Catch Termination Signals - Listen for interrupt and termination signals. - Trigger shutdown through a cancelable context. - Stop accepting new requests immediately on signal. - Log the shutdown sequence for observability. ### Drain Servers - Call graceful stop on the HTTP server with a deadline. - Call graceful stop on the gRPC server to finish active RPCs. - Reject new connections while finishing existing ones. - Fall back to a hard stop if the deadline is exceeded. ### Stop Background Work - Cancel worker contexts so loops and pollers exit. - Wait for worker goroutines using a wait group. - Flush queued or buffered work where it is safe. - Avoid starting new background tasks during shutdown. ### Close Resources In Order - Close the database pool after handlers stop using it. - Flush logs, metrics, and trace exporters. - Release locks, file handles, and network listeners. - Ensure no goroutine references a closed resource. ### Bound And Verify - Apply an overall shutdown deadline aligned to the platform grace period. - Return a clean exit code reflecting success or timeout. - Test shutdown by signaling during active load. - Confirm no requests are dropped during a rolling deploy. ## ASK THE USER FOR - The components your service runs such as HTTP, gRPC, and workers. - Your platform termination grace period. - The resources that must close in a specific order. - Any in-flight work that must finish versus can be abandoned.
Or press ⌘C to copy