Long-Lived Connections in Production: Proxies, Limits and Deploys
Operate long-lived SSE and WebSocket connections at scale: Linux file descriptor limits, reverse proxy timeouts, draining sockets during rolling deploys, and spreading out reconnects.
Contentsand lesson path
On this page
- Why it matters
- Kernel limits and reverse proxy configuration
- Graceful socket draining and rolling deployments
- Check your understanding
- Apply it
- Review prompt
Lessons of Real-Time APIs & Webhooks
- Polling, Push or Callback? Choosing a Delivery Channel Concept · 20 min
- Streaming Responses and Server-Sent Events Worked example · 25 min
- Lab: An Authenticated WebSocket Feed Across Workers Lab · 30 min
- Webhooks Others Can Trust: Sign, Retry, Verify Worked example · 25 min
- Long-Lived Connections in Production: Proxies, Limits and Deploys Concept · 15 min
- Check: Choose and Defend a Real-Time Design Knowledge check · 8 questions
What you will learn
- Stream incremental results over server-sent events or a chunked response, including relaying an upstream stream such as LLM tokens, with heartbeats, resume via Last-Event-ID and cleanup when the client disconnects.
- Serve WebSocket connections that authenticate and check the origin at the handshake, follow a versioned message protocol, bound each connection's send queue, and fan out events across server processes through a pub/sub channel.
Prerequisites: Async I/O in Python
01. Why it matters
Standard REST APIs operate on transient connection lifecycles: an HTTP request arrives, the server queries a database, transmits a JSON payload within 50 milliseconds, and releases the TCP socket. In contrast, real-time architectures—such as Server-Sent Events (SSE) and WebSockets—maintain long-lived, persistent TCP connections that remain open for minutes, hours, or even days.
That breaks some assumptions of ordinary web operations, and three failures are common:
- Running out of file descriptors. On Linux and other Unix-like systems, every open network socket is a file descriptor, a numbered handle the process holds. A common default soft limit is 1,024 file descriptors per process (
ulimit -n). A worker near that limit, counting its other open files, cannot accept more connections:accept()fails withOSError: [Errno 24] Too many open files, new clients are refused, and the worker may also fail to open log files or database connections. - Idle timeouts in proxies and load balancers. Cloud load balancers (AWS ALB, Google Cloud Load Balancing), reverse proxies (NGINX, Envoy), and carrier NAT gateways close TCP connections that stay idle too long, often after 60 seconds (the default idle timeout of an AWS ALB and of nginx's
proxy_read_timeout), and some mobile NATs sooner. Without heartbeats, a client may not notice that its stream is dead. - The reconnect stampede after a deploy. A rolling deploy stops the old worker processes. If 50,000 connected clients are cut off at once and all reconnect at once, this thundering herd floods the ingress with TLS handshakes and the database with authentication queries, and can turn a routine deployment into an outage.
02. Kernel limits and reverse proxy configuration
Holding tens of thousands of open connections needs settings in both the Linux kernel and the proxy in front of your service:
- Raise the file descriptor limit. Configure
/etc/security/limits.confor your container systemd unit to raise the hard and softnofilelimits from 1,024 to 65,536 or higher (LimitNOFILE=65536). Ensurefs.file-maxin/etc/sysctl.confsupports system-wide socket volume. - Socket buffer memory. Linux allocates socket buffer memory on demand: the
net.ipv4.tcp_rmemandnet.ipv4.tcp_wmemvalues are limits and autotuning starting points, not memory reserved per socket, so tens of thousands of idle sockets cost little buffer memory. The cost appears with slow consumers: a socket whose client does not read keeps its send buffer full, and thousands of them add up. Cap that withtcp_wmemand, more importantly, with bounded application-level queues such as the per-connection outbox in the WebSocket lab. - Running out of ephemeral ports. Each connection a reverse proxy opens to a backend pod takes a local port from the ephemeral port range,
net.ipv4.ip_local_port_range, which is32768 60999by default on Linux; it can be widened, for example to1024 65535. If tens of thousands of connections churn quickly, sockets lingering in theTIME_WAITstate exhaust available ports.net.ipv4.tcp_tw_reuse = 1lets the kernel reuse aTIME_WAITport for a new outgoing connection when TCP timestamps show it is safe, which helps the proxy side; it does nothing for incoming connections. The usual fixes are reusing upstream connections (nginxkeepalive) and a wider port range. TCP keepalive (net.ipv4.tcp_keepalive_time = 300) is a separate setting: it detects dead peers on idle connections. - nginx settings. By default, nginx enforces
proxy_read_timeout 60s;. For WebSockets and SSE, increase this parameter to an hour (proxy_read_timeout 3600s;), disable proxy buffering (proxy_buffering off;), and forward protocol upgrade headers explicitly (Upgrade $http_upgrade; Connection "upgrade";).
# /etc/nginx/conf.d/realtime.conf
map $http_upgrade $connection_upgrade {
default upgrade;
"" close;
}
upstream realtime_backend {
server 127.0.0.1:8000;
keepalive 64; # Maintain persistent connection pool to upstreams
}
server {
listen 443 ssl;
http2 on; # nginx 1.25.1+; older versions use "listen 443 ssl http2;"
server_name api.example.com;
ssl_certificate /etc/ssl/certs/api.example.com.pem;
ssl_certificate_key /etc/ssl/private/api.example.com.key;
# 1. WebSocket endpoint routing
location /ws/ {
proxy_pass http://realtime_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 3600s; # Prevent 60s idle disconnect
proxy_send_timeout 3600s;
}
# 2. Server-Sent Events endpoint routing
location /api/v1/stream/ {
proxy_pass http://realtime_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_buffering off; # Flush SSE chunks immediately
proxy_cache off; # Never cache event streams
proxy_read_timeout 3600s;
chunked_transfer_encoding on;
}
}03. Graceful socket draining and rolling deployments
To deploy without cutting streams off abruptly or causing a reconnect storm, servers and clients have to cooperate:
- Give pods time to leave. Configure Kubernetes
terminationGracePeriodSeconds(e.g. 60 to 120 seconds). Kubernetes removes a terminating pod from Service endpoints in parallel with sendingSIGTERM, and readiness probes only run periodically, so new connections can still arrive for a few seconds after the signal. Add apreStophook (for example a 5 to 10 second sleep) so the pod leaves the load balancers before the process starts draining, and fail readiness from the moment draining begins. - Tell clients you are leaving. Instead of dropping TCP connections, the retiring worker closes them one by one, with a reason. For WebSockets, the server sends a close frame with status code 1001 (Going Away). For SSE, the server yields a clean disconnect event.
- Close sockets at a bounded rate. Rather than closing all 5,000 of its sockets the moment
SIGTERMarrives, a worker spreads the closures over a fixed window, for example 30 seconds (about 170 closures per second). That fits inside a 60-second grace period with time left for thepreStopsleep and for clients to finish, and the reconnects reach the ingress spread out instead of as one burst. - Reconnect with exponential backoff and full jitter. Clients must not reconnect on fixed, synchronised timers. If 50,000 clients all retry every 1.0 second, each wave arrives together and can overload the pods that just started. Clients must calculate reconnect delays using exponential backoff with full randomized jitter:
sleep_duration = random.uniform(0, min(max_backoff, base_delay * (2 ** attempt)))
Full jitter spreads the reconnects evenly over a window that grows with each attempt up to max_backoff (for example 30 or 60 seconds), so new replicas take the load gradually instead of all at once.
04. Check your understanding
05. Apply it
Audit your deployment infrastructure for long-lived real-time connections:
- Check system limits. Check current process file limits with
ulimit -n. Linux capabilities do not set this limit: raise it in the container runtime (docker run --ulimit nofile=65536:65536, theulimitskey in Compose, or your containerd/CRI default) or withLimitNOFILE=65536in a systemd unit, so that the process can hold at least 65,536 open files. - Set ingress timeouts. Update your NGINX or Envoy ingress annotations. Ensure
proxy_read_timeoutis set to at least 3600 seconds, and that response buffering is completely disabled for SSE routes (proxy_buffering off;). - Drain in stages. In your backend service, attach a signal handler to
SIGTERM. When received, stop accepting new connections, send WebSocket close frames with code 1001 (Going Away) spread over about 30 seconds, well inside the grace period, and allow active tasks to conclude cleanly. - Reconnect with jitter. In your frontend or client SDK, verify that connection retries implement exponential backoff with full randomized jitter (
random(0, min(cap, base * 2^attempt))). Test disconnecting your backend server during a load test and assert that reconnecting traffic does not create an instantaneous traffic spike.
You have completed the Real-Time APIs and Webhooks skill. Next, you will learn how to handle file uploads and object storage securely without filling API server disks.
06. Review prompt
Explain why long-lived TCP connections require tuning operating system file descriptor limits and socket buffer sizes. Describe the failure modes caused by default reverse proxy timeouts and buffering. Finally, explain the reconnect thundering herd and how server-side graceful draining combined with client-side full jitter keeps a deployment from turning into an outage.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.