Chat System
WhatsApp-style real-time messaging, worked through the TOGAF ADM — where persistent connections become the Phase D core.
Chat system, the ADM way, in 30 seconds
- A (Vision): real-time, reliable 1:1 and group messaging; principles — never lose a message, push not poll, scale to millions of open connections.
- B (Business): capabilities — send message, receive in real time, read history, deliver when offline.
- C (Data/App): messages stored per conversation; a connection registry; stateless chat logic, stateful connection tier.
- D (Technology): the core — WebSocket gateways, connection registry, persist-before-deliver, ordering, offline path.
- E–H: ship 1:1 first, then groups and receipts; govern with delivery-latency SLOs.
- Lesson: the 'server must push' realization in Phase A dictates the whole stateful Phase D architecture.
A phone line, not a mailbox
Most web systems work like a mailbox: you walk up, ask a question, get an answer, and leave. You only ever hear back because you knocked. Chat is different — it's a phone line left off the hook. Once Alice and Bob are connected, a message can arrive from the other end at any moment, with nobody having asked for it. The server has to call you the instant a message lands, not wait for you to check.
That one difference — the server pushing to you unprompted — upends the usual design. A normal server forgets you the moment it answers; a chat server has to remember you're on the line, hold your connection open for hours while you do nothing, and know exactly which of its thousands of machines is holding your particular line so it can ring it. Tens of millions of open-but-idle phone lines is the real engineering problem, and everything in Phase D exists to manage them.
What makes it hard — the problem before the solution
- The server must push. A message arrives for you with no request from you to answer — the normal request/response shape doesn't fit.
- Connections are long-lived and stateful. Millions of sockets stay open while idle, and each one is pinned to a specific server, so a dead server drops real connections.
- Messages must never be lost. A dropped connection at the wrong instant can't be allowed to swallow a message.
- Order only matters within a conversation. Two people's unrelated chats don't need a global order — but your chat with Bob must read in the order it was sent.
Why the ADM fits chat
Chat breaks the request/response assumption every other system makes: the server must push to clients unprompted. If you recognize that in Phase A as a principle, the stateful WebSocket design in Phase D follows naturally. Skip it and you end up bolting real-time onto a request/response design that can't support it.
Phase A — Architecture Vision
- Vision: instant, reliable messaging between users and small groups, at tens of millions of concurrent connections.
- Stakeholders: users (want instant delivery + history), the business (wants reliability and sane cost).
- Principles: never lose a message (persist before deliver); push, don't poll (real-time requires it); plan for millions of idle-but-open connections (the hard, stateful part).
Phase B — Business Architecture
- Value stream: Alice sends → system routes → Bob receives instantly (or on reconnect if offline).
- Send message — must be fast and never lost.
- Receive in real time — the server pushes to an online recipient.
- Read history / offline delivery — stored messages delivered when a user reconnects, nudged by a push notification.
Phase C — Information Systems Architecture (Data & Application)
Data architecture
- Messages stored in a write-heavy store keyed by conversation (wide-column fits) for history and offline delivery.
- Connection registry:
user → which gateway holds their open socket, in a fast store. - Message IDs are client-generated for dedup and status (sent/delivered/read).
CREATE TABLE messages (
conversation_id BIGINT, -- partition/shard key: all a chat's messages co-located
seq BIGINT, -- per-conversation sequence -> ordering within the chat
message_id UUID, -- client-generated: used for dedup on resend
sender_id BIGINT,
body TEXT,
created_at TIMESTAMP,
status TEXT, -- 'sent' | 'delivered' | 'read'
PRIMARY KEY (conversation_id, seq) -- read a conversation's history by range scan
);Application architecture
- Stateful WebSocket gateway tier — its only job is holding client connections.
- Stateless chat service — assigns IDs/timestamps, persists, and routes messages.
- Media path bypasses messaging — upload to blob storage + CDN, send a reference.
Phase D — Technology Architecture (the core)
D1 — Estimate the load
# 50M daily users, ~40 messages/day each
msgs_per_sec = 50_000_000 * 40 / 86_400 # ~23,000 msgs/sec
# The real pressure is CONNECTIONS, not throughput:
# tens of millions of sockets open while idle.
# ~100k connections/server -> a whole fleet just to hold connections.D2 — The connection tier (WebSockets)
- Every online client holds an open WebSocket to a gateway server.
- A connection registry maps each user to the gateway holding their socket, so messages can be routed to the right place.
- Connections are stateful, so the load balancer pins a user to their gateway for the life of the connection (see Load balancing).
Why WebSockets, and why not just poll?
The simplest-sounding option is polling: have the client ask 'any new messages?' every second or two. It needs no special connection and reuses ordinary request/response. Here's the gap it can't fill — you're forced to choose between fast and cheap, and you can't have both. Poll every second and a message can still sit for up to a second before it's noticed (not real-time), while millions of clients each firing a request per second generate a tidal wave of mostly-empty 'nope, nothing' replies (not cheap). Tighten the interval for speed and the waste explodes; loosen it for efficiency and chat stops feeling instant.
A WebSocket dissolves the dilemma: the connection stays open, so the server pushes the message the microsecond it arrives (instant) and sends nothing at all when there's no news (cheap). The cost you pay instead is that the server must now hold and track every open connection — which is the stateful complexity the rest of Phase D is about. That's a cost worth paying, because it's the only option that is both real-time and efficient.
| Approach | Real-time? | The gap it can't fill |
|---|---|---|
| Short polling | No — up to one interval of delay. | Fast interval = request storm; slow interval = laggy chat. Can't win both. |
| Long polling | Closer, but awkward. | Holds a request open then must re-establish after each message — fiddly at scale. |
| WebSocket (chosen) | Yes — server pushes instantly. | Server must track millions of stateful, pinned connections and handle failover. |
D3 — Delivering a message (persist first)
- Alice's client sends over its socket to her gateway → the chat service.
- The service persists the message first (so it's never lost) and stamps an ID/timestamp.
- It looks up Bob in the connection registry: which gateway is he on?
- Online: route to Bob's gateway → push down his socket instantly.
- Offline: leave it stored; fire a push notification; deliver on reconnect.
async function handleSend(msg) {
// 1. PERSIST FIRST — durable before any push, so a dropped socket never loses it.
const stored = await messageStore.append(msg.conversationId, msg);
// 2. Where is the recipient connected right now?
const gateway = await connectionRegistry.get(msg.recipientId);
if (gateway) {
// 3a. Online: push down their open WebSocket via their gateway.
await gateway.push(msg.recipientId, stored);
} else {
// 3b. Offline: it's safely stored; nudge them and deliver on reconnect.
await pushNotifications.send(msg.recipientId);
}
return stored.seq; // ack the sender with the assigned sequence
}D4 — Ordering, dedup & receipts
- Ordering only within a conversation — order by server timestamp/sequence per conversation, not globally.
- Dedup via the client-generated message ID so a resend after a flaky connection doesn't duplicate (see Idempotency).
- Receipts are small status events: 'delivered' when the recipient's gateway gets it, 'read' when their client confirms.
D5 — Scale & groups
- Scale the gateway fleet horizontally; on gateway death, users reconnect and re-register (needs Service discovery + health-checked registry).
- Group chats fan out one message to every online member's gateway — buffer via a queue (see Message queues).
- Shard the message store by conversation ID.
async function fanOutToGroup(groupId, stored) {
const members = await groupMembers(groupId); // could be hundreds
for (const userId of members) {
const gateway = await connectionRegistry.get(userId);
if (gateway) {
// Online: push down their socket via whichever gateway holds it.
await gateway.push(userId, stored);
} else {
// Offline: already persisted, so just nudge them to reconnect.
await pushNotifications.send(userId);
}
}
// Big groups buffer through a queue so one slow gateway can't stall the rest.
}Scaling & bottlenecks — what breaks first
Chat scales along an unusual axis. Most systems strain on throughput; chat strains on open connections. Name the failure order and the interviewer knows you've built one.
| Breaks first as you scale | The symptom | The fix |
|---|---|---|
| Connections per gateway | A gateway runs out of file descriptors / memory holding idle sockets. | Add gateways; cap connections per node; the fleet exists mainly to hold sockets. |
| A gateway dies | Every user pinned to it drops at once. | Clients auto-reconnect and re-register; registry health-checks and repoints them. |
| The connection registry | Lookups to find a recipient's gateway get slow or stale. | Keep it in a fast in-memory store; expire dead entries; replicate for reads. |
| Large-group fan-out | One message to a 1000-member group = 1000 pushes. | Buffer through a queue; cap group size; batch pushes per gateway. |
The counterintuitive takeaway: a chat gateway is mostly idle. It's spending its resources remembering millions of quiet connections, not moving a lot of data. That's why you size the fleet by connection count, not by message rate — and why a single bad deploy that drops connections is felt instantly by everyone pinned to those servers.
Phases E & F — Migration Planning
- Ship 1:1 chat first — the core connection + persist + deliver loop.
- Add groups (fan-out) and receipts once 1:1 is solid.
- Add media last, via blob storage + CDN, off the message path.
Phases G & H — Governance & Change
- Governance (G): SLOs on delivery latency and connection success rate; capacity policies for the connection fleet.
- Change (H): adding reactions or edits is a bounded change on the message model, not a re-architecture.
Chat is the canonical stateful, real-time system — and the ADM is what keeps its trickier, stateful design honest and ordered.
Why it matters
- It's the clearest case for server-push and persistent connections.
- It forces reasoning about stateful servers, connection routing, and failover — harder than stateless tiers.
- It ties protocols, async delivery, idempotency, and service discovery into one phase-ordered system.
If ignored
- Miss the 'push not poll' principle and you bolt real-time onto a request/response design that can't support it.
- Push before persisting and messages vanish on dropped connections.
- Ignore the stateful connection tier and the design can't scale or fail over.
Where it fits
- Phase D holds the WebSocket gateway tier, connection registry, and delivery flow.
- Phase A's 'never lose a message' and 'push not poll' principles drive all of D.
- Sits beside the interview framework as a second way to structure the answer.
Related topics
- Communication protocols: WebSockets are the Phase D foundation
- Service discovery: tracks which gateway holds each user's connection
- Idempotency: client message IDs dedup resends
- Message queues: fans out group messages
Interview lens
Questions it unlocks
- Design WhatsApp / Messenger.
- How does the server push to an online user?
- How would TOGAF's ADM structure a real-time system?
60-second answer
I frame it as an ADM walk. Phase A's key principles are 'never lose a message' and 'push, don't poll', which immediately imply WebSockets and a stateful gateway tier. Phase B names send, receive-real-time, history, and offline delivery. Phase C models messages per conversation, a connection registry, and a stateless chat service over a stateful connection tier. Phase D is the core: clients hold WebSockets to gateways, the registry maps user to gateway, and a message is persisted first then routed to the recipient's gateway or stored for offline delivery. Ordering is per conversation, dedup uses client message IDs, and groups fan out via a queue. E–H ship 1:1 first then groups, governed by delivery-latency SLOs.
Common traps
- Missing the push-not-poll principle and designing around polling.
- Delivering before persisting and losing messages on dropped connections.
- Forgetting the connection tier is stateful and needs pinning and failover.