How it works
A chat gateway is a server that holds open client sockets and forwards messages over them. After authentication, a placement service chooses a healthy gateway with capacity near the device. The device connects and registers its user and device identity. A routing directory, often an in-memory store such as Redis, maps the active device to its gateway; the gateway owns the socket while connected.
One account may have a phone and laptop on different gateways. Do not assume “user online” means there is only one destination. Gateways need limits for connection count, memory, and outbound queues. Drain them during deployment, meaning stop new placements and move existing clients in stages, so clients reconnect gradually rather than all at once.
If a gateway fails, the socket disappears. The client reconnects, authenticates again, receives a new placement, and requests messages since its last acknowledged cursor, the position of the newest message it has safely applied. The routing directory is a hint to live delivery; stored history is the recovery source. Discord’s published gateway protocol has this shape: clients send heartbeats, and after a drop they resume with the last sequence number they saw.
The danger is a reconnect storm. If a gateway with 100,000 sockets dies and every client retries at once, healthy gateways face 100,000 authentications in a moment. Retrying with jitter, a random delay spread here over 60 seconds, brings that to about 1,700 per second. This machinery earns its cost only at scale: a few thousand users can connect through a plain load balancer instead of a placement service.
A gateway holding 80,000 sockets restarts. What must happen before clients can safely resume?
Clients reconnect to healthy gateways with capacity, authenticate, re-register their routes, and fetch any messages beyond their saved cursors. Use gradual retries and gateway draining to avoid a reconnect storm.
Use this as a guide for self review; written answers are not graded.Keep in mind
- Track live routes per device, not only per account.
- Reconnect plus catch-up repairs a broken channel; a load balancer alone cannot recover messages.