What it is
A chat application delivers messages between users in real time, in one-to-one and group conversations, keeps history on every device, and reaches users who are offline. WhatsApp, Messenger, Slack and Discord follow the same broad shape: long-lived connections at the edge, a messaging core that stores and orders messages, and a fan-out path to recipients.
Why it exists
HTTP request/response cannot push a message to a phone at the moment it is sent. Polling wastes battery and adds delay. Chat therefore needs servers that hold millions of open connections, a way to find the right connection for a recipient, durable storage so nothing is lost when a recipient is offline, and an order that every participant agrees on.
How it works
Requirements. Functional: send and receive messages in one-to-one and group chats, history, delivery and read receipts, offline delivery, multiple devices per user. Non-functional: delivery to online users well under a second, no lost messages, consistent order within a conversation, and availability while individual servers fail.
Estimates (illustrative). 50 million daily users sending 40 messages a day is 2 billion messages a day, about 23 000 per second on average and two to three times that at peak. If 10 million users are connected at once, the gateway tier holds 10 million connections; how many fit on one machine depends on memory per connection and message rate, so it is measured, not assumed. At 200 bytes per message, history grows by roughly 400 GB a day before replication.
Gateways. Each client opens a WebSocket (or MQTT, or a long-polling fallback) through a layer-4 balancer to a gateway and keeps it open, with heartbeats to detect dead connections. On connect, the gateway authenticates the client and writes user/device → gateway into a presence store (often an in-memory store with TTLs refreshed by heartbeats).
Send path. The gateway forwards a message to the chat service, which assigns the next sequence number for the conversation, writes it to the message store (partitioned by conversation id, so one conversation's messages live together and have one writer) and acknowledges the sender.
Fan-out. The chat service looks up the recipients' gateways in presence and publishes the message to each gateway's channel in a pub/sub system. Gateways push it down the sockets; clients acknowledge, which produces the "delivered" receipt. For a group, the message is stored once and published once per gateway holding members.
Offline delivery. If a recipient has no live connection, the chat service sends a push notification through the platform services (APNs, FCM). When the app connects, it asks for all messages after the last sequence number it holds in each conversation.
Ordering. Within a conversation, the sequence number is the order. Clients render by sequence number, buffer messages that arrive early and fetch gaps. There is no global order across conversations.
Failures. When a gateway dies, its clients reconnect to others. Clients use exponential backoff with random jitter so they do not return at once; the tier keeps enough headroom (N+1) to absorb one gateway's connections; planned shutdowns drain connections gradually.
When to use it
Any product with real-time conversations: messaging apps, team chat, customer support chat, in-game chat, comments that update live. The same gateway + presence + pub/sub shape also serves live notifications, collaborative cursors and dashboards.
When not to
- Low-volume notifications that can wait seconds: server-sent events or plain polling are simpler than WebSockets.
- Broadcast to millions with no replies (live sports scores): a pub/sub or streaming CDN product fits better than per-user conversations.
- If a hosted chat or real-time service meets your requirements, running your own gateway fleet is significant operational work.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Fan-out on write (push to each member) | Low read latency, simple clients | Huge work for very large groups and channels |
| Fan-out on read for large channels | Cheap writes | Clients fetch on open; more read load |
| Strong per-conversation ordering (single writer) | Everyone sees the same order | A hot conversation is limited by one partition |
| End-to-end encryption | Server cannot read messages | Fan-out per device on the client, no server-side search, harder multi-device sync |
| Presence for everyone | Rich "online" indicators | Heavy write and fan-out traffic; usually throttled or limited to contacts |
Alternatives
- Server-sent events plus HTTP posts for one-directional streams with occasional sends.
- MQTT over persistent connections for mobile and IoT, with broker-managed subscriptions.
- Hosted real-time platforms that provide gateways, presence and pub/sub as a service.
Failure modes
- Gateway crash and reconnect storm: all its clients return at once and can overload the survivors and the auth service.
- Stale presence: a dead connection still listed, so messages are published to a gateway that cannot deliver; heartbeats and TTLs bound this, sync on reconnect repairs it.
- Lost acknowledgement: the client resends; the server must deduplicate by a client message id.
- Hot conversation or celebrity channel: one partition and one fan-out dominate; switch large channels to fan-out on read.
- Uneven connection balance: long-lived connections do not move when a new gateway joins; recycle connections gradually.
In production
Track connected clients per gateway, connection churn, message end-to-end latency (send to deliver), undelivered message age, push success rate and reconnect rate. Use client message ids for idempotent sends. Drain gateways before deploys by asking clients to reconnect over minutes, not seconds. Cap reconnect backoff and add jitter in every client release, because you cannot fix old clients later. Keep gateways thin so they can be restarted often.
Common misconceptions
- "WebSockets make the backend stateless." The gateway tier is stateful by nature; isolate that state there.
- "Push notifications deliver messages." They are hints with size limits and no guarantee; the store and sync deliver.
- "Messages arrive in order if the network is ordered." Different paths and devices reorder; sequence numbers define order.
- "A load balancer evens out connections." Only new ones; existing long-lived connections stay where they are.
Interview angle
Start with requirements and the connection model, then draw clients → L4 balancer → gateways → chat service → message store, plus presence and pub/sub. Interviewers probe: how a message finds the recipient's connection, when the sender sees a tick, what happens if the recipient is offline, how ordering works in a group, how large groups are handled, and what happens when a gateway dies. Mentioning reconnect storms and jittered backoff unprompted shows operational experience.
Model assumptions
The simulated steps are a simplified, per-request model, not a benchmark; the engine does not model long-lived connections. A message is one request: users (Poisson arrivals) → layer-4 balancer → gateway → chat service → message store (about 6 ms per write) and back. Each gateway has 16 slots and holds a slot for about 15 ms of its own work plus the wait for the chat service, about 500 messages per second per gateway. A reconnect is one request that reads missed messages from the store. The balancer health-checks every 500 ms and ejects a gateway after two failed checks. Clients retry failed sends and reconnects with full jitter. Reconnect waves are compressed to one second (storm) and five seconds (jittered). The WebSocket upgrade, presence, pub/sub fan-out, push notifications and ordering are scripted illustrations. Numbers show behaviour and orders of magnitude only.