Skip to main content

Chat System

Learning objectives
  • Design a stateful WebSocket gateway tier and the routing that finds a recipient's connection
  • Guarantee per-conversation ordering and no-loss delivery with sequence numbers, acks and resync
  • Model message storage in a wide-column store and choose a group fan-out strategy
  • Adapt the design to a bank's customer-support chat: routing to agents, audit, PII redaction

TL;DR​

  • Clients hold a persistent WebSocket to a gateway tier; a session registry maps user/device → gateway. Gateways are stateful, so deploys and failures mean mass reconnects — design for them.
  • Order messages with a per-conversation sequence number assigned by the server, never by client clocks. Clients dedup by clientMsgId and detect gaps by seq.
  • Persist before ack. The sender's tick means "durably stored"; delivery to recipients is asynchronous.
  • Store messages in a wide-column store partitioned by (conversation, bucket) and clustered by seq — append-heavy writes, "latest N" reads.
  • Small groups: write once, fan out delivery to online members. Huge channels: don't push to everyone; let clients pull.
  • Receipts and presence often generate more traffic than messages: coalesce to cursors (highest seq read), subscribe to presence only for what is on screen.
  • Bank support chat is low volume but high control: authenticated, routed to skilled agents, recorded for years, PANs redacted — no end-to-end encryption.

Why it matters​

Chat tests stateful real-time systems: connection management, ordering, at-least-once delivery and fan-out — problems that reappear in trading notifications, live order tracking and livestream commerce. Banks and e-commerce platforms rarely build a consumer messenger, but they very often build customer-support chat (in-app chat with an agent or bot), buyer–seller chat in a marketplace, and ops chat-ops. Interviewers use the classic version, then ask "how would this differ for our support centre?"

1. Clarify requirements​

QuestionAssumption
1:1, groups, broadcast channels?1:1 and groups up to 500 members
Multi-device?Yes — phone + web, each in sync
History?Stored forever (consumer) / per retention policy (bank)
Features?Text, receipts (sent/delivered/read), presence, typing indicators; media via object storage
Latency?Under 300 ms end to end for online recipients in the same region
Scale?50M DAU
E2E encryption?Out of scope for consumer version; explicitly not allowed for bank support (must be recorded)

2. Estimate​

  • Messages: 50M DAU × 40 messages/day = 2B/day ≈ 23k/s average, ≈ 70k/s peak.
  • Deliveries: groups multiply this; with an average of ≈ 3 recipients, ≈ 200k deliveries/s at peak — plus receipts, which roughly double the frame count.
  • Connections: ≈ 30% of DAU online at peak = 15M concurrent sockets. At a rough 50k–100k connections per tuned gateway node (memory-bound: buffers + goroutines ≈ tens of KB per connection), that is ≈ 150–300 gateway nodes.
  • Storage: 2B × ≈ 200 B = 400 GB/day ≈ 146 TB/year before replication. Append-only, rarely updated, mostly recent reads.

3. API and data model​

WebSocket frames (JSON or protobuf):

{"type": "send", "clientMsgId": "c-7f2e", "conversationId": "g_8812", "body": "Đơn hàng của mình giao chưa?"}
{"type": "ack", "clientMsgId": "c-7f2e", "seq": 1042, "serverTs": 1760688120123}
{"type": "msg", "conversationId": "g_8812", "seq": 1042, "senderId": "u_77", "body": "..."}
{"type": "receipt", "conversationId": "g_8812", "kind": "read", "upToSeq": 1042}
{"type": "sync", "cursors": [{"conversationId": "g_8812", "lastSeq": 1030}]}

REST for history and conversation list: GET /v1/conversations/g_8812/messages?beforeSeq=1000&limit=50.

Message table (CQL, Cassandra/ScyllaDB):

