Real-Time Messaging with WebSockets: Running Connection Servers at Scale

How chat apps keep millions of persistent connections: WebSocket gateways, heartbeats, load balancing, connection registries, reconnection and kernel tuning.

Published November 27, 2026

A messaging app is only "instant" if the server can push data to the phone the moment it arrives. That requires a persistent connection per online device, which at WhatsApp scale means hundreds of millions of open sockets. This article explains how connection (gateway) servers work, how they are load balanced, how they find each other, and how clients recover from the mobile network's constant interruptions.

The concept

HTTP request-response does not fit chat: the server cannot speak until the client asks. Long polling works but wastes resources. WebSockets upgrade an HTTP connection into a full-duplex channel where either side can send frames at any time with only a few bytes of overhead. Native mobile apps sometimes use raw TCP with a custom binary protocol or MQTT instead, but the architecture is the same.

Gateway servers do as little as possible: terminate TLS, authenticate the device, keep the socket alive with heartbeats, and translate frames to internal messages. Keeping them stateless beyond the open socket is crucial. When a gateway crashes or is redeployed, its clients simply reconnect elsewhere and resynchronise from the message store, so nothing is lost.

Connection lifecycle

PhoneLoad balancerGatewayRegistryTLS + HTTP Upgradepick gatewayverify tokenSET user → gatewayping every 30-60 spush messages
Establishing and maintaining a persistent connection.

Ways to push data to clients

TechniqueProsCons
Short pollingTrivialWasteful, high latency
Long pollingWorks through any proxyRequest churn, harder ordering
Server-Sent EventsSimple server push over HTTPOne direction only
WebSocketFull duplex, low overheadNeeds sticky L4/L7 balancing
Custom TCP / MQTTSmallest overhead, tuned for mobileCustom tooling

Holding a million connections on one box

Idle connections are cheap if each one costs only a few kilobytes of memory and no thread. Event-driven runtimes (Erlang/BEAM, Go, Netty, Node.js, Rust Tokio) achieve this. The Linux kernel needs tuning: raise file descriptor limits, widen the ephemeral port range for outbound connections, and size TCP buffers conservatively because millions of default-sized buffers add up.

# /etc/sysctl.d/90-gateway.conf
fs.file-max = 4000000
fs.nr_open = 4000000
net.core.somaxconn = 65535
net.ipv4.tcp_rmem = 4096 16384 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.ipv4.ip_local_port_range = 10000 65000
# systemd unit: LimitNOFILE=4000000

Surviving flaky mobile networks

  1. Network drops (tunnel, Wi-Fi to 4G switch)
  2. Client detects missed pong or socket error
  3. Reconnect with exponential backoff + jitter
  4. Send last received message id / sync cursor
  5. Server replays everything after that cursor
Reconnection must be cheap, automatic and lossless.

Practical examples

Minimal gateway in Node.js (ws)

Authenticate on upgrade, register the session, heartbeat, forward messages.

import { WebSocketServer } from 'ws'
const wss = new WebSocketServer({ port: 8080 })
const local = new Map()                       // userId -> socket on THIS gateway

wss.on('connection', async (ws, req) => {
  const userId = await verifyToken(new URL(req.url, 'http://x').searchParams.get('t'))
  if (!userId) return ws.close(4401, 'unauthorized')
  local.set(userId, ws)
  await redis.set(`session:${userId}`, GATEWAY_ID, { EX: 90 })
  ws.isAlive = true
  ws.on('pong', () => { ws.isAlive = true; redis.expire(`session:${userId}`, 90) })
  ws.on('message', (data) => chatService.handle(userId, JSON.parse(data)))
  ws.on('close', () => { local.delete(userId); redis.del(`session:${userId}`) })
})

setInterval(() => wss.clients.forEach(ws => {
  if (!ws.isAlive) return ws.terminate()
  ws.isAlive = false; ws.ping()
}), 30_000)

Routing a message to another gateway

Gateways subscribe to their own channel; the chat service publishes to the recipient's gateway.

const gw = await redis.get(`session:${recipientId}`)
if (gw) await redis.publish(`gw:${gw}`, JSON.stringify({ to: recipientId, msg }))
else    await push.notify(recipientId, msg.preview)

Client reconnect with backoff and jitter

Prevents a thundering herd when a gateway restarts.

let attempt = 0
function connect() {
  const ws = new WebSocket(`wss://chat.example.com/ws?t=${token}&since=${lastId}`)
  ws.onopen = () => { attempt = 0 }
  ws.onclose = () => {
    const delay = Math.min(30_000, 500 * 2 ** attempt++) * (0.5 + Math.random())
    setTimeout(connect, delay)
  }
}

Common mistakes

  • Keeping undelivered messages only in gateway memory, losing them when it restarts.
  • Reconnecting all clients immediately without jitter after an outage, overloading the cluster.
  • Using L7 load balancers with short idle timeouts that silently kill quiet WebSockets.
  • Heartbeats too frequent (battery drain) or too rare (dead connections linger and NAT mappings expire).
  • Draining gateways during deploys without telling clients, causing mass simultaneous reconnects.

Key takeaways

  • Persistent connections let the server push messages instantly.
  • Gateways should be thin and stateless beyond the socket.
  • A registry maps each user to their gateway; pub/sub or RPC routes between gateways.
  • Clients reconnect with backoff and resync from a cursor, so nothing is lost.

FAQ

How do you deploy new gateway code without disconnecting everyone?

Drain gradually: stop sending new connections to old instances, ask connected clients to reconnect in small batches, then shut down.

Are WebSockets blocked by corporate firewalls?

Usually not over port 443 with TLS. Fallbacks such as long polling (as Socket.IO provides) help in restrictive networks.

Why heartbeat if TCP has keepalive?

TCP keepalive defaults are measured in hours and are invisible to the application. App-level pings detect dead connections in seconds and keep mobile NAT mappings alive.

More Architecture articles