Course contents

17. Real-World System Design Lesson 9 of 20

Chat Application

Design a chat system: stateful WebSocket gateways, presence, store-then-ack, pub/sub fan-out, push for offline users, per-conversation order, reconnect storms.

25 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Clients keep a WebSocket to a gateway; a presence map says which gateway holds whom.
  • A message is acknowledged after it is stored with the next sequence number of its conversation.
  • The chat service publishes to the gateways that hold recipients; pub/sub decouples the two tiers.
  • Offline users get a push hint and sync everything after their last sequence number.
  • Order is per conversation, assigned by one writer and rendered by sequence, not arrival.
  • A gateway crash brings all its clients back at once; jitter and N+1 capacity absorb it.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Requirements, and a connection that stays open

    Requirements: one-to-one and group chats, delivery to online users in well under a second, offline users get a push notification and the messages later, history on every device, and messages in the same order for everyone in a conversation. Illustrative estimate: 50 million daily users sending 40 messages a day is 2 billion messages, about 23 000 per second on average, with perhaps 10 million connections open at once.

    Servers cannot call phones, so each client opens a long-lived WebSocket to a gateway and keeps it. Alice lands on Gateway 1, Bob on Gateway 3. Each gateway records who it holds in a presence map. That is state: Bob can only be reached through Gateway 3. Scripted illustration.

    Scene: Alice and Bob each open a WebSocket through the load balancer: Alice to Gateway 1, Bob to Gateway 3. Each gateway registers its user in the presence map. Scripted illustration.

    Key idea: Chat gateways are stateful: they hold the open connections, and a presence map says which gateway holds whom.

  2. 2. Persist first, then acknowledge

    Now many users send, about 150 messages per second in this scaled-down run. A message arrives over the sender’s socket at a gateway, which forwards it to the chat service. The chat service gives it the next sequence number in its conversation, appends it to the message store (partitioned by conversation id), and only then acknowledges: the sender’s single tick means “stored”, not “delivered”.

    The three gateways share the load and are lightly busy; every message is stored and acknowledged. Gateways stay thin: they hold sockets and relay, while logic lives in the chat service. This step is simulated.

    Scene: Users send about 150 messages per second through the load balancer and three gateways to the chat service, which stores each one in the message store and acknowledges it. No errors; gateways are lightly loaded.

    Key idea: Acknowledge a message only after it is durably stored, with a per-conversation sequence number.

  3. 3. Deliver through pub/sub to the right gateway

    Follow one message. Alice sends it over her socket; the chat service stores it and acknowledges Alice. Then it looks up Bob in presence (Gateway 3) and publishes the message on Gateway 3’s channel in a pub/sub system. Gateway 3 pushes it down Bob’s socket and Bob’s app acknowledges: now Alice sees “delivered”.

    Pub/sub decouples the chat service from the gateways: it does not need connections to hundreds of them, and a group message is published once per gateway that holds members. Background traffic is paused so the single message is easy to follow. Scripted illustration.

    Scene: Alice’s message goes to Gateway 1 and the chat service, is stored and acknowledged to Alice. The chat service finds Bob on Gateway 3 in presence, publishes to Gateway 3’s channel, and Gateway 3 delivers it to Bob, who acknowledges. Scripted illustration.

    Key idea: Store, acknowledge the sender, look up where recipients are connected, publish to those gateways.

  4. 4. Offline users: push now, sync later

    Carol’s phone is offline, so presence has no gateway for her. The message is already stored, so nothing is lost; the chat service hands a push notification to a push service, which sends it through the platform’s gateway (APNs for iOS, FCM for Android). The notification wakes the app or shows a banner; it is a hint, not the delivery.

    When Carol opens the app, it connects (to Gateway 2 this time) and asks for everything after the last sequence number it has (15). The chat service reads messages 16 and 17 from the store and sends them. The store, not the notification, is the delivery guarantee. Scripted illustration.

    Scene: Carol is offline: the stored message triggers a push notification through the push service and APNs/FCM. Later Carol connects to Gateway 2, asks for messages after sequence 15, and receives 16 and 17 from the store. Scripted illustration.

    Key idea: Offline delivery = durable store + push as a wake-up hint + sync from the last sequence number on reconnect.

  5. 5. Order by sequence, not by arrival

    Alice and Bob post in the same group at almost the same moment, through different gateways. The chat service handles each conversation in one place (one partition, one writer), so it can number them: Alice’s becomes 17, Bob’s 18.

    On the way to Carol, message 18 happens to arrive before 17. Carol’s app does not display by arrival time: it holds 18 until 17 is there and shows them in sequence order. If 17 did not arrive soon, the app would ask for the gap. Ordering is guaranteed per conversation only; a global order across all chats would need one sequencer for everything, which does not scale and nobody needs. Scripted illustration.

    Scene: Alice and Bob send to the same group via different gateways. The chat service numbers the messages 17 and 18 and stores them in order. Message 18 reaches Carol first; her app waits for 17 and displays both in sequence order. Scripted illustration.

    Key idea: One sequencer per conversation assigns the order; clients render by sequence number and fill gaps, whatever the arrival order.

  6. 6. A gateway dies and everyone reconnects at once

    Traffic is back at 150 messages per second. One second in, Gateway 2 crashes. Every client it held loses its socket and reconnects immediately: about 1 800 reconnects in one second, each one authenticating and fetching missed messages. Until health checks eject Gateway 2 (about a second), the balancer still sends a third of everything to the dead gateway.

    The two survivors can handle about 1 000 requests per second together. The reconnect wave plus normal messages exceeds that: queues fill, requests are rejected, clients retry, which adds even more load. A routine crash of one machine turns into an outage for many users: a reconnect storm.

    Scene: Gateway 2 crashes and its clients reconnect all at once. Requests to Gateway 2 fail until health checks eject it; the two remaining gateways are overloaded by the reconnect wave and reject requests.

    Key idea: Stateful connection tiers fail in bursts: when a gateway dies, all its clients come back at the same instant.

  7. 7. Reconnect with jittered backoff

    Same crash, but clients now wait a random delay before reconnecting (here spread over 5 seconds; real apps use exponential backoff with jitter, capped at tens of seconds). The same 1 800 clients come back at about 360 per second.

    The survivors absorb that comfortably: the only failures left are the requests that hit Gateway 2 before it was ejected, and their retries mostly succeed. Two more things help in production: servers can tell clients to reconnect elsewhere before a planned shutdown (draining), and capacity is planned so that the remaining gateways can take one gateway’s connections (N+1).

    Scene: Gateway 2 crashes again, but clients reconnect with random delays over five seconds. The remaining gateways stay within capacity; only requests sent to Gateway 2 before it was ejected fail, and most of those succeed on retry.

    Key idea: Jittered reconnects turn a reconnect spike into a gentle ramp; plan gateway capacity for N+1.

  8. 8. The design and its trade-offs

    Gateway 2 is replaced and back in rotation. The finished design: stateful WebSocket gateways behind a layer-4 balancer, a presence map of who is connected where, a stateless chat service that sequences and stores messages per conversation, pub/sub to the gateways that hold recipients, push notifications and sequence-based sync for offline users, and jittered reconnects.

    Trade-offs to discuss: large groups (fan-out on write to thousands of members versus members pulling recent messages), delivery and read receipts multiply message traffic, end-to-end encryption moves fan-out work to clients (one encrypted copy per device), presence is eventually consistent and expensive at scale, and balancing long-lived connections is uneven: a recovered gateway gets only new connections.

    Scene: The complete chat system: clients, load balancer, three gateways, presence, chat service, message store, pub/sub, and the push path to offline users. All gateways are healthy.

    Key idea: Durable store and per-conversation sequence for correctness; stateful gateways and pub/sub for reach; jitter and N+1 for the gateway tier’s failures.