CREATE TABLE messages (
conversation_id text,
bucket int, -- seq / 10000: bounds partition size, computable from seq
seq bigint,
sender_id text,
client_msg_id text,
body text,
created_at timestamp,
PRIMARY KEY ((conversation_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC);

CREATE TABLE user_conversations (
user_id text,
conversation_id text,
last_seq bigint, -- latest message seq (for unread badge)
read_seq bigint, -- this user's read cursor
muted boolean,
PRIMARY KEY (user_id, conversation_id)
);

Bucketing by seq / 10000 rather than by day means a quiet 1:1 conversation lives in one partition for years, while a busy group rolls to a new partition every 10k messages — no unbounded partitions, and the reader computes which bucket to query from the seq it has. See NoSQL Data Modeling.

4. High-level design​

  • Gateways terminate WebSockets, authenticate the token on connect, register (user, device) → gateway in the session registry, and forward frames to the chat service over gRPC. They keep no business state.
  • Chat service is stateless: dedup, assign seq, persist, ack, publish.
  • Fan-out workers consume by conversation, look up members and their sessions, and push to the right gateways — or to push notifications for offline members.

5. Deep dives​

5.1 Connection management​

  • Why WebSocket: full-duplex, low overhead per message, works through most proxies. Long polling is the fallback; SSE is one-way. See Polling, WebSocket & SSE.
  • Load balancing: an L4 balancer (or L7 with WebSocket upgrade support) distributes new connections by least-connections. No stickiness needed — the connection itself is sticky.
  • Heartbeats: mobile carriers and NATs silently drop idle TCP flows after minutes. Ping every ≈ 30 s; if two pongs are missed, close and clean the registry.
  • Slow consumers: each connection has a bounded outbound queue; if it fills, disconnect and let the client resync. Never let one slow phone block a gateway goroutine pool.
  • Deploys: a gateway restart drops ≈ 100k connections at once. Drain gradually: stop accepting, send a reconnect frame to batches, clients reconnect with jittered backoff. Without jitter you create a reconnect storm that looks like a DDoS.

One goroutine should own all writes on a connection (most WebSocket libraries are not safe for concurrent writers):

package gateway

import (
"context"
"time"
)

type Frame struct {
Type string
Data []byte
}

type FrameWriter interface {
WriteFrame(Frame) error
}

// writeLoop serialises messages, receipts and pings onto one connection.
// out is bounded; the producer disconnects the client when it is full.
func writeLoop(ctx context.Context, conn FrameWriter, out <-chan Frame, ping time.Duration) error {
ticker := time.NewTicker(ping)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case f, ok := <-out:
if !ok {
return nil
}
if err := conn.WriteFrame(f); err != nil {
return err
}
case <-ticker.C:
if err := conn.WriteFrame(Frame{Type: "ping"}); err != nil {
return err
}
}
}
}

5.2 Ordering and no-loss delivery​

  • Server-assigned seq per conversation is the ordering truth. Client timestamps are wrong (skewed clocks, offline composition); global Snowflake IDs are only roughly ordered across nodes. See Time, Clocks & Ordering.
  • Allocating seq: INCR conv:<id>:seq in Redis is simple and fast. A Redis failover can lose recent increments and reissue a seq — guard with a conditional insert (IF NOT EXISTS on (conversation, seq)) or reconcile the counter from the store's max seq on failover. The alternative is a single owner per conversation (route by consistent hashing to one chat-service shard or one Kafka partition) that assigns seq in memory.
  • Idempotent send: the client retries with the same clientMsgId until acked; the server keeps (conversation, clientMsgId) → seq for a few minutes and returns the original seq on repeats.
  • Gap detection and resync: a client that sees seq 1040 then 1042 fetches 1041. On reconnect it sends its lastSeq per conversation (or one per-user cursor, see below) and the server streams what was missed. This is what makes "at-least-once + dedup" feel exactly-once to the user.

5.3 Storage choice​

The workload is write-heavy, append-only, partitioned naturally by conversation, and read as "latest 50, then page back" — a textbook fit for an LSM-based wide-column store (Storage Engines). Facebook Messenger historically used HBase; Discord has written publicly about moving trillions of messages from Cassandra to ScyllaDB. Watch for:

  • Hot partitions from very active groups → bucketing bounds partition size, but one bucket can still be hot; cap group size or treat big groups as channels.
  • Tombstones from deletes in Cassandra hurt reads; prefer soft-delete flags or TTL-based expiry.
  • Search over history is a separate index (Elasticsearch/OpenSearch) fed from Kafka — not queries on the message table.

5.4 Group fan-out​

StrategyHowGood forCost
Write once, fan out deliveryOne row per message in the conversation; push to each online member's gatewayGroups up to a few hundredEach device syncs per conversation cursor
Per-user inbox (timeline)Copy a pointer/message into every member's inboxMulti-device sync with one cursor per user; simpler clientStorage and writes × group size
Pull for channelsStore once; send a lightweight "new activity" hint; clients fetch when openedBroadcast channels, 10k+ membersSlightly higher read latency

A common hybrid: write once into the conversation, plus a small per-user sync queue of (conversation, seq) pointers so a device can ask "what changed since my cursor?" in one call. Same push-vs-pull reasoning as News Feed.

5.5 Receipts and typing indicators​

  • Sent = server ack (persisted). Delivered = a recipient device acked up to seq N. Read = the user's read cursor moved to N.
  • Store receipts as cursors, not per-message rows: read_seq in user_conversations. "Read up to 1042" covers 1,000 messages in one write.
  • In groups, "read by 37 of 120" is computed on demand from members' cursors; do not push every member's read event to every other member.
  • Coalesce: the client sends at most one read receipt per conversation every second or two.
  • Typing indicators are ephemeral: fire-and-forget through gateways, never persisted, dropped under load.

5.6 Presence​

  • The gateway refreshes presence:<user> with a TTL (≈ 60 s) on each heartbeat; expiry means offline. Add a grace period before announcing "offline" so a phone switching from Wi-Fi to 4G does not flap.
  • Do not broadcast every change to all contacts. Clients subscribe to presence for the conversations currently on screen; the presence service publishes changes only to subscribers.
  • For big groups show "≈ 23 online", computed lazily and cached.

5.7 Variant: bank customer-support chat​

