Sub topic 9
Connection draining and graceful deploys
This chapter assumes you know what a load balancer does, how health checks work, and the difference between Layer 4 and Layer 7 balancing. You should also be comfortable with HTTP keep-alive and with sending signals to a process.
The problem: removing a backend without breaking requests
Backends leave the pool all the time. You deploy a new version, scale in, patch the operating system, or replace an instance. If you stop a backend abruptly, every request it is serving fails. Clients see connection resets, truncated responses, or 502 and 504 errors from the load balancer.
A health check does not fix this. Active checks run every few seconds and usually need several failures before a server is marked down. During that window the load balancer keeps sending new requests to a server that is already gone.
Connection draining (also called connection draining or deregistration delay, depending on the product) solves the problem in two steps:
- The load balancer stops sending new connections or requests to the backend.
- The backend keeps running until its in-flight work finishes or a timeout expires.
A graceful deploy adds a third requirement. The backend must cooperate: it must know it is being drained and must exit cleanly.
What "in-flight" means
The meaning of in-flight differs by layer, and this causes most surprises.
| Layer | Unit that is drained | What can go wrong |
|---|---|---|
| Layer 4 | TCP connections | A long-lived connection (WebSocket, gRPC stream, database session) can outlive any reasonable timeout. |
| Layer 7 | HTTP requests | A keep-alive connection may be idle between requests, so the balancer must decide whether to close it. |
At Layer 4 the load balancer sees only connections. It cannot tell whether a connection is busy or idle, so it waits for the connection to close or for the drain timeout to expire, then cuts it.
At Layer 7 the load balancer sees request boundaries. It can finish the current response, then close the keep-alive connection or route the next request on that connection elsewhere. Behavior varies by product, so check how yours treats idle keep-alive connections.
The drain sequence
The ordering matters. The backend should keep serving until the load balancer has actually stopped sending traffic.
Two timers control this process:
- Drain timeout. The longest the load balancer waits for existing connections. After it, connections are closed forcibly.
- Termination grace period. The longest the orchestrator waits after sending SIGTERM before it sends SIGKILL.
Set the grace period longer than the drain timeout plus your slowest normal request. If it is shorter, the process is killed while still serving.
Draining in NGINX and HAProxy
NGINX
Open-source NGINX has no runtime API for draining a single upstream server. The usual approach is to mark the server down in the configuration and reload.
upstream app {
least_conn;
server 10.0.0.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 down;
server 10.0.0.13:8080 backup;
}After nginx -s reload, NGINX starts new worker processes with the new configuration. The old workers stop accepting new connections and exit once their existing connections finish. A server marked down receives no new requests from the new workers, and requests already running on it complete.
A long-lived connection can keep an old worker alive for a long time. The worker_shutdown_timeout directive sets an upper limit on how long old workers may linger.
worker_shutdown_timeout 60s;The commercial NGINX Plus offers a drain parameter and an API for this, which avoids reloads. It is not available in the open-source build.
HAProxy
HAProxy supports draining at runtime through its stats socket. Enable the socket with admin level in the global section:
global
stats socket /var/run/haproxy.sock mode 660 level admin
defaults
mode http
timeout connect 5s
timeout client 30s
timeout server 30s
frontend web
bind *:80
default_backend app
backend app
balance roundrobin
option httpchk GET /healthz
http-check expect status 200
server app1 10.0.0.11:8080 check
server app2 10.0.0.12:8080 checkThen set the server state from the shell:
echo "set server app/app1 state drain" | socat stdio /var/run/haproxy.sock
echo "show servers state app" | socat stdio /var/run/haproxy.sockIn the drain state, HAProxy sends no new sessions to the server, except requests from clients whose persistence cookie or stick-table entry points to it. Health checks keep running. When you are ready, move to full maintenance mode:
echo "set server app/app1 state maint" | socat stdio /var/run/haproxy.sockTo bring the server back, use state ready.
Drain does not wait for you. HAProxy will not tell you when the last session ends, so poll the server's current session count (scur in show stat) and proceed when it reaches zero or your timeout expires.
Making the backend cooperate
The load balancer controls where new traffic goes. The backend controls how it exits. A graceful backend does the following when it receives SIGTERM:
- Starts failing its health endpoint, so the load balancer removes it even if nobody ran a drain command.
- Keeps serving requests for a short delay, because the load balancer needs time to notice.
- Stops accepting new connections.
- Finishes in-flight requests.
- Exits with status 0.
This Python example shows the pattern with only the standard library. Run it, call /healthz, then send SIGTERM and call /healthz again.
import signal
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
DRAIN_SECONDS = 5
draining = threading.Event()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
code = 503 if draining.is_set() else 200
body = b"draining\n" if draining.is_set() else b"ok\n"
else:
code, body = 200, b"hello\n"
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
class Server(ThreadingHTTPServer):
daemon_threads = False # wait for in-flight requests on close
server = Server(("0.0.0.0", 8080), Handler)
def on_sigterm(signum, frame):
draining.set() # health check now fails
# shutdown() must not run in the thread that runs serve_forever()
threading.Timer(DRAIN_SECONDS, server.shutdown).start()
signal.signal(signal.SIGTERM, on_sigterm)
try:
server.serve_forever()
finally:
server.server_close() # joins request threadsThe DRAIN_SECONDS delay covers the gap between the first failing health check and the load balancer acting on it. With a check interval of 2 seconds and a fall threshold of 3, a server needs about 6 seconds to be marked down, so 5 seconds is too short for that setup. Set the delay to at least interval × fall plus a margin.
Platform-specific behavior
Managed platforms implement the same idea with different names and defaults.
| Platform | Setting | Notes |
|---|---|---|
| AWS ALB and NLB target groups | Deregistration delay | Default 300 seconds. Targets in `draining` state get no new requests. A 300 second default makes deploys slow if requests are short, so lower it to fit your slowest request. |
| Kubernetes | `terminationGracePeriodSeconds`, `preStop` hook | Default grace period is 30 seconds. Endpoint removal and SIGTERM happen concurrently, so a short `preStop` sleep gives the proxies time to catch up. |
| HAProxy | `state drain`, `hard-stop-after` | `hard-stop-after` limits how long an old process lives after a reload. |
| NGINX open source | `down` plus reload, `worker_shutdown_timeout` | No per-server runtime drain. |
On Kubernetes, a common pattern is a preStop hook that sleeps for a few seconds, followed by the application's own SIGTERM handling. The sleep exists because the pod is removed from service endpoints at the same time the container is told to stop, and kube-proxy or ingress controllers update asynchronously.
Edge cases
- Long-lived connections. WebSockets, server-sent events and gRPC streams never finish on their own. Decide whether to close them at the timeout and rely on clients reconnecting. Clients must retry with backoff, or a deploy turns into a reconnect storm against the remaining servers.
- Idle keep-alive connections. A client may reuse a connection the backend has just closed. Set the backend keep-alive timeout longer than the load balancer's idle timeout, so the load balancer is always the side that closes first. Otherwise you see sporadic 502 errors.
- Sticky sessions. Persistence can pin clients to a draining server. HAProxy's drain state still honors persistence, so those clients keep arriving. Expect the drain to take longer, or plan for session loss at the end.
- Non-idempotent requests. A load balancer that retries a failed request on another server can duplicate a POST. Retry only idempotent requests unless the application deduplicates.
- Capacity during rolling deploys. Draining one server shrinks the pool. If you drain several at once and the rest cannot carry the load, you cause the outage yourself. Limit how many servers drain at the same time.
- Database transactions and queues. A request that finishes at the HTTP layer may leave background work behind. Drain workers separately from web servers.
Checklist for a graceful deploy
- Mark the backend as draining on the load balancer, or fail its health check.
- Wait at least the health check detection time.
- Watch active connections or in-flight requests fall toward zero.
- Send SIGTERM and let the application finish.
- Stop the process, deploy the new version and wait for it to pass health checks.
- Return it to the pool, then repeat for the next server.
Exercise
A service sits behind a load balancer with a health check interval of 3 seconds and a fall threshold of 2. The service handles requests that take up to 20 seconds. Its orchestrator sends SIGTERM and waits 30 seconds before SIGKILL. The application currently exits immediately on SIGTERM and users see errors during deploys. Describe how you would change the application's shutdown behavior, and say whether the 30 second grace period is enough.
Show answer
On SIGTERM the application should first fail its health endpoint, then keep serving for at least interval × fall plus a margin, which is 3 × 2 = 6 seconds plus a few seconds, for example 8 to 10 seconds. After that it stops accepting new connections and waits for in-flight requests, which can take up to 20 seconds, then exits with status 0. The total is roughly 10 + 20 = 30 seconds, which leaves no margin, so the 30 second grace period is too tight. Raise it to about 45 or 60 seconds, or shorten the pre-drain delay and the request time limit, so SIGKILL does not cut off the slowest requests.