<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rafał Roppel on Medium]]></title>
        <description><![CDATA[Stories by Rafał Roppel on Medium]]></description>
        <link>https://medium.com/@rafalroppel?source=rss-2850535cd231------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b-y928GF7RIDHtCR</url>
            <title>Stories by Rafał Roppel on Medium</title>
            <link>https://medium.com/@rafalroppel?source=rss-2850535cd231------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:25:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafalroppel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Graceful Shutdown in Go, Explained: Signals, Contexts, and the Correct Shutdown Sequence]]></title>
            <link>https://rafalroppel.medium.com/graceful-shutdown-in-go-explained-signals-contexts-and-the-correct-shutdown-sequence-f24fd9ef8fac?source=rss-2850535cd231------2</link>
            <guid isPermaLink="false">https://medium.com/p/f24fd9ef8fac</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Rafał Roppel]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 20:31:10 GMT</pubDate>
            <atom:updated>2025-12-20T20:31:10.597Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xha0GQd-L3deNoXjaLddkw.png" /></figure><h3>What actually happens when a service is terminated</h3><p>A production service almost never “stops” because you decided to stop it. It stops because something else made a decision:</p><ul><li>an operator deploys a new version,</li><li>a process manager restarts it,</li><li>an orchestrator evicts a pod,</li><li>a node is drained,</li><li>an auto-scaler replaces instances.</li></ul><p>In all of these cases the service is usually still doing work at the moment termination begins. Some requests are currently being processed, some connections are idle, some goroutines are blocked on I/O, and some background work may be in progress.</p><p>The crucial point is that termination is not a single event. It is a short timeline where your application is expected to respond correctly, within a fixed time budget.</p><p>That timeline is what “graceful shutdown” is about.</p><h3>Graceful shutdown vs hard stop</h3><p>A <strong>hard stop</strong> is when the process disappears immediately. The operating system tears down sockets and everything ends right there. Any in-flight requests may be cut mid-response. Any work that was “almost done” becomes “not done” from the client’s perspective.</p><p>A <strong>graceful shutdown</strong> is a controlled sequence:</p><ol><li>stop accepting new work,</li><li>let in-flight work finish (within a deadline),</li><li>cancel anything that should not outlive the process,</li><li>close resources in a deliberate order,</li><li>exit cleanly.</li></ol><p>This is not about being “nice”. It is about preventing avoidable failure modes:</p><ul><li>clients retry because they got a connection reset,</li><li>partial responses corrupt client-side expectations,</li><li>background work keeps running against resources that are already closing,</li><li>the service doesn’t terminate within the platform’s grace period and gets killed anyway.</li></ul><p>⚠️ A shutdown that <em>sometimes</em> finishes in time is not graceful. It is nondeterministic.</p><h3>Signals: the only contract you really get</h3><p>On Unix-like systems, the OS communicates termination through <strong>signals</strong>.</p><p>For a service, two signals matter the most:</p><ul><li><strong>SIGINT</strong>: interrupt (what you get from Ctrl+C in a terminal),</li><li><strong>SIGTERM</strong>: termination request (what you get from process managers, Docker, Kubernetes).</li></ul><p>There is also one signal you must respect conceptually:</p><ul><li><strong>SIGKILL</strong>: immediate kill. It cannot be caught or handled. If you receive SIGKILL, you do not get to run cleanup code.</li></ul><p>So a graceful shutdown strategy is fundamentally: <br>➡️ <strong>catch SIGINT/SIGTERM and turn them into application-level cancellation.</strong></p><h3>How to send signals locally</h3><ul><li>SIGINT: press Ctrl+C</li><li>SIGTERM:</li></ul><pre>kill -TERM &lt;pid&gt;</pre><ul><li>SIGKILL (not for graceful tests):</li></ul><pre>kill -KILL &lt;pid&gt;</pre><h3>What Go does by default (and why you need to override it)</h3><p>If you don’t implement any signal handling, Go inherits the operating system defaults:</p><ul><li>SIGINT / SIGTERM terminate the process,</li><li>no coordinated draining happens,</li><li>no deadlines are enforced by your code,</li><li>cleanup depends on luck and timing.</li></ul><p>Graceful shutdown starts when you intercept the signal and <strong>choose your own sequence</strong>.</p><p>In Go, you typically build that sequence from four primitives:</p><ul><li>os/signal to subscribe to SIGINT/SIGTERM,</li><li>context to represent cancellation and deadlines,</li><li>http.Server (not http.ListenAndServe) so you can call Shutdown,</li><li>a small control loop (usually a select) that waits for “stop requested” vs “server failed”.</li></ul><p>⚠️ A lot of examples use log.Fatal(...) around server start. log.Fatal calls os.Exit(1), which skips deferred cleanup. A shutdown story that can’t run cleanup reliably is not a shutdown story.</p><h3>The shutdown timeline in production: LB/Kubernetes and time budgets</h3><p>In a local terminal, you can stop a server whenever you want. In production, termination usually comes with a deadline.</p><p>In Kubernetes, the high-level lifecycle looks like this:</p><ul><li>the platform decides the pod should terminate,</li><li>the container receives <strong>SIGTERM</strong>,</li><li>Kubernetes waits up to terminationGracePeriodSeconds,</li><li>if the process is still alive, it is forcibly killed (SIGKILL).</li></ul><p>That means your application needs to complete its shutdown sequence <strong>within the platform’s grace period</strong>, with some margin for safety.</p><p>This is also why health endpoints exist:</p><ul><li><strong>liveness</strong> answers “should I be restarted?”,</li><li><strong>readiness</strong> answers “should I receive traffic?”.</li></ul><p>Readiness becomes part of graceful shutdown: the moment shutdown begins, you want to become <em>not ready</em> so the load balancer stops sending new traffic while you drain in-flight work.</p><p>In the final code, we will implement:</p><ul><li>a bounded shutdown timeout,</li><li>a readiness flag that flips immediately after SIGTERM,</li><li>http.Server.Shutdown(...) to drain in-flight requests,</li><li>correct handling of expected shutdown errors.</li></ul><h3>The code</h3><p>This is the complete program we’ll dissect next. It includes:</p><ul><li>graceful termination on SIGINT/SIGTERM,</li><li>bounded shutdown (Shutdown with timeout),</li><li>/livez and /readyz (readiness flips to false as soon as shutdown starts),</li></ul><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;errors&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;os&quot;<br>    &quot;os/signal&quot;<br>    &quot;sync/atomic&quot;<br>    &quot;syscall&quot;<br>    &quot;time&quot;<br>)<br><br>const (<br>    addr = &quot;:8080&quot;<br><br>    shutdownTimeout     = 30 * time.Second<br>    shutdownHardDelay   = 3 * time.Second<br>    readinessDrainDelay = 5 * time.Second<br><br>    // Only for demonstration in /work.<br>    workDuration = 8 * time.Second<br>)<br><br>func main() {<br>    // OS signals -&gt; cancellation.<br>    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)<br>    defer stop()<br><br>    var ready atomic.Bool<br>    ready.Store(true)<br><br>    mux := http.NewServeMux()<br><br>    mux.HandleFunc(&quot;/livez&quot;, func(w http.ResponseWriter, _ *http.Request) {<br>        w.WriteHeader(http.StatusOK)<br>        _, _ = w.Write([]byte(&quot;ok\n&quot;))<br>    })<br><br>    mux.HandleFunc(&quot;/readyz&quot;, func(w http.ResponseWriter, _ *http.Request) {<br>        if !ready.Load() {<br>            http.Error(w, &quot;not ready&quot;, http.StatusServiceUnavailable)<br>            return<br>        }<br>        w.WriteHeader(http.StatusOK)<br>        _, _ = w.Write([]byte(&quot;ready\n&quot;))<br>    })<br><br>    // Demonstration endpoint: cancellable &quot;work&quot; using select.<br>    // This shows how request cancellation (including shutdown) interrupts work.<br>    mux.HandleFunc(&quot;/work&quot;, func(w http.ResponseWriter, r *http.Request) {<br>        timer := time.NewTimer(workDuration)<br>        defer timer.Stop()<br><br>        select {<br>        case &lt;-r.Context().Done():<br>            // Client cancelled (e.g., closed connection) OR server is shutting down and request context got cancelled.<br>            http.Error(w, &quot;request cancelled&quot;, http.StatusRequestTimeout)<br>            return<br>        case &lt;-timer.C:<br>            w.WriteHeader(http.StatusOK)<br>            _, _ = w.Write([]byte(&quot;work done\n&quot;))<br>            return<br>        }<br>    })<br><br>    srv := &amp;http.Server{<br>        Addr:    addr,<br>        Handler: mux,<br><br>        // Good hygiene; not strictly required for shutdown itself.<br>        ReadHeaderTimeout: 5 * time.Second,<br>        IdleTimeout:       60 * time.Second,<br>    }<br><br>    // Run server and capture its termination.<br>    serverErr := make(chan error, 1)<br>    go func() {<br>        log.Printf(&quot;http: listening on %s\n&quot;, addr)<br>        serverErr &lt;- srv.ListenAndServe()<br>    }()<br><br>    // Wait for signal or unexpected server exit.<br>    select {<br>    case &lt;-ctx.Done():<br>        log.Println(&quot;shutdown: signal received&quot;)<br>    case err := &lt;-serverErr:<br>        // Server stopped on its own (e.g., bind error).<br>        if err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {<br>            log.Printf(&quot;shutdown: server error: %v\n&quot;, err)<br>        }<br>        // If server already exited, we can return (nothing to shut down).<br>        log.Println(&quot;shutdown: complete (server already stopped)&quot;)<br>        return<br>    }<br><br>    // First: stop being ready (so LB/K8S stops sending new traffic).<br>    ready.Store(false)<br><br>    // Give time for readiness check to propagate<br>    time.Sleep(readinessDrainDelay)<br>    log.Println(&quot;Shutdown: readiness check propagated, now waiting for ongoing requests to finish.&quot;)<br>    <br>    // Then: graceful drain within a time budget.<br>    shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)<br>    defer cancel()<br><br>    if err := srv.Shutdown(shutdownCtx); err != nil {<br>        log.Printf(&quot;shutdown: graceful shutdown failed: %v\n&quot;, err)<br><br>        // waiting for forced cancellation<br>        time.Sleep(shutdownHardDelay)<br><br>        // Last resort: force close open connections.<br>        // This should unblock ListenAndServe().<br>        if closeErr := srv.Close(); closeErr != nil {<br>            log.Printf(&quot;shutdown: server close failed: %v\n&quot;, closeErr)<br>        }<br>    }<br><br>    // Join: wait for the server goroutine to return, but don&#39;t wait forever.<br>    select {<br>    case err := &lt;-serverErr:<br>        // Normalize the expected error.<br>        if err != nil &amp;&amp; !errors.Is(err, http.ErrServerClosed) {<br>            log.Printf(&quot;shutdown: server returned error: %v\n&quot;, err)<br>        }<br>    case &lt;-shutdownCtx.Done():<br>        // If we end up here, something is seriously stuck (or Shutdown timeout was too aggressive).<br>        log.Printf(&quot;shutdown: timed out waiting for server to stop: %v\n&quot;, shutdownCtx.Err())<br>    }<br><br>    log.Println(&quot;shutdown: complete&quot;)<br>}</pre><h3>Code walkthrough</h3><p>Let’s walk through the final program the same way it runs: from startup, through steady state, into shutdown, and finally process exit. The goal is not to memorize a template, but to understand which piece is responsible for which guarantee.</p><h4>Startup: turning OS signals into a Go cancellation signal</h4><p>At the very top we wire OS signals into cancellation:</p><ul><li>os.Interrupt represents <strong>SIGINT</strong> (what you usually get from Ctrl+C). It lives in os because it’s intended as a portable, Go-level concept of “user requested interrupt”.</li><li>syscall.SIGTERM is the Unix termination request used by supervisors, containers and Kubernetes, so it comes from syscall.</li></ul><p>Using both keeps local and production behavior consistent.</p><p>The key choice here is <strong>signal.NotifyContext</strong> rather than a raw channel subscription.</p><p>With NotifyContext, you don’t “receive signals” in the rest of the code — you receive cancellation: &lt;-ctx.Done(). That aligns shutdown with the rest of Go: contexts and deadlines.</p><p>💡Prefer NotifyContext when your shutdown story is “cancel work and drain gracefully”. Use signal.Notify + a channel when you genuinely need to branch by signal type (e.g., SIGTERM vs SIGINT vs SIGHUP).</p><h4>Readiness: a single atomic flag is enough (and intentionally boring)</h4><p>We keep readiness as an atomic.Bool and default it to true.</p><p>This has two pragmatic benefits:</p><ol><li>it is safe to read from multiple goroutines without locks,</li><li>it is trivial to flip to false the moment shutdown begins.</li></ol><p>The /readyz handler simply returns 200 when ready, and 503 when not.</p><p>That’s the entire point: readiness should be cheap and predictable.</p><h4>Health endpoints: why /livez and /readyz are separate</h4><p>/livez answers “is the process alive and capable of answering at all?”. As long as the server runs, it returns 200.</p><p>/readyz answers “should this instance receive traffic?”. During shutdown, the correct answer becomes “no”, even though the process is still alive and draining.</p><p>This split is what lets load balancers and Kubernetes drain traffic without prematurely killing the container.</p><h4>The demonstration endpoint: why the select belongs here</h4><p>/work is intentionally demonstrational. It shows a pattern you’ll use in real systems when you have <strong>your own waiting primitive</strong> (timer, channel, worker result, retry loop) and you want it to be cancellable:</p><ul><li>“Either the work finishes, or the request is canceled.”</li></ul><p>That’s exactly what this select expresses:</p><ul><li>case &lt;-timer.C: we finished the simulated unit of work,</li><li>case &lt;-r.Context().Done(): stop early, because the request is no longer valid.</li></ul><p>A subtle point that is easy to miss: r.Context() can be canceled for multiple reasons:</p><ul><li>the client disconnected,</li><li>the client timed out and closed the connection,</li><li><em>the server initiated shutdown and canceled in-flight requests once its deadlines require it</em>.</li></ul><p>That’s why this endpoint is a clean place to teach cancellation semantics without dragging in a real upstream dependency.</p><p>❗️In most real I/O, you should not re-implement cancellation with select. Instead, pass ctx into context-aware APIs (QueryContext, Do(reqWithContext), etc.). The select pattern is for “your own waiting”, not for replacing library primitives.</p><h4>Starting the HTTP server: why ListenAndServe must run in a goroutine</h4><p>A graceful shutdown implementation requires the main goroutine to stay in control. It needs to wait for:</p><ul><li>a shutdown request (signal), or</li><li>the server failing on its own (port in use, listener error, etc.).</li></ul><p>ListenAndServe() is blocking, so we run it in a goroutine and report its return value via a channel:</p><pre>serverErr := make(chan error, 1)<br>go func() { <br>    serverErr &lt;- srv.ListenAndServe() <br>}()</pre><p>Two details matter here.</p><p><strong>First: the channel is buffered, size 1.</strong><br> This is not about performance. It is about avoiding a failure mode: if the goroutine tries to send an error while the main goroutine is not currently receiving, an unbuffered send could block and leak the goroutine right when you need it to exit cleanly. One slot is enough because we only ever send one terminal result.</p><p><strong>Second: you must treat </strong><strong>http.ErrServerClosed as expected.</strong><br> After a normal Shutdown(), ListenAndServe() returns http.ErrServerClosed. Logging it as an error makes every normal deployment look like a failure.</p><h4>The control point: the one select that orchestrates shutdown</h4><p>The program has a single “control loop” decision point:</p><ul><li>if we receive a signal: we initiate graceful shutdown,</li><li>if the server exits unexpectedly: we log and exit.</li></ul><p>That’s the minimum structure that still behaves correctly in production.</p><p>A detail worth calling out: if the server already died (e.g., bind error), there is nothing to drain. The code returns early and avoids calling Shutdown() on something that never started.</p><h4>Shutdown sequencing: why readiness flips before calling Shutdown()</h4><p>Once shutdown begins, we do <strong>one thing first</strong>:</p><pre>ready.Store(false)</pre><p>This is deliberately placed <em>before</em> srv.Shutdown().</p><p>The reasoning is operational:</p><ul><li>Shutdown() drains in-flight requests, but by itself it doesn’t stop your load balancer from trying to send new requests until the server stops accepting them.</li><li>In orchestrated environments, readiness is what removes you from rotation. The earlier you flip readiness, the less new work you receive while draining.</li></ul><p>So the intended sequence is:</p><ol><li>stop receiving new traffic at the platform layer (readiness),</li><li>stop accepting new connections at the server layer and drain (Shutdown),</li><li>close everything and exit.</li></ol><h4>Bounded drain: why shutdown must have a timeout</h4><p>Graceful shutdown is only meaningful if it is bounded.</p><p>A shutdown without a deadline is a hang that waits for the worst-behaved client or the most stuck goroutine.</p><p>So we create a shutdownCtx with a fixed timeout and use it in Shutdown().</p><p>This timeout is your application’s budget. In Kubernetes, it must fit comfortably within the platform’s grace period, with margin.</p><h4>The “last resort”: when and why to call Server.Close()</h4><p>Shutdown() is the polite attempt: stop accepting new work and wait for in-flight requests to finish.</p><p>But in production you must plan for failure modes:</p><ul><li>stuck clients,</li><li>misbehaving handlers,</li><li>forgotten background work,</li><li>long-running responses that exceed your time budget.</li></ul><p>If Shutdown() returns an error (typically timeout), calling srv.Close() is the emergency brake: it forces connections closed and unblocks the server.</p><p>This is not “anti-graceful”; it’s what prevents your process from being killed by the platform after exceeding the grace period.</p><h4>Joining the server goroutine: what it guarantees</h4><p>Finally, we “join” by waiting for the server goroutine to return:</p><ul><li>this is the clean point where we know ListenAndServe() has stopped,</li><li>and it avoids leaving goroutines behind in more complex programs.</li></ul><p>We still keep it bounded: we don’t wait forever. The join uses the same shutdownCtx deadline, so the program cannot hang at the very end.</p><h3>Small, important nuances (the ones people usually get wrong)</h3><h4>Notify vs NotifyContext</h4><ul><li>NotifyContext is the default choice for services because it integrates directly with cancellation and deadlines.</li><li>Notify is useful if you need the actual signal value, or want different behavior per signal.</li></ul><h4>Why the signal channel (when you use it) is often buffered with size 1</h4><p>When using signal.Notify(ch, ...), the runtime may attempt to deliver a signal even if your receiver is momentarily not ready. A buffer of 1 is a pragmatic guardrail: it reduces the chance of losing a signal or blocking a delivery path.</p><p>In our final code, the buffered channel is used for serverErr, for the same reason: a terminal error should never block shutdown wiring.</p><h4>Why /work uses select, but most handlers shouldn’t</h4><p>/work teaches cancellation when you control the wait primitive. Real I/O calls should be canceled by passing ctx to the library primitive, not by reinventing it around the call.</p><h3>Production edges: second SIGTERM, explicit cancel, Close() strategy, and RegisterOnShutdown</h3><p>The “final code” from the previous section is a solid baseline, but production systems tend to fail at the margins. This section covers the margin cases that repeatedly show up in real incidents and postmortems — and how to address them without turning the program into a framework.</p><h4>Double SIGTERM: polite drain first, forced stop second</h4><p>In many environments you effectively get two phases:</p><ul><li>first: “please stop” (SIGTERM) — you should drain and exit cleanly,</li><li>later: “you had your chance” (SIGKILL) — the platform kills the process.</li></ul><p>Sometimes operators recreate that pattern manually by sending SIGTERM twice. Sometimes you want it deliberately: the <strong>first signal starts graceful shutdown</strong>, the <strong>second signal forces immediate close</strong>.</p><p>If you only use signal.NotifyContext, you intentionally <em>lose</em> the identity and multiplicity of signals; you just get “cancelled”. That’s fine for most services, but if you want the “second signal escalates” behavior, a channel is the right primitive for that part.</p><p>A clean way to implement escalation without changing the rest of your flow is:</p><ul><li>keep NotifyContext as the main shutdown trigger,</li><li>add a secondary signal.Notify channel for “escalation”.</li></ul><p>Conceptually:</p><pre>sigCh := make(chan os.Signal, 2) // 2 because we care about the second signal<br>signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)<br>defer signal.Stop(sigCh)<br><br>// First signal starts graceful shutdown.<br>&lt;-sigCh<br><br>// If a second signal arrives, force close immediately.<br>go func() {<br>    &lt;-sigCh<br>    _ = srv.Close()<br>}()</pre><p>❗️If you implement “second SIGTERM escalates”, buffer the signal channel appropriately. If you only allocate room for one signal, you’ve built the mechanism and then removed its ability to observe the second event.</p><p>You do not need this in every service. It is an operational choice: add it if your environment or your team’s incident playbook benefits from a deterministic “hard stop now” path.</p><h4>Why (and when) you call stop() explicitly</h4><p>In the baseline code you defer stop() right after signal.NotifyContext(...). That’s correct and usually enough.</p><p>But there is a practical nuance: stop() does two things:</p><ol><li>it stops signal delivery to that context,</li><li>it releases internal resources associated with the notification.</li></ol><p>When shutdown begins, calling stop() early can simplify reasoning:</p><ul><li>you prevent re-entrancy and repeated signal handling work,</li><li>you make your shutdown logic a one-way door.</li></ul><p>This is especially useful if you start layering “escalation” behavior or multiple contexts.</p><p>A reasonable practice is:</p><ul><li>defer stop() for the normal path,</li><li>and also call stop() as the first step once you commit to shutdown.</li></ul><p>It is not mandatory, but it makes the shutdown path more deterministic.</p><h4>Shutdown() vs Close(): your intended contract</h4><p>These two methods serve different contracts:</p><ul><li>Shutdown(ctx) is cooperative: stop accepting new connections, drain in-flight work, respect a deadline.</li><li>Close() is forceful: close listeners and active connections immediately.</li></ul><p>The production-grade pattern is:</p><ol><li>try Shutdown() with a deadline,</li><li>if the deadline expires or Shutdown() fails, call Close() to avoid exceeding the platform grace period.</li></ol><p>This is exactly why Close() belongs in the “last resort” branch: you keep the graceful path as the default, but you guarantee termination.</p><h4>RegisterOnShutdown: the right tool for coordinated component shutdown</h4><p>http.Server.RegisterOnShutdown is often overlooked, but it solves a real coordination problem: the HTTP server is frequently the “entry point” of your process, yet it is not the only thing that must stop.</p><p>RegisterOnShutdown lets you attach hooks that run when Shutdown() begins. That makes it a good place to trigger application-level actions such as:</p><ul><li>stopping background workers from accepting new jobs,</li><li>unsubscribing from queues,</li><li>cancelling internal contexts,</li><li>beginning to close long-lived resources.</li></ul><p>Here is how it fits the “flat code” style without introducing a framework.</p><h4>A practical integration pattern</h4><p>You create a background “app context” for non-HTTP work, and a WaitGroup to join it. When shutdown begins, you cancel that context. Then, after the HTTP server drains, you wait for the background work to exit.</p><p>RegisterOnShutdown is used to <em>start</em> the background cancellation as soon as Shutdown() begins.</p><pre>appCtx, appCancel := context.WithCancel(context.Background())<br>defer appCancel()<br><br>var bgWG sync.WaitGroup<br>// Example background worker (placeholder for DB consumer, queue subscriber, etc.)<br>bgWG.Add(1)<br><br>go func() {<br>    defer bgWG.Done()<br>    &lt;-appCtx.Done()<br>    // cleanup for this worker here<br>}()<br><br>srv.RegisterOnShutdown(func() {<br>    // Trigger app-level shutdown as soon as HTTP shutdown begins.<br>    appCancel()<br>})</pre><p>Then, in your main shutdown sequence, after srv.Shutdown(...) returns (or after you call Close() as last resort), you join background work:</p><pre>done := make(chan struct{})<br>go func() {<br>    defer close(done)<br>    bgWG.Wait()<br>}()<br><br>select {<br>case &lt;-done:<br>    // background work stopped<br>case &lt;-shutdownCtx.Done():<br>    // timed out waiting for background work<br>}</pre><p>This is the important conceptual split:</p><ul><li>Shutdown() drains HTTP.</li><li>RegisterOnShutdown triggers “stop everything else”.</li><li>your main shutdown path still performs the final joining and enforces the same time budget.</li></ul><p>❗️Do not put long, blocking cleanup directly inside RegisterOnShutdown hooks. Treat the hook as a signal (“shutdown is starting”), not as the entire cleanup mechanism. Keep the time budget enforcement in one place (your main shutdown sequence).</p><h4>A subtle but important caveat</h4><p>RegisterOnShutdown hooks are called when you invoke Shutdown(). If you end up having to force termination with Close() (for example, after a timeout), you should assume the hooks may not cover every case you care about.</p><p>So the rule of thumb is:</p><ul><li>use RegisterOnShutdown to start coordination early,</li><li>but keep critical cleanup logic reachable even in the forced path (the same place you call Close()).</li></ul><h4>Where this leaves the “final code”</h4><p>With these additions, your production shutdown flow becomes a deliberate, testable sequence:</p><ul><li>first signal: mark not-ready and begin graceful drain,</li><li>RegisterOnShutdown: trigger app-level cancellation early,</li><li>after draining: join background work and close resources,</li><li>if anything exceeds the time budget: escalate with Close(),</li><li>optional: second signal escalates immediately.</li></ul><p>In the next section, we’ll apply these improvements to the final code while keeping it flat, and we’ll be explicit about ordering: what must happen before Shutdown(), what can happen inside RegisterOnShutdown, and what must happen after Shutdown() returns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f24fd9ef8fac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>