Video in progress

During a deploy, 40,000 clients drop at once and reconnect to the new instances, and the instances fall over. How do you soften this?

This is a "thundering herd": everyone does the handshake, authentication and initial state load at the same time. The mitigation is backoff with jitter on the client, closing connections gradually on the server (graceful drain), a handshake rate limit, and making the initial load cheaper.

📖 Answer

The problem usually isn't the reconnect itself but the work after it: every client validates a token at CONNECT (a JWKS request?), restores subscriptions, and asks the database for history. 40,000 × "load history" = the database falls over, the instance slows down, the health check fails, k8s kills the pod, and everyone drops again.

What I do:

Drain on the server. Before shutting an instance down (a preStop hook or SmartLifecycle.stop), it closes connections in batches, say over 2 to 3 minutes, not all at once, with code 1001 (going away). In Kubernetes, terminationGracePeriodSeconds is set long enough for that, and maxSurge/maxUnavailable are small in a rolling update.

Jitter on the client. On receiving 1001 it doesn't reconnect immediately but waits a random 0 to 30 seconds.

Admission control. Accept up to N handshakes per second, and answer the rest with 503 + Retry-After. This doesn't lose the extra clients, it just queues them.

Cheap initial state. Not the full history for every client, only the difference after seq. Frequently requested things go in a cache.

Health check. Tie readiness to the number of connections or the inbound queue: when an instance is full, the LB sends new connections elsewhere, and liveness doesn't kill it.

You can test this before it hits prod: open 40k connections in a load test, then kill one pod. The reconnect spike and the load on the database are clearly visible on the graphs.