Build a Team Chat Platform with Live Delivery and Sync
System DesignModel answerLast updated
Design a workplace chat backend covering DMs and channels, with sub-second delivery, durable acknowledged messages, per-conversation ordering, and consistent history across devices.
Design a Workplace Chat Backend
You are asked to design the backend for a team chat product. People talk one-on-one in direct messages and in shared channels. The service must serve millions of users online at once, and a message sent to an online recipient should appear almost immediately.
What the product must do
- A user can post a message to another person or to a channel.
- A user can read earlier messages and see the same history on every device they own.
- A user who is online receives new messages live, without refreshing.
Quality bars
- Durability: once the system confirms a message to the sender, it must never be lost.
- Scale: it must stay healthy at the busiest hours of the day.
- Ordering: inside one conversation, messages appear in the same chronological order for everyone.
- Latency: online recipients see new messages nearly instantly.
What to cover in your answer
- Interfaces: the main calls for sending, fetching history, and keeping a live connection open.
- Storage: a schema (SQL, NoSQL, or a mix) for users, channels, memberships, and messages.
- Architecture: how messages are pushed live, and how every active device of a given user gets them.
- Scaling: how you split message data for very large channels and how you cope with a few extremely busy ("hot") conversations.
State your own usage assumptions and do a quick capacity estimate before drawing the design.
Hints
Hint 1
Begin with numbers: messages per second at peak, concurrent sockets, and the size of the largest channels. You will likely find that fan-out deliveries, not writes, dominate the load.
Hint 2
Ordering across the whole system is unnecessary. Give each conversation a single writer that hands out an increasing sequence number, and let clients use it to detect duplicates and gaps.
Hint 3
Separate the acknowledgement from the delivery. Acknowledge the sender only after a durable append, then let independent consumers handle persistence and live push. Make retries safe with a client-generated message id.
Hint 4
To avoid per-member fan-out, have each gateway subscribe to the channels its connected users belong to, so a message is published once per channel and reaches only gateways that have listeners.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and sizing
In scope: DMs, group DMs, public/private channels, live delivery, multi-device history, presence. Out of scope (mention as extensions): search, file uploads, threads.
Assumptions:
| Quantity | Estimate |
|---|---|
| Daily active users | 20M |
| Peak concurrent | ~5M users, ~8M sockets |
| Messages per day | 2B, about 23k/s average, ~100k/s peak |
| Message size with metadata | ~1 KB, so ~2 TB/day raw (~6 TB with 3x replication) |
| Sockets per gateway | ~100k, so roughly 80-100 gateways at peak |
| Channel size | Median tens of online members; a few channels with 100k-1M+ members |
Takeaway: writes are moderate, but deliveries multiply them into millions of pushes per second, and big channels are the hot spots.
2. Interfaces
WebSocket (/connect?token&device_id)
- Client to server:
send {client_msg_id, channel_id, body},ack {channel_id, seq},typing,heartbeat. - Server to client:
message {message_id, channel_id, seq, sender_id, body, ts},send_ack {client_msg_id, message_id, seq},presence,read_update.
REST (fallback and history)
POST /channels/{id}/messageswith{client_msg_id, body}returns{message_id, seq}; idempotent onclient_msg_id.GET /channels/{id}/messages?before_seq=&limit=50returns history newest-first.GET /sync?cursors={channel: last_seq}returns missed messages after a reconnect.POST /channels/{id}/read {seq}sets the read marker.
The client-generated client_msg_id is what makes retries safe, so call it out.
3. Data model
Relational (sharded Postgres/MySQL) for low-volume data needing strong consistency:
users,channels(channel_id, type, name, last_seq),memberships(channel_id, user_id, role, joined_seq), and a reverse tableuser_channels(user_id, channel_id, last_read_seq, muted)for the sidebar.
Wide-column (Cassandra/Scylla) for messages:
messages(channel_id, bucket, -- partition key
seq, -- clustering key DESC
message_id, sender_id, body, client_msg_id, created_at, edited_at, deleted)
bucket = seq / 100_000 bounds partition size, so a busy channel never becomes one unbounded partition. The latest page is a single-partition read; older pages walk back through buckets.
Why not SQL for messages? The load is append-heavy, read by range, and grows forever. Wide-column stores scale writes linearly and make range scans cheap. Ordering comes from our own sequence numbers rather than DB transactions.
4. Architecture
Client -WS-> Gateway -> Message Service (sharded by channel)
| assign seq, append
v
Kafka (key = channel_id)
| |
Persistence workers Fan-out workers
| |
Cassandra Pub/Sub (channel topics) -> Gateways -> sockets
Redis: session registry (user -> device -> gateway), presence with TTL
Send path
- The gateway authenticates and routes the frame to the Message Service shard owning the channel (consistent hashing, ownership leased via etcd/ZooKeeper).
- The owner checks membership (cached) and dedupes on
(channel_id, client_msg_id). - It assigns the next per-channel
seq(single writer, so order is trivially right). - It appends to Kafka with
acks=alland replication 3. Only after that does it sendsend_ack. This delivers the "acknowledged means durable" guarantee. - Independent consumers write idempotently to Cassandra (keyed by
(channel_id, seq)) and publish to the live layer.
Reaching every device. Each gateway keeps channel_id -> local sockets. When a socket connects, the gateway subscribes to that user's channels in pub/sub. A message is published once per channel, received only by gateways with online members, and written to every local socket, covering all devices. Fan-out cost scales with the number of gateways involved, not the member count.
Multi-device consistency. Each device tracks last_seq per channel. Delivery is at-least-once; clients dedupe by seq. A gap (expected 41, got 43) or a reconnect triggers /sync to backfill from storage.
Presence. Heartbeats every ~30s refresh a Redis key with a TTL. Only push presence for users currently visible on screen.
5. Deep dives
Ordering and failover. Order is per conversation only. If the owner dies, the new owner takes the lease with a higher epoch (fencing token), recovers the last committed seq from the Kafka partition, and writes from the stale owner are rejected. This prevents duplicate or forked sequences.
Hot and huge channels
- Gateway-level subscription collapses fan-out.
- For million-member channels, use tiered pub/sub: channel server, regional relays, gateways.
- Cache the latest ~200 messages per hot channel in Redis so many simultaneous opens do not hammer the database.
- Bucketed partitions spread storage load.
- Batch pushes over ~50 ms windows and rate-limit posting in very large channels.
- Make shard ownership load-aware so a hot channel can move to a dedicated node.
Offline users. With no active session, a notification service sends APNs/FCM push for DMs and mentions. The message is already durable and arrives through /sync on return.
6. Trade-offs
- WebSocket vs long-polling: WebSocket gives the lowest latency; keep long-polling/REST as a fallback for restrictive networks.
- Per-user push vs per-channel subscription: per-user is simpler for DMs; channel subscription is essential for big channels. A hybrid works.
- Kafka in the write path: adds a few milliseconds but gives a durable, replayable log and decouples persistence from delivery.
- At-least-once + client dedupe is simpler and more robust than exactly-once delivery.
7. Common mistakes
- Promising a global total order.
- Acknowledging before durable write.
- Fanning out per member instead of per gateway.
- Using one unbounded partition per channel.
- Forgetting idempotency for retries and a gap-repair path for reconnects.
- Ignoring failover fencing for the sequencer.