System Design: Chat Application

A chat app: client and server talk over WebSocket, a two-way connection that stays open (right for messages and typing indicators; SSE is one-way, polling is…

The message "Reunion meeting Saturday at 7 pm" lands in a group of five. A tick appears on the sender's phone. The three members who are online get it in an instant. Dewi, whose phone is off, gets it as soon as her phone is back on, still in order and with nothing missing. Designing a chat app like WhatsApp means designing the path of that one message: from the sender's phone, into storage, then to every recipient as fast as possible, including the ones who are offline.

A post office for one housing estate works much the same way. Every letter is first written in a ledger with a running number. Then it is carried to the houses where someone is home. An empty house gets a "parcel waiting" slip on the door, and the letter is delivered as soon as the owner gets back. Record it first, number it, deliver to whoever is in, tell whoever is out: that is the whole design.

ChitChat's requirements and estimates

In this lesson we design ChitChat, a chat app. It is a stand-alone, interview-style design, so not TicketTune.

Functional Non-functional
1-on-1 and group chat A message reaches an online recipient in under 200 ms
A message for someone offline arrives when they come online A message marked "sent" must never be lost
Sent, delivered and read status Messages in one conversation show in the same order on every phone
Online status and "last seen" Recent history opens fast

ChitChat's numbers (an example model), worked out as in the What Is System Design lesson:

What Working Result
Messages per day 10,000,000 users × 40 messages 400,000,000
Messages per second 400,000,000 ÷ 86,400 ≈ 4,630
Storage per day 400,000,000 × 200 bytes 80 GB
Storage per year 80 GB × 365 29.2 TB
Connections at peak 30% of users online at once 3,000,000
WebSocket servers 3,000,000 ÷ 50,000 connections per server 60
Presence heartbeats 3,000,000 ÷ 30 seconds 100,000 per second

The last row is the one people forget: just to keep online status fresh, the system takes 100,000 writes a second, far more than the messages themselves.

Why WebSocket

Plain HTTP can only answer: the server can't send a message to Rina's phone unless Rina asks first. There are three ways to get new messages there:

Chat needs both directions with very low latency. Take the "Siti is typing..." indicator: a small event sent many times a minute. Over WebSocket, it just goes down the connection that is already open. How WebSocket works is covered in the WebSocket lesson (Node.js track).

Because the connections stay open, a chat server is stateful: it holds thousands of open connections. In this model one server holds about 50,000, so we need 60 servers, and the sender and the recipient are often on different ones.

The journey of one message

The Reunion Committee group: Budi and Siti are connected to server ws-1; Rina, Andi and Dewi to ws-2. Dewi is offline. Budi sends "Reunion meeting Saturday at 7 pm":

Step What happens
1 ws-1 gives the message a running number, seq 1, for this conversation
2 ws-1 stores the message in the message store: 1 write
3 ws-1 sends an ack to Budi. On Budi's phone: "sent"
4 Siti on the same ws-1: sent straight down her WebSocket
5 Rina and Andi on ws-2: ws-1 publishes the message to the ws-2 channel on Redis Pub/Sub, and ws-2 sends it to them
6 Dewi is offline: the message is marked "pending" for Dewi, and a push notification goes out

So one message costs only 1 database write, 3 WebSocket sends (Siti, Rina, Andi), plus 1 push notification for Dewi. The message is stored once and then spread to many recipients. That spreading is called fan-out. Redis Pub/Sub is the Redis feature that sends a message to everyone subscribed to a channel; here every chat server subscribes to its own channel.

// ChitChat: the "Reunion Committee" group on two WebSocket servers (an example model)
const serverOf = { Budi: "ws-1", Siti: "ws-1", Rina: "ws-2", Andi: "ws-2", Dewi: "ws-2" };
const online = new Set(["Budi", "Siti", "Rina", "Andi"]); // Dewi is offline
const messages = []; // the message store, in seq order
const pending = { Dewi: [] }; // seqs that haven't reached Dewi yet

function send(text) {
  const seq = messages.length + 1; // running number per conversation
  messages.push({ seq, text }); // store first, then send
  console.log(`seq ${seq} stored, ack to Budi`);
  const perServer = {};
  for (const name of Object.keys(serverOf)) {
    if (name === "Budi") continue;
    if (!online.has(name)) {
      pending[name].push(seq);
      console.log(`${name} offline: push notification`);
    } else {
      (perServer[serverOf[name]] ??= []).push(name);
    }
  }
  for (const [server, recipients] of Object.entries(perServer)) {
    const route = server === "ws-1" ? "directly" : "via Redis Pub/Sub";
    console.log(`${server} ${route}: ${recipients.join(", ")}`);
  }
}

function connect(name) {
  online.add(name);
  console.log(`${name} online: send seq ${pending[name].join(", ") || "(none)"}`);
  pending[name] = [];
}

send("Reunion meeting Saturday at 7 pm");
connect("Dewi");

The output:

seq 1 stored, ack to Budi
Dewi offline: push notification
ws-1 directly: Siti
ws-2 via Redis Pub/Sub: Rina, Andi
Dewi online: send seq 1

Message order

One TCP connection keeps its order, but a message travels several paths: Budi may send from his phone and his laptop, two messages may be handled by two different processes, and a publish between servers may be retried. So two messages sent back to back can arrive reversed on Rina's phone: seq 2 first, then seq 1.

The fix: the phone shows messages by seq, not by arrival time. Don't use the sender's phone clock, because no two devices agree on the time (the Why Distributed Systems Are Hard lesson). Seq also exposes gaps: if a phone has seq 5 and then receives seq 7, it knows seq 6 hasn't arrived and asks the server for it.

Offline, push notifications and read receipts

A message for someone offline is neither thrown away nor resent over and over. The steps:

  1. The message is stored in the database first (that already happened in step 2).
  2. The server sends a push notification through FCM (Android) or APNs (iPhone), Google's and Apple's services that can wake up a closed app.
  3. When Dewi comes online, her phone says "the last seq I have is 0", and the server sends seq 1 onwards.

The ticks on Budi's phone are three statuses: sent (the ack: stored on the server), delivered (the recipient's phone has it), read (the recipient opened the chat). "Delivered" and "read" are just small events sent back over WebSocket, for example { type: "read", upTo: 3 }: "I have read up to seq 3".

