Adding a second WebSocket server is the moment most real-time architectures break. The first server worked because it held everything in memory: a map of connection ID to socket, a broadcast method, done. The second server holds a different map, and a message published on node A silently never reaches the users connected to node B. Nothing crashes. There is no error to debug. Your chat messages just stop arriving, for some users, sometimes.
The fix is well-trodden — a pub/sub backplane between the nodes — but the details around it are where outages live: reconnect storms during deploys, idle connections quietly killed by load balancers, slow clients consuming unbounded memory, and Redis pub/sub’s fire-and-forget semantics losing messages exactly when Redis restarts. This post builds the full picture with a Go implementation and then covers every edge the naive version misses.
Why sticky sessions solve the wrong problem
Start with a clarification that saves a lot of confused architecture: a WebSocket connection is already sticky. It is one TCP connection, and TCP packets do not hop between servers. Once the handshake completes, that client talks to exactly one server until the connection closes — no load balancer will move it mid-stream. Sticky sessions only matter for the handshake, because the HTTP upgrade request must land on a server that can actually complete it, and for reconnects, where you may want a client to return to the same node for local-state reasons.
What stickiness does not do is solve fan-out. If node A receives “send this to room #devs” — from an HTTP webhook, a Kafka consumer, a cron job — it can only deliver to the subset of room members whose sockets it holds. Routing the publish request to the “right” node requires knowing where every subscriber lives, which is itself a shared-state problem. Solving “which node gets the message” by routing is O(subscribers) coordination; solving it by broadcast is one pub/sub publish. That is why the standard design broadcasts to all nodes and lets each node filter locally.
The backplane: publish once, fan out locally
Each node keeps its own local registry of connections, subscribes to the message bus once, and fans inbound messages out to its local subscribers. Publishers — HTTP handlers, workers, other services — publish to the bus instead of touching sockets directly. Redis pub/sub is the common backplane; NATS or Kafka work identically at the pattern level with different durability guarantees.
type Hub struct {
mu sync.RWMutex
conns map[string]map[*websocket.Conn]struct{} // channel -> local subscribers
rdb *redis.Client
sub *redis.PubSub
}
func (h *Hub) Subscribe(ch string, c *websocket.Conn) {
h.mu.Lock()
defer h.mu.Unlock()
if h.conns[ch] == nil {
h.conns[ch] = make(map[*websocket.Conn]struct{})
// First local interest in this channel: subscribe at Redis.
h.sub.Subscribe(context.Background(), ch)
}
h.conns[ch][c] = struct{}{}
}
func (h *Hub) Publish(ctx context.Context, ch string, payload []byte) error {
// Publishers never touch sockets — they publish to the backplane.
return h.rdb.Publish(ctx, ch, payload).Err()
}
func (h *Hub) Run(ctx context.Context) {
for {
msg, err := h.sub.ReceiveMessage(ctx)
if err != nil {
// Resubscription with backoff goes here; see reconnect section.
return
}
h.mu.RLock()
for c := range h.conns[msg.Channel] {
go h.safeWrite(c, msg.Payload)
}
h.mu.RUnlock()
}
}
Every node runs the same loop, so a message published anywhere reaches every node that has a subscriber in that channel. The node then filters: it only writes to sockets it actually holds. This is O(nodes) network traffic per publish, not O(subscribers) — which is exactly why you eventually shard channels rather than adding nodes forever, but 10-50 nodes of fan-out headroom covers most teams for years.
Redis pub/sub is fire-and-forget — plan for the gap
Redis pub/sub keeps no history. If a node’s subscription drops — Redis restarts, network blip, failover — messages published during the gap are gone, unrecoverably. For chat where clients refresh anyway, this is often acceptable. For anything where a missed message matters (order updates, collaborative editing, notifications), you need one of:
- Sequence numbers and resume. Tag each published message with a per-channel sequence number; the client sends its last-seen number on reconnect, and the server replays the gap from a bounded ring buffer or Redis Streams.
- Redis Streams instead of pub/sub.
XREADwith a consumer-managed cursor gives you persistence and replay for free, at the cost of trimming strategy management. - NATS JetStream or Kafka as the backplane, when you need consumer offsets and replay semantics across the board.
The client-side half of this contract is an explicit resubscribe on every reconnect, with the last-seen sequence number if you have one. A reconnect handler that restores subscriptions is not optional — it is the difference between a deploy blip and users silently missing everything until they reload.
Keeping connections alive: the idle-timeout gauntlet
A WebSocket with no traffic for a while will be killed by something in the path, and usually by several things in order: NAT gateways and stateful firewalls drop idle flows around 60-120 seconds, cloud load balancers have their own idle timeouts (60 seconds by default on AWS ALBs), and proxies in front of you may have their own. The fix is application-level heartbeat traffic at an interval shorter than the shortest timeout — ping every 25-30 seconds is the standard choice.
const (
pingInterval = 25 * time.Second
pongWait = 60 * time.Second
)
func (h *Hub) pumpRead(ch string, c *websocket.Conn) {
c.SetReadDeadline(time.Now().Add(pongWait))
c.SetPongHandler(func(string) error {
// Each pong extends the client's lease on the connection.
return c.SetReadDeadline(time.Now().Add(pongWait))
})
for {
_, msg, err := c.ReadMessage()
if err != nil {
h.Unsubscribe(ch, c) // also drops the Redis sub at zero interest
return
}
// ... handle inbound message
}
}
func (h *Hub) pumpWrite(ctx context.Context, c *websocket.Conn, out <-chan []byte) {
ticker := time.NewTicker(pingInterval)
defer func() { ticker.Stop(); c.Close() }()
for {
select {
case msg := <-out:
_ = c.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err := c.WriteMessage(websocket.TextMessage, msg); err != nil {
return
}
case <-ticker.C:
if err := c.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
case <-ctx.Done():
// Graceful drain: tell the client why, so it reconnects cleanly.
c.WriteMessage(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseGoingAway, "server restarting"))
return
}
}
}
The pong handler matters as much as the ping: it converts client heartbeats into a liveness signal, so dead connections (phone on wifi left a building) are reaped within one pongWait window instead of leaking forever. Set a write deadline on every outbound write — a slow client must fail the write, not freeze the pump.
Deploys without a reconnect storm
Rolling a WebSocket service means deliberately disconnecting every client on the draining pod. Done naively, all of them reconnect the instant the new pod passes its readiness probe, synchronized — a thundering herd against exactly the resource that just started cold. The standard playbook:
- Stop admitting new connections (readiness probe flips first).
- Send a close frame with code 1001 (Going Away) so clients know to reconnect — and can add jittered backoff rather than retrying instantly.
- Wait for in-flight writes to flush, then close; Kubernetes’
terminationGracePeriodSecondsis your budget. - Cap client backoff (say 1-30 s with jitter) so a long outage does not stretch reconnects into minutes.
If you deploy on Kubernetes, the hard part is not your code, it is the pod termination window: the gap between “connection closed” and “routing table updated”. Budget for it; do not pretend it is zero.
The security and memory edges
Three edges bite production systems in that order. First, cross-site WebSocket hijacking: browsers do not enforce same-origin on WebSocket handshakes the way they do on fetch, so a malicious page can open a socket to your API with the victim’s cookies. Validate the Origin header on every upgrade and treat the handshake like a state-changing POST. Second, subscribe authorization: channel names are user-controlled input, and subscribe("orders:4471") must be checked against the authenticated user’s rights at subscribe time — the handshake being authenticated proves nothing about which channels they may join. Third, backpressure: a hub that writes to sockets without bound will buffer indefinitely for slow clients. Bound each connection’s outbound channel (hundreds of messages, not thousands), and on overflow, drop the client — forcing a reconnect with a clean state is far cheaper than buffering a lagging phone until the pod OOMs.
For capacity planning, connections cost memory before they cost CPU. A gorilla/websocket connection plus its read pump, write pump, and buffers lands around 10-20 KB in Go, which puts a modest pod in the tens of thousands of connections — the wall you hit first is almost always the fan-out topology or the registry, not raw socket count.
Wrapping up
The architecture that survives contact with production: stateless nodes that keep only local connection registries, a pub/sub backplane for cross-node fan-out, heartbeats tuned under your shortest network timeout, explicit resubscribe-on-reconnect, and drain-aware deploys with jittered client backoff. Sticky sessions are a handshake detail, not an architecture; the backplane is the architecture. And when message loss during a Redis gap becomes unacceptable, swap pub/sub for Redis Streams or NATS JetStream — the hub code above barely changes, because everything else was already in place.