Skip to content

Graceful drain on deploy — taking a backend out of the LB without dropping requests

A runbook for draining a backend behind HAProxy, Nginx, or a cloud LB before a deploy — connection-close, health-check signals, and the in-flight-request budget.

A rolling deploy on a six-node app pool was producing a 0.3% error rate that nobody could explain. The deploy script systemctl stop-ed each app, waited 5 seconds, then ran the upgrade — clean and atomic. The LB’s health check ran every 10 seconds. So between “app stopped” and “LB notices and removes the backend,” every in-flight request and every new request hit a closed socket. The fix isn’t faster health checks; it’s a proper drain — tell the LB to stop sending new traffic, wait for in-flight to complete, then stop the app. This article is the runbook.

How to verify

Confirm what your current drain mechanism actually does:

# Active session count on the backend you're about to drain
echo "show servers state app_backend" | socat stdio /run/haproxy/admin.sock \
  | awk '$4=="srv1" {print $4, $9, $13}'
# columns include current_state, current_sessions, etc.

# In-flight requests on the app itself (e.g. Node.js metric, JVM gauge)
curl -s http://app-srv1.internal:9090/metrics | grep -E 'http_requests_in_flight|http_active'

# Confirm health check interval/threshold
grep -E 'inter|fall|rise' /etc/haproxy/haproxy.cfg

# Confirm the app handles SIGTERM as a graceful stop, not a kill
systemctl cat app.service | grep -E 'KillMode|TimeoutStopSec'

If the app’s TimeoutStopSec is 5 seconds and your in-flight requests take 30 seconds (e.g. a PDF render), systemctl stop will hard-kill mid-request. Drain timing is downstream of two questions: how long does the LB take to notice, and how long does the app take to finish what’s in-flight.

What’s happening

A “drain” is the controlled state where a backend still serves in-flight requests but receives no new ones. Every real LB has this concept:

  • HAProxy: set server BACKEND/SERVER state drain via the admin socket. The backend’s current sessions stay; new sessions go to other backends.
  • Nginx (Plus): server ... drain; directive applied via API. Same semantics.
  • AWS ALB/NLB: the target enters draining state when deregistered; the LB respects the target group’s deregistration_delay.timeout_seconds.
  • Kubernetes Service: mark the pod NotReady (failing readiness probe) and the endpoints controller pulls it from the Endpoints object; kube-proxy stops routing new connections.

What none of these do automatically: wait for in-flight requests to finish before letting you stop the app. That’s your responsibility. The pattern is:

  1. Tell the LB the backend is draining (LB stops sending new requests).
  2. Wait long enough that the LB definitely noticed and all in-flight clients have drained their long-lived connections.
  3. Tell the app to gracefully stop (SIGTERM, finish current requests, exit).
  4. Wait for the app’s own grace period to expire.
  5. Hard-stop and replace.

The two waits matter for different reasons. The first wait is bounded by the LB’s polling interval and load-balancing model — for HAProxy with inter 2s, a 5-second wait is enough. The second wait is bounded by the longest legitimate in-flight request — and that one is application-specific.

The procedure

This is the order we run on a typical HAProxy + Node.js stack:

  1. Mark the backend as draining via the HAProxy admin socket. Don’t disable it — disable stops sessions immediately; drain lets them finish:

    echo "set server app_backend/srv1 state drain" \
      | socat stdio /run/haproxy/admin.sock
    
    # Confirm it took
    echo "show servers state app_backend" | socat stdio /run/haproxy/admin.sock \
      | awk '$4=="srv1" {print $4, $9}'
    # state should now be "DRAIN"

    New connections route to other backends; existing sessions stay. The HAProxy stats page also shows the backend with a yellow “DRAIN” indicator.

  2. Wait for in-flight requests to drain. Poll the LB until current sessions for that backend hit zero (or hit your tolerance threshold):

    for i in {1..60}; do
      sessions=$(echo "show servers state app_backend" \
        | socat stdio /run/haproxy/admin.sock \
        | awk '$4=="srv1" {print $9}')
      echo "in-flight: $sessions"
      [ "$sessions" -le 0 ] && break
      sleep 1
    done

    For long-lived connections (WebSocket, SSE), you may never hit zero — set a hard cap (e.g. 60 seconds for a B2B API, 5 minutes for an upload-heavy service) and force the close after.

  3. Send SIGTERM to the app and let it close gracefully. Modern Node.js with server.close() on SIGTERM finishes in-flight requests, closes keep-alive sockets, and exits. Node with no SIGTERM handler waits for the default Node grace and then hard-exits:

    sudo systemctl stop app.service
    # If you've set TimeoutStopSec=90 in the unit file, systemd waits 90s
    # before SIGKILL. Set this to longer than your longest legitimate request.

    For JVM apps, the same logic applies with kill -TERM and a shutdown hook. For Go services using net/http.Server, call srv.Shutdown(ctx) on SIGTERM.

  4. Do the upgrade. Replace the binary, run migrations on a separate connection (not from inside the app process), restart:

    sudo apt-get install --only-upgrade app
    sudo systemctl start app.service
    sleep 5  # let the app become healthy on its readiness endpoint
    curl -fsS http://app-srv1.internal:8080/healthz
  5. Bring the backend back up. Set state to ready; the LB resumes sending traffic:

    echo "set server app_backend/srv1 state ready" \
      | socat stdio /run/haproxy/admin.sock
    
    # Verify it's serving traffic
    sleep 10
    echo "show servers state app_backend" | socat stdio /run/haproxy/admin.sock \
      | awk '$4=="srv1" {print $4, $9}'
  6. Move to the next backend. A rolling deploy iterates 1-5 across each backend, never two simultaneously, with a sanity check after each.

Operational notes

  • The longest request defines the grace period. A PDF generation that takes 2 minutes means your drain budget is 2 minutes per backend. A 100ms JSON API means 5 seconds. Audit your slowest endpoint before deciding; don’t pick numbers from a runbook template.
  • WebSocket and long-poll connections never drain naturally. They live for hours. Send an application-level “reconnect please” message before drain (close code 1012 for WebSocket = “Server Restart” tells well-behaved clients to reconnect cleanly to whatever backend they land on next).
  • AWS ALB deregistration_delay.timeout_seconds defaults to 300 seconds. That’s the upper bound the LB will wait for a draining target to finish. Tune to your actual longest request — 300s is wrong for a JSON API, right for a long-lived upload service.
  • Kubernetes readiness probes are the drain. Mark the pod NotReady, wait for the readiness-probe period times two, then send SIGTERM. The preStop lifecycle hook is where you do this — sleep for the LB’s max convergence time before letting the container actually receive SIGTERM.
  • A drain that never completes is a stuck app. If sessions don’t drop after 5 minutes of drain, something is leaking connections — usually a WebSocket without a server-side close on SIGTERM, or a long-poll handler ignoring it. Force the close and investigate after.
  • Don’t drain by removing a backend from config and reloading the LB. That’s not a drain — that’s a reload, which on HAProxy spins up new workers and gracefully drains the old ones, but does so for every backend at once. Use the runtime admin socket for per-backend changes.

Stack Harbor runs production deploys with per-backend drain orchestration baked into the deploy tooling — the script that ships a release is the same script that drains, waits, upgrades, and re-enables, with sanity checks at each step. If your current deploys produce mystery error blips that show up only at the cutover moment, this is the kind of operating discipline we cover under managed operations.