Presence: online or last seen

A phone that is online sends a heartbeat (a small ping) every 30 seconds. The server stores it in Redis with a 60-second TTL, for example SET presence:dewi online EX 60. As long as pings keep coming, the key is extended. If the phone loses signal without closing its connection, the key expires on its own at most 60 seconds later, and the status turns into "last seen".

Storing history

Every message is stored for good in a database partitioned by conversation_id and sorted by seq, for example Cassandra/ScyllaDB (strong at heavy writes) or a partitioned PostgreSQL. People almost always read the latest messages, so the last 50 or so of each conversation are cached in Redis: the database for persistence, the cache for the recent messages that get opened often. Photos and videos don't go into the chat database: they live in object storage and are served through a CDN.

🤔 Big groups: fan-out on write or on read

The fan-out so far is fan-out on write: when a message is written, it is sent to every member right away. A 1,000-member group means 1 write and 999 sends per message. For a 100,000-member channel, one message becomes 99,999 sends, and most members never even open the channel. There you use fan-out on read: the message is stored once, and members fetch it when they open the channel. Where the line sits (100 or 1,000 members, say) is a design decision.

⚠️ Messages that go missing or arrive out of order

TL;DR: A chat app: client and server talk over WebSocket, a two-way connection that stays open (right for messages and typing indicators; SSE is one-way, polling is wasteful). One message: the server gives it a seq per conversation, stores it once, acks the sender ("sent"), then fans out: directly to recipients on the same server, via Redis Pub/Sub to other servers, and a push notification (FCM/APNs) to those offline, who receive all their pending messages when they come back. Show messages by seq, not arrival time. Presence: a heartbeat every 30 seconds, a 60-second TTL in Redis. History: a database partitioned by conversation + a Redis cache for the latest messages. ChitChat: 4,630 messages a second, 80 GB a day, 3 million connections on 60 servers, 100,000 heartbeats a second. Big groups use fan-out on read.

⚡ WebSocket: two-way, always open

Guess first: the "Siti is typing..." indicator is sent many times a minute. Polling, SSE or WebSocket?

WebSocket. One connection that stays open and works both ways. SSE is one-way only, and polling wastes battery and requests.

Meaning: Because the connections stay open, a chat server is stateful. One server holds about 50,000 connections, so the sender and the recipient are often on different servers.

⚡ Store first, then send

Write:

const seq = messages.length + 1; // running number per conversation
messages.push({ seq, text }); // store first, then send

Meaning: The ack to Budi means the message is safe in the database. Then the fan-out: directly to recipients on the same server, via Redis Pub/Sub to other servers, and a push notification to those offline.

⚡ Order by seq

Meaning: Two messages can arrive reversed on Rina's phone. The phone shows messages by the server's seq, not by arrival time or the sender's phone clock. Seq also exposes gaps: having seq 5 and then receiving seq 7 means seq 6 must be asked for.

⚡ Presence through heartbeats

Meaning: A phone that is online sends a heartbeat every 30 seconds, stored in Redis with a 60-second TTL. If the signal drops, the key expires on its own and the status turns into "last seen".

What you will learn