What changes:

  • Scale is small (tens of thousands of conversations/day, hundreds of agents) — Postgres is fine; the hard parts are workflow and compliance.
  • Identity: chat runs inside the authenticated app session; sensitive actions (card block, limit change) require step-up authentication in the app, never "tell the agent your OTP". Agents must never ask for OTPs or passwords — put that in the UI copy.
  • Routing: skills-based queues (cards, loans, fraud), priority for fraud reports, agent concurrency limits (say 3 chats each), SLA timers with escalation.
  • Audit and retention: transcripts are records — append-only, retained per policy (often years), exportable for disputes. No end-to-end encryption, because the bank must be able to read them; encrypt in transit and at rest instead.
  • PII/PCI: detect and mask card numbers (16 digits + Luhn check) and national ID numbers before storage and before showing to agents who don't need them. Storing a full PAN would pull the chat platform into PCI DSS scope. See Compliance.
  • Attachments (ID photos, receipts): malware scan, encryption, signed short-lived URLs.
  • Build vs buy: many banks buy a contact-centre platform; the architect's job is then integration (SSO, CRM, data residency, audit export). Say this in the interview — it is a real architect answer.

For an e-commerce marketplace, buyer–seller chat adds anti-fraud scanning (sellers pushing buyers to pay off-platform, phone numbers and external links in messages) and order context cards.

6. Trade-offs to state out loud​

DecisionChoiceAlternative and when
TransportWebSocketLong polling for restrictive networks; SSE for receive-only
Seq allocationRedis INCR + conditional insertSingle-owner shard per conversation when strict ordering under failover matters
StoreWide-column (Cassandra/Scylla)Postgres for support chat or under ≈ 1B messages total
Group fan-outWrite once + delivery fan-outPer-user inbox when multi-device simplicity beats storage cost
ReceiptsCursorsPer-message rows only if legally required per message
PresenceSubscribe-on-screenBroadcast only for tiny contact lists

Interview angle​

  • Strong answers: persist-before-ack, server seq per conversation, explicit reconnect/resync protocol, a plan for gateway deploys, and receipts as cursors.
  • Follow-ups: How does a message reach a user connected to another gateway? What if the recipient has three devices? How do you guarantee ordering when two members send at the same millisecond? How do you roll a new gateway version without dropping 15M users? What changes for a bank's support chat?
  • Red flags: ordering by client timestamp, broadcasting presence to all contacts, storing chat in one giant relational table without a partitioning plan, E2E encryption for a regulated support channel.

Self-check​

1. How does the system find which gateway holds the recipient's connection?

On connect, the gateway writes (user, device) → gateway id into a session registry (Redis with TTL refreshed by heartbeats). Fan-out workers read it and call the target gateway (gRPC or a per-gateway queue). If no entry exists, the user is offline and gets a push notification.

2. Why "persist before ack", and what does the sender's tick mean?

So that an acked message can never be lost, even if the chat service crashes right after acking. The tick means "durably stored by the server", not "delivered". Delivery to recipients is asynchronous and tracked by separate receipts.

3. A client reconnects after 10 minutes in a tunnel. How does it catch up without duplicates or gaps?

It sends its last seen seq per conversation (or a per-user sync cursor). The server returns messages with higher seq in order; the client inserts by seq and ignores ones it already has. Any gap detected later triggers a targeted fetch.

4. Compare write-once fan-out and per-user inbox for groups.

Write-once stores each message once and pushes to online members; devices sync per conversation — cheap storage, more client work. Per-user inbox copies into every member's timeline — one cursor per user, simple multi-device sync, but writes and storage scale with group size. Large channels should use pull.

5. You must roll out a new gateway version. What is the plan?

Drain nodes gradually: stop accepting new connections, send reconnect frames to batches, clients reconnect with jittered exponential backoff to other nodes, registry entries update on reconnect. Watch reconnect rate and connect latency; keep spare capacity (≈ 20–30%) so the remaining nodes can absorb the moved connections.

6. What three things would you insist on for a bank's support chat that a consumer chat doesn't need?

Any three of: transcripts as auditable records with retention (no E2E); PAN/ID redaction before storage; agents never asking for OTP and sensitive actions requiring in-app step-up; skills-based routing with SLA; encrypted, malware-scanned attachments; integration with CRM/core banking under least privilege.

🧠 Flashcards0/8 learned · 0 retries

Exercise​

Write a Go gateway with nhooyr.io/websocket or gorilla/websocket: per-connection bounded outbound channel, the writeLoop above, Redis session registry with TTL, and a chat service that assigns seq with INCR. Run two gateway instances, connect 2,000 simulated clients, kill one gateway, and measure how long until all clients are reconnected and have no seq gaps. Done when you can show the reconnect curve with and without jitter.

Further reading​

  • System Design Interview — An Insider's Guide (Vol. 1), Alex Xu — "Design a Chat System".
  • Discord engineering blog — "How Discord Stores Trillions of Messages".
  • RFC 6455, The WebSocket Protocol.
  • Designing Data-Intensive Applications, Martin Kleppmann — ordering and partitioning chapters.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).