Gin in the wider system · 6 MIN READ
Surviving a rolling deploy in Gin: fail readiness, keep serving through a drain delay, then Shutdown
Implement and test a SIGTERM sequence that flips readiness to 503, keeps serving while load balancers stop routing, disables keep-alives, and shuts the http.Server down within a grace period the platform honors.
During a rolling deploy every old replica is told to stop while traffic is still arriving. Calling Shutdown the moment SIGTERM lands closes the listener before every load balancer has heard the replica is leaving, and the requests they still send meet a refused connection. The fix is an ordered sequence with one owner, and because it is about time and ordering, it should be modeled with an injected clock and tested like any other code.
gin · A MAP OF THE IDEA
- Flip readiness to 503
- Disable keep-alives
- Serve through the delay
- Shutdown, then Close
Useful when
- Rollouts complete without refused connections or cut requests.
- An injected clock makes the sequence testable in milliseconds.
Watch out
- Delay plus budget must fit inside terminationGracePeriodSeconds.
- Shutdown does not wait for hijacked connections or streams.
- A main that returns when ListenAndServe does cuts the drain short.
Implementation & operation cost: Every Pod termination takes the drain delay plus in-flight time, which lengthens each rollout; the code is one Lifecycle flag, one Drain function and a grace period to keep in sync.
The window where requests get dropped
When Kubernetes deletes a Pod, two things start in parallel: the control plane removes the Pod's endpoints from its Services, and the kubelet runs any preStop hook and then sends SIGTERM. The endpoint change then has to reach every kube-proxy, ingress controller and cloud load balancer, which takes from milliseconds to several seconds. A process that closes its listener at once refuses connections routed during that window; one that exits drops requests mid-flight; and clients holding keep-alive connections keep reusing the old Pod's sockets. Kubernetes already marks a terminating Pod's endpoints not ready, so for a plain Service the readiness flip mostly confirms what the control plane did. It matters for load balancers and ingress controllers that health-check the Pod directly, and EndpointSlices still publish the probe result as their serving condition. The drain delay is what covers propagation. The server-lifecycle lesson sets the budgets; this one orders the steps.
Model the sequence with a fake clock and a fake server
Drain depends only on interfaces: a Clock with After, and the three methods of *http.Server it calls. The model supplies a clock that moves only when told and a server that runs the Gin engine through httptest recorders and refuses requests once Shutdown has closed its listener. main narrates two runs: a slow export that finishes inside the budget, and one that does not.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
)
// Clock is the drain sequence's only source of time.
type Clock interface {
After(d time.Duration) <-chan time.Time
}
// Server is the part of *http.Server the sequence uses; *http.Server satisfies it.
type Server interface {
SetKeepAlivesEnabled(bool)
Shutdown(context.Context) error
Close() error
}
// Lifecycle owns the readiness flag; handlers read it, Drain writes it.
type Lifecycle struct{ draining atomic.Bool }
func (l *Lifecycle) Readyz(c *gin.Context) {
if l.draining.Load() {
c.String(http.StatusServiceUnavailable, "draining")
return
}
c.String(http.StatusOK, "ready")
}
// Drain runs once SIGTERM arrives: readiness, delay, graceful Shutdown, then Close.
func Drain(sigterm <-chan struct{}, lc *Lifecycle, srv Server, clock Clock, delay, budget time.Duration, step func(string)) error {
<-sigterm
lc.draining.Store(true)
srv.SetKeepAlivesEnabled(false)
wait := clock.After(delay)
step("SIGTERM: readiness 503, keep-alives off, still serving for " + delay.String())
<-wait
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
expired := clock.After(budget)
go func() {
select {
case <-expired:
cancel()
case <-ctx.Done():
}
}()
step("delay over: Shutdown closes the listener, budget " + budget.String())
if err := srv.Shutdown(ctx); err != nil {
srv.Close()
return fmt.Errorf("drain budget exceeded, connections closed: %w", err)
}
return nil
}
// fakeClock fires timers only when Advance is called.
type fakeClock struct {
mu sync.Mutex
now time.Duration
timers map[chan time.Time]time.Duration
}
func (c *fakeClock) After(d time.Duration) <-chan time.Time {
c.mu.Lock()
defer c.mu.Unlock()
ch := make(chan time.Time, 1)
c.timers[ch] = c.now + d
return ch
}
func (c *fakeClock) Elapsed() time.Duration {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *fakeClock) Advance(d time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.now += d
for ch, at := range c.timers {
if at <= c.now {
ch <- time.Time{}.Add(at)
delete(c.timers, ch)
}
}
}
// fakeServer models what http.Server does with a handler, without sockets.
type fakeServer struct {
h http.Handler
mu sync.Mutex
closed bool
noKeep atomic.Bool
inflight sync.WaitGroup
shutdown chan struct{} // closed once the listener is gone
}
func (s *fakeServer) Do(path string) (*httptest.ResponseRecorder, error) {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil, errors.New("connection refused")
}
s.inflight.Add(1)
s.mu.Unlock()
defer s.inflight.Done()
w := httptest.NewRecorder()
if s.noKeep.Load() {
w.Header().Set("Connection", "close") // net/http adds this when keep-alives are off
}
s.h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
return w, nil
}
func (s *fakeServer) SetKeepAlivesEnabled(v bool) { s.noKeep.Store(!v) }
func (s *fakeServer) Shutdown(ctx context.Context) error {
s.mu.Lock()
s.closed = true
s.mu.Unlock()
close(s.shutdown)
done := make(chan struct{})
go func() { s.inflight.Wait(); close(done) }()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *fakeServer) Close() error { return nil }
func newRouter(lc *Lifecycle, entered chan<- struct{}, release <-chan struct{}) *gin.Engine {
r := gin.New()
r.GET("/readyz", lc.Readyz)
r.GET("/orders", func(c *gin.Context) { c.String(http.StatusOK, "orders") })
r.GET("/export", func(c *gin.Context) {
entered <- struct{}{}
<-release // a slow request that is in flight when SIGTERM arrives
c.String(http.StatusOK, "export done")
})
return r
}
func run(name string, exportFinishes bool) {
fmt.Println("==", name)
lc := &Lifecycle{}
entered, release := make(chan struct{}), make(chan struct{})
srv := &fakeServer{h: newRouter(lc, entered, release), shutdown: make(chan struct{})}
clock := &fakeClock{timers: map[chan time.Time]time.Duration{}}
sigterm, steps, result := make(chan struct{}), make(chan string), make(chan error)
go func() {
result <- Drain(sigterm, lc, srv, clock, 5*time.Second, 20*time.Second, func(s string) { steps <- s })
}()
at := func(format string, args ...any) {
fmt.Printf("t+%-3s "+format+"\n", append([]any{clock.Elapsed().String()}, args...)...)
}
get := func(path string) {
w, err := srv.Do(path)
if err != nil {
at("GET %-7s %v", path, err)
return
}
conn := w.Header().Get("Connection")
if conn == "" {
conn = "keep-alive"
}
at("GET %-7s %d %s, connection %s", path, w.Code, w.Body.String(), conn)
}
get("/readyz")
exported := make(chan *httptest.ResponseRecorder)
go func() { w, _ := srv.Do("/export"); exported <- w }()
<-entered
close(sigterm)
at("%s", <-steps)
get("/readyz")
get("/orders")
clock.Advance(5 * time.Second)
at("%s", <-steps)
<-srv.shutdown
get("/orders")
if exportFinishes {
close(release)
w := <-exported
at("in-flight /export finished: %d %s", w.Code, w.Body.String())
at("Drain returned %v", <-result)
return
}
clock.Advance(20 * time.Second)
at("Drain returned %v", <-result)
close(release)
<-exported
}
func main() {
gin.SetMode(gin.TestMode)
run("export finishes inside the budget", true)
run("export ignores the budget", false)
}Drain waits for sigterm to close, stores the draining flag that Lifecycle.Readyz reads, disables keep-alives, and only then asks the clock for the delay, so the step message proves the timer exists before main advances. During the delay /readyz answers 503 while /orders is still served, with Connection: close as net/http adds when keep-alives are off. After Advance(5s), Drain registers the budget timer and calls Shutdown; the fake closes its listener, so the next request is refused, and waits for in-flight requests. In the first run the export finishes and Shutdown returns nil. In the second, Advance(20s) fires the budget, the watcher cancels the context and Drain falls back to Close. main prints every line after a channel receive, so scheduling never changes the order.
Why the order is readiness, keep-alives, delay, Shutdown
Readiness goes first because it is the only signal some balancers act on; return 503, since Kubernetes HTTP probes count every status from 200 to 399 as success, and keep liveness at 200 throughout, as the metrics-health lesson explains. The delay should exceed a direct health checker's probe period times its failure threshold plus endpoint propagation; five to ten seconds is common, and every Pod in a rollout pays it. SetKeepAlivesEnabled(false) closes idle HTTP/1.1 connections at once and makes each active one close after its current response; HTTP/2 connections get a GOAWAY when their last open stream finishes. Shutdown disables keep-alives too, so the explicit call matters only during the delay, which is the point: clients reconnect while the listener still accepts, and the balancer sends the new connections elsewhere. Shutdown closes listeners and idle connections, then waits for active ones; it does not wait for hijacked connections, and an open Server-Sent Events stream simply holds it until the budget expires, so register a RegisterOnShutdown function that tells streaming handlers to finish.
Wire the same Drain to a real signal and server
Nothing in Drain changes for production. A real clock adapts time.After, *http.Server already has SetKeepAlivesEnabled, Shutdown and Close, and the Lifecycle value is injected into the Gin handler like any other dependency, so the model's tests keep covering the code that ships. The one new obligation is in main, which must not return while the drain is still running.
type realClock struct{}
func (realClock) After(d time.Duration) <-chan time.Time { return time.After(d) }
func serve(srv *http.Server, lc *Lifecycle, delay, budget time.Duration) error {
sigterm := make(chan struct{})
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, os.Interrupt)
go func() { <-sigs; signal.Stop(sigs); close(sigterm) }()
drained := make(chan error, 1)
go func() {
drained <- Drain(sigterm, lc, srv, realClock{}, delay, budget, func(s string) { slog.Info(s) })
}()
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return err
}
// ListenAndServe returns as soon as Shutdown starts; requests are
// still in flight, so wait for Drain before main may return.
return <-drained
}Run this fragment in your own environment. signal.Stop after the first signal restores default handling, so a second Ctrl-C ends a stuck drain at once. The comment marks the classic bug: ListenAndServe returns http.ErrServerClosed the moment Shutdown begins, and a main that returns then exits with requests still running. If ListenAndServe fails for another reason, such as a port already in use, serve returns that error immediately. Do not derive request contexts from the signal, as the config-startup lesson warns.
Fit the sequence inside the Pod's grace period
The grace period countdown starts when the Pod is deleted, before any preStop hook runs, and SIGKILL arrives when it ends, whatever the process is doing. Keep the arithmetic true whenever the delay or budget changes: delay plus Shutdown budget plus the time to close pools and flush telemetry must fit inside terminationGracePeriodSeconds. A preStop sleep is the other place a delay can live, useful when you cannot change the application, but it counts against the same grace period, so never stack it on top of an in-app delay by accident. Pair the sequence with a rollout strategy that keeps capacity, such as maxUnavailable 0 with a surge, as the rollout lesson describes. To verify it in a real cluster, run steady load through kubectl rollout restart and count errors; the target is zero, and the model keeps the ordering from regressing.
# Pod template fragment: merge into a Deployment in your own cluster.
spec:
terminationGracePeriodSeconds: 35 # delay 5s + Shutdown budget 20s + margin
containers:
- name: api
image: registry.example.com/notes-api@sha256:<digest>
readinessProbe:
httpGet: {path: /readyz, port: 8080}
periodSeconds: 2
failureThreshold: 1
# Only if the app cannot delay on SIGTERM itself. Distroless images have
# no shell, so use the sleep action, not exec: ["sleep", "5"].
# lifecycle:
# preStop:
# sleep:
# seconds: 5Apply this in your own cluster, not in the app. The comment beside terminationGracePeriodSeconds is the budget to recheck on every change. A 2-second probe period with failureThreshold 1 lets anything polling /readyz see the 503 well within the 5-second delay. The commented preStop block is the alternative owner of the delay; the sleep action needs Kubernetes 1.30 or newer, where it is enabled by default, and an exec sleep would fail in an image without a shell.
TAKE THIS WITH YOU
On SIGTERM flip readiness to 503, disable keep-alives and keep serving through a drain delay, then Shutdown within a budget and Close after it; fit delay plus budget inside terminationGracePeriodSeconds and wait for the drain before main returns.
Check your understanding
On SIGTERM a Gin service calls http.Server.Shutdown at once, and during rolling deploys some clients see connection refused. Why does a short drain delay before Shutdown fix this?
Go to the source
Progress stays in this browser. No account needed.