Part 6 of 22 · System Design

How do you build real-time chat?

WebSockets for the live connection, but the database is the source of truth: messages get a server-assigned sequence per conversation, clients acknowledge what they've seen, and reconnecting clients fetch what they missed. Polling, long polling and server-sent events still have their place.

Black and white photo of a worker in a hard hat at a telephone switchboard

The verdict, which we’ll earn by the end: treat the live connection as a fast path, never as the only path.

  • Persist first, then push. A message is stored with a per-conversation sequence number before anyone is told about it.
  • Push over WebSockets (or server-sent events for one-way updates) to clients that are connected.
  • Clients track the last sequence they’ve seen, and on reconnect ask for everything after it. That one rule handles dropped connections, app restarts and multiple devices.
  • Route messages between servers through a pub/sub layer, because the sender and receiver are usually connected to different servers.

Chat feels instant and effortless when it works, which makes it easy to forget how much is going on underneath. Then a phone drops into a tunnel, a message vanishes, another shows up twice, and two people in the same conversation see replies in a different order. That’s our case. My favourite thing about the solution is how one number, a sequence per conversation, solves ordering, gaps and reconnects at once.

Case file

The case Messages vanish, show up twice, or arrive in a different order
Suspects The transport: polling, long polling, SSE, WebSockets
Culprit Treating the live connection as the only path
The fix Persist first with a per-conversation sequence, push, fetch after N on reconnect

The first suspect: the transport #

Polling Long polling Server-sent events (SSE) WebSockets
How Ask every N seconds Request waits until there’s news, then re-asks One long HTTP response streaming events Full-duplex connection after an HTTP upgrade
Direction Client → server Client → server Server → client Both
Latency Up to N seconds Low Low Lowest
Cost Many empty requests One open request per client One open connection per client One open connection per client
Works through proxies Always Almost always Almost always (it’s HTTP); over HTTP/1.1 browsers allow only about 6 connections per site, so serve it over HTTP/2 Usually; some corporate proxies interfere
Good for Low-traffic dashboards Fallback Live status, notifications, feeds Chat, collaboration, games

It’s natural to blame the pipe first, and it does matter. For chat, use WebSockets with a fallback, or SSE for receiving plus normal HTTP POST for sending. That second option is simpler to run behind standard load balancers and works well. But here’s the twist: any of these connections can drop at any moment, so picking the best one doesn’t close the case. It’s a red herring if you stop there.

Following the message #

Let’s trail a single message from Alice to Bob and watch where the evidence points.

Sequence diagram: a-981, idempotent on client_id, show as sent, Bob is connected here, give me conv 42 after seq 1057Sequence diagram: a-981, idempotent on client_id, show as sent, Bob is connected here, give me conv 42 after seq 1057
Diagram source
sequenceDiagram
  participant A as Alice's app
  participant G1 as Gateway 1
  participant S as Chat service
  participant DB as Message store
  participant PS as Pub/sub
  participant G2 as Gateway 2
  participant B as Bob's app
  A->>G1: send {conv: 42, client_id: "a-981", text}
  G1->>S: store
  S->>DB: INSERT ... seq = next for conv 42 (idempotent on client_id)
  DB-->>S: seq 1057
  S-->>G1: ack {client_id: "a-981", seq: 1057}
  G1-->>A: ack (show as sent)
  S->>PS: publish conv 42, seq 1057
  PS->>G2: (Bob is connected here)
  G2->>B: message seq 1057
  B->>G2: read up to 1057
  Note over B,G2: Bob reconnects later: "give me conv 42 after seq 1057"
  • Gateways hold the open connections and nothing else. They scale horizontally; a load balancer spreads connections across them.
  • The chat service validates, stores and publishes. It assigns the sequence number, so every member sees messages in the same order. Giving that job to a single authority is the elegant move that makes everything downstream simple: nobody else has to agree on order.
  • Pub/sub (Redis pub/sub or streams, NATS, Kafka) carries “conversation 42 has a new message” to every gateway that has a member of conversation 42 connected.
  • The message store is append-mostly and partitioned by conversation: (conversation_id, seq) is the primary key, so loading history is a range read.

The reveal: delivery guarantees #

Now the earlier mysteries resolve one by one. A handful of small rules add up to a system you can trust.

  • No duplicates: the client generates an ID for each message it sends (client_id). If the send times out and the client retries, the server recognises the ID and returns the original sequence number. This is the idempotency pattern.
  • No gaps: clients know the last sequence they’ve seen per conversation. If a pushed message arrives with a gap (1057 after 1055), or after any reconnect, they fetch the missing range.
  • Order: the server’s per-conversation sequence is the order. Don’t use client clocks.
  • Delivered and read receipts: clients report “delivered up to N” and “read up to N” per conversation, which is far cheaper than per-message receipts.

A side case: presence (“online”, “typing…”) #

Presence looks like part of the same case, but it’s a different animal: ephemeral and high-volume. Never put it in the main database.

  • Each gateway records connected users in a fast store with a short TTL, refreshed by heartbeats.
  • “Typing” events go straight through pub/sub to the conversation’s members and are never stored.
  • Show presence only for contacts and active conversations; broadcasting every status change to every contact doesn’t scale.

The same pattern bends to fit situations with different shapes:

Situation What I’d use
1:1 and small group chat The design above; fan out to members through pub/sub
Large rooms or channels (thousands of members) Don’t push every message to every member; push “channel has new messages” and let clients fetch when they view it
Live order status, delivery tracking SSE (one-way), backed by the same “fetch since sequence N” rule
Offline mobile users Push notifications through APNs/FCM, carrying only enough to show the alert; the app fetches the messages when opened

Remember this

  • Store first, then push: the live connection is a fast path over a durable log.
  • One server-assigned sequence per conversation fixes order, gaps and reconnects.
  • A client-generated message ID makes every retry harmless.

Case closed: what I’d do by default #

  1. Store first, then push, with a server-assigned sequence per conversation.
  2. Client-generated message IDs so retries never duplicate.
  3. “Fetch after sequence N” on every reconnect: the live connection is an optimisation.
  4. Stateless gateways plus pub/sub, so any server can reach any user.
  5. Presence in a TTL store, never in the message database.

Once you see the live connection as a fast path over a durable log, real-time chat stops feeling mysterious. The reliable part is boring on purpose, so the exciting part can be fast, and I find that division of labour genuinely lovely. (For the next case, the append-only log post finds the same idea hiding under queues and databases.)

Like (sign in first) 0 likes 💬 0

Written by

Vishal Kumar

Associate Director at CapGrid, running product and engineering in a CPTO capacity. 10+ years building distributed, multi-tenant SaaS and AI platforms. AWS Certified Solutions Architect - Professional. Based in Gurugram.

Comments

No comments yet.

Sign in to comment. We'll email you a link; no password needed.