Build a Scalable Real-Time Messaging Backend for Group Conversations
System DesignModel answerLast updated
Design a messaging backend for 1:1 and group conversations with near-real-time delivery, exact unread counts, durable history, offline sync, and clear ordering guarantees at large scale.
Task
Design the backend of a messaging product used by a large marketplace to connect two parties, and also to host multi-person group threads. A user can start a conversation with one or more people, post text messages, and see others' messages show up almost immediately. Every participant must see a correct unread count per conversation and be able to scroll back through the entire history.
Functional scope
- Direct (two-person) and group conversations
- Sending and receiving text; small payloads, with attachments passed by reference
- Creating groups and adding or removing members
- Unread count per conversation, plus paginated history
- The same history available on all of a user's devices
- Delivery to people who are offline at send time
Non-functional goals
- Highly available, low-latency send and receive; p95 delivery to connected recipients under one second
- Durable: once the server confirms a message, it must not be lost
- An explicitly stated ordering and consistency model, with justification
Assumptions (adjust and state your own)
- About 50M monthly active users and 5M simultaneous connections at peak
- About 1B messages per day: roughly 12K writes/s on average, about 60K/s at a 5x peak
- Typical conversations hold up to ~100 members. Explain what changes when one reaches thousands or tens of thousands
- Reads dominate: opening a conversation loads the latest ~30 messages, and older history is paged
What to cover
- Clarifying questions and the guarantees you commit to (ordering, delivery semantics, consistency)
- API surface: conversations, membership, send, history, delivery and read acknowledgements
- Entities, partition and clustering keys, and the storage engine for the message log versus metadata
- The send path: validation, sequence assignment, durability boundary, when the sender is acknowledged
- How a message gets its position, and why timestamps alone fail
- The connection layer, locating a recipient's live socket, and scaling to millions of sockets
- Fan-out on write versus on read, and where the switch happens as groups grow
- Offline delivery, retries, push wake-ups, reconnect and a second device catching up
- Exact per-user unread counts and efficient deep pagination
- Membership changes: what new members see, whether removed members get in-flight messages
- Read receipts and typing indicators, and their cost in large groups
- Sharding, hot conversations, failure modes, metrics and alerts
Hints
Hint 1
Model each conversation as an append-only log with a per-conversation sequence number, then derive unread counts, sync cursors and membership visibility from sequence numbers rather than from timestamps.
Hint 2
Decide where the durability boundary is (replicated log or quorum write) and acknowledge the sender only after it. Make everything downstream (inbox updates, socket delivery, push) an asynchronous consumer of that log so it can be replayed.
Hint 3
Choose fan-out per conversation size: write-time fan-out for small groups, a shared per-conversation topic plus pull-on-open for very large ones. Treat push notifications as wake-up hints and sync by cursor as the real delivery path.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Treat every conversation as an append-only log with a monotonically increasing sequence number. Ordering, sync, unread counts and membership visibility all reduce to comparisons of sequence numbers. Notifications and socket pushes are optional accelerators on top of a durable log.
1. Requirements and guarantees
Clarify first: maximum group size, whether receipts and typing indicators are in scope, retention, edits and deletes, end-to-end encryption, and supported platforms.
Back-of-envelope: 1B msgs/day gives ~12K/s average and ~60K/s peak. With ~3 recipients on average that is ~200K deliveries/s at peak. At ~1 KB per message, ~1 TB/day raw and ~3 TB/day replicated, so tiered storage for old data.
Commitments:
- Total order within a conversation; no global order (it would serialize everything and nobody needs it).
- At-least-once delivery, idempotent receipt. Clients attach a
client_msg_id; the server de-dups on(sender, client_msg_id)and receivers de-dup on(conversation_id, seq). - Durability: an ack means a quorum has persisted the message.
- Read-your-writes for the sender; others are eventually consistent within the sub-second target.
2. APIs
POST /conversationswith members and typePOST /conversations/{id}/members,DELETE /conversations/{id}/members/{uid}POST /conversations/{id}/messageswithclient_msg_id, body, attachment ref; returns{seq, server_ts}GET /conversations/{id}/messages?before_seq=&limit=30GET /syncwith per-conversation cursorsPOST /conversations/{id}/read {seq}- A WebSocket that pushes
{conv_id, seq, msg}; the client acks the highest delivered seq
3. Data model
- Message log: wide-column store (Cassandra/Scylla). Partition key
(conversation_id, bucket)where bucket is a seq range (e.g. 10K messages) to bound partition size; clusteringseq DESC. Columns: sender, client_msg_id, body, ts, type (user message or system event). - Metadata and membership: sharded relational store (MySQL/Vitess) because membership changes need transactions.
conversations(id, type, last_seq, member_version),members(conversation_id, user_id, joined_seq, left_seq, last_read_seq, role). - User inbox index:
(user_id, last_activity_ts, conversation_id)sharded by user, powering the conversation list. - Presence/sessions: Redis,
user -> {device -> gateway}with a heartbeat-refreshed TTL.
4. Write path
- The gateway authenticates; the chat service checks membership (cached by
member_version), rate limits, and de-dups. - The request is routed to the conversation's owning partition, which has a single leader under a lease. The leader assigns
seq = last_seq + 1. - Durability boundary: append to a replicated log (Kafka keyed by conversation,
acks=all) and/or write to the store at QUORUM. Only then ack the sender with the seq. - Async consumers update inboxes, push to live sockets, and trigger mobile pushes. Because they read the durable log, they are replayable.
5. Ordering
Wall clocks skew across devices and servers, ties occur within a millisecond, and NTP can step backward. Timestamp ordering would give participants different views and hide gaps. A single-writer sequence gives a total order, gap detection (holding 41 then receiving 43 means fetch 42) and cheap cursors. On failover, a lease epoch fences the old leader and the new one resumes from the max persisted seq. Timestamps are display-only.
6. Real-time delivery and presence
Stateless WebSocket gateways at ~100K connections each means ~50-100 nodes for 5M sockets. On connect the gateway registers itself in Redis (sharded by user). Delivery workers look up recipients' gateways and forward via internal RPC or pub/sub. Stale entries die by TTL. If a gateway dies, clients reconnect elsewhere and resync by seq, so only the real-time path degrades, not correctness.
7. Fan-out strategy
- Small groups (up to a few hundred): fan-out on write: update each member's inbox/unread state and push to online devices. Cost O(members) per message.
- Large groups: fan-out on read. Store once; online members subscribe to a per-conversation topic on gateways; offline members compute what they missed from their cursor on open. No per-member writes.
- Crossover: where
message_rate x memberswrite amplification dominates, typically around 1K members, earlier for very hot rooms. Make it a per-conversation mode that can flip dynamically.
8. Offline delivery and multi-device
The log is the source of truth; there is no per-device mailbox to lose. APNs/FCM pushes are wake-up hints only. Each device stores last_synced_seq per conversation. On reconnect, /sync returns conversations whose last_seq exceeds the device cursor (from the inbox index), then per-conversation deltas. A new device just has older cursors. Servers redeliver unacked messages; clients drop seqs they already hold.
9. Unread counts and pagination
unread = last_seq - member.last_read_seq, minus a small counter for the user's own messages (or count only others' messages via an adjustment). This is exact with no per-message counters. Read acks advance the watermark with max() so they are monotonic and idempotent, and propagate to other devices. History uses keyset pagination (seq < before_seq LIMIT 30), a single-partition read; older buckets can live on cheaper tiers. Avoid OFFSET.
10. Membership changes
Record joined_seq and left_seq. A new member sees messages with seq >= joined_seq by default (or full history if policy allows). A removed member is entitled to messages up to left_seq only; the membership check on the delivery path is made against the member version, and removal writes a system event so that in-flight messages after left_seq are not pushed. Accept a tiny race window and enforce on read too.
11. Receipts and typing
Delivery/read receipts are just watermarks, so they are cheap in small groups. In large groups, drop per-user receipts, show aggregates or counts, and sample or disable typing indicators. Typing is ephemeral: send over sockets only, never persist, rate-limit, and expire quickly.
12. Scaling, failures, observability
- Shard by conversation id. Mitigate hot conversations with large-group mode, per-conversation rate limits and bucketed partitions.
- Failures: leader loss gives a brief send stall for affected conversations until a new lease holds. Store node loss is covered by quorum. Redis loss degrades live delivery, with sync as fallback. Push provider outages delay only wake-ups.
- Metrics: send-to-ack latency, send-to-deliver p95/p99, consumer lag on the log, gateway connection counts and reconnect rate, sequence gaps detected by clients, push success rate, dedup hit rate, per-partition hot-key skew. Alert on lag, ack error rate and delivery SLO burn.
Common mistakes
- Ordering by timestamp.
- Acking before the durable write.
- Per-message unread counters instead of watermarks.
- Fan-out on write for huge groups.
- Treating push notifications as the delivery path.
- OFFSET pagination.