Durable, Ordered Messaging Backend for 1:1 and Group Chat
System DesignModel answerLast updated
Design a messaging backend where an acknowledged message is never lost, each conversation has a deterministic order, and reconnecting clients catch up without gaps or duplicates.
Problem
You are designing the backend for a workplace messaging product. It supports direct conversations between two people and group channels of up to 1,000 members. Once the sender has been told "your message was accepted", that message must survive crashes of individual servers or in-memory queues. Every recipient must see a conversation's messages in the same deterministic order. Clients that lose connectivity must be able to resume without missing or double-seeing anything.
Functional requirements
- Direct (1:1) and group conversations, with groups of up to 1,000 participants.
- Real-time push to connected clients, and catch-up for clients that were offline.
- At-least-once transport combined with client-side deduplication, so users experience exactly-once delivery.
- Membership can change over time. A user may read only messages sent while they were a member.
Non-functional requirements
- Durability: the sender's acknowledgment may only be returned after the message is on durable, replicated storage. Acknowledging data held only in a volatile broker is not acceptable.
- Ordering: strict, monotonic ordering within each conversation (no global order is needed).
- Latency: P99 delivery under 100 ms to connected recipients.
- Availability: gateway or broker failures must not corrupt data or permanently lose messages.
Scale
- 50 million daily active users, 10 million concurrent streaming connections (WebSocket or gRPC).
- About 1 billion messages per day: roughly 12k writes/s on average, 50k writes/s at peak.
- Group size: median 8, P99 200, hard cap 1,000.
What to cover
- APIs: sending, real-time streaming, and catch-up sync.
- Storage and ordering: how sequence numbers are issued, the schemas, and how data is partitioned.
- Message lifecycle: client, gateway, sequencing and persistence, fan-out, push gateways.
- Durability trade-offs: memory-only brokers (e.g. Redis Pub/Sub) versus log- or quorum-backed storage (e.g. Kafka, Cassandra/ScyllaDB) before the sender is acknowledged.
- Reconnection: the protocol when a client returns carrying its last delivered sequence number after a drop or a server failover.
Hints
Hint 1
Make the durable log or quorum store the source of truth, and treat every in-memory pub/sub layer as a best-effort speed-up that can lose pushes without losing messages.
Hint 2
Give each conversation its own dense, gap-free counter owned by a single writer at a time (a leased, fenced sequencer). Dense numbers let clients detect missing messages locally.
Hint 3
Make sends idempotent with a client-generated message ID, and put membership joins and leaves into the same per-conversation sequence so read-access windows are totally ordered with messages.
Hint 4
Store each message once per conversation and fan out pushes only to online users; offline users reconcile by pulling from their last known sequence number.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Contract and back-of-envelope numbers
The central promise is: ACK means durable. Ordering is per conversation only. "Exactly-once" is what the user sees, built from at-least-once transport plus deduplication.
- Ingress: 50k msg/s at ~1 KB is ~50 MB/s, or ~150 MB/s with 3x replication.
- Storage: ~1 TB/day raw, ~3 TB/day replicated.
- Push volume: with an average of ~20 recipients per message, peak push is on the order of 1M deliveries/s, mostly to online users.
- Connections: 10M concurrent at 50-100k per gateway means ~100-200 gateway nodes.
- Latency budget (100 ms P99): ~10 ms quorum commit, ~5 ms recipient lookup, ~10-30 ms gateway push, the remainder is network.
2. APIs
SendMessage(conversation_id, client_msg_id, body)
-> {seq, server_ts} // returned only after durable commit; retries return the same seq
Stream(session_token) // bidirectional WebSocket / gRPC
server -> client: Message{conversation_id, seq, sender, body}
client -> server: DeliveryAck{conversation_id, seq}
Sync(cursors: [{conversation_id, last_delivered_seq}])
-> {conversations: [{id, head_seq}], messages: [...], next_page_token}
GetHistory(conversation_id, from_seq, to_seq, limit)
client_msg_id (a UUID made by the client) is the idempotency key.
3. Data model and partitioning
Use a wide-column store (Cassandra or ScyllaDB), partitioned by conversation_id.
| Table | Key | Purpose |
|---|---|---|
messages | PK conversation_id, clustering seq | One copy of each message |
idempotency | (conversation_id, client_msg_id) -> seq, TTL 1-3 days | Safe retries |
conversations | conversation_id -> head_seq, type, epoch | Latest sequence and owner epoch |
membership | (conversation_id, user_id) -> [join_seq, leave_seq) windows | Read-access enforcement |
user_conversations | PK user_id -> conversation_id, last_read_seq, last_activity | Conversation list and sync |
Very hot conversations can be bucketed as (conversation_id, seq / 100000) to avoid unbounded partitions.
Sequence numbers are per conversation, dense and monotonic (1, 2, 3...). Density lets a client spot a gap by itself. Avoiding a global counter removes a global coordinator and a bottleneck.
4. Sequencing and write path
Hash conversations into roughly 1,024 logical shards; each shard has exactly one owning sequencer.
Ownership and fencing. The sequencer holds a lease in etcd/ZooKeeper together with an increasing epoch. Every write carries the epoch and storage rejects stale epochs, so a paused "zombie" sequencer cannot cause split-brain.
Message lifecycle
- The client sends over its stream; the gateway authenticates and routes by
conversation_idto the shard owner. - The sequencer checks
idempotency(a repeat returns the originalseq), verifies the sender is an active member, and assignsseq = head_seq + 1from its in-memory head. - Durable commit: either append to a replicated log (Kafka RF=3,
acks=all,min.insync.replicas=2, idempotent producer, partitions aligned to shards), or write directly to the store atQUORUMwith RF=3, including the idempotency row. - ACK the sender with
seq, only now. - Asynchronously: a materializer writes to
messages(if using a log), and the fan-out service consumes the log and pushes.
Writes for one conversation are pipelined in order. If n fails, abort n+1..., reload the head from durable state, and retry, so no holes appear.
Failover. A new sequencer takes the lease with epoch+1, recovers head_seq from the log tail or max stored seq, and resumes.
5. Fan-out and delivery
- A connection registry (Redis-like) maps
user_id -> {gateway, connection}. It is ephemeral and rebuilt on reconnect. - The fan-out engine loads a cached, versioned membership snapshot, groups online recipients by gateway, and sends one batch per gateway, which then pushes locally.
- Offline users receive nothing; they reconcile on reconnect. Mobile notifications are a separate, lossy hint.
- Storage is fan-out-on-read (one copy per conversation); push is fan-out-on-write to online users only. Write amplification stays near 1x instead of up to 1,000x for per-user inboxes.
Client ordering rules
- Render strictly by
seq. - If
n+2arrives beforen+1, buffer ~200 ms, then callGetHistoryfor the gap. - Drop anything with
seq <= last_delivered.
Membership changes are messages in the same sequence. Joins and leaves pass through the sequencer, so join_seq and leave_seq are totally ordered with chat messages. Push, sync and history all clip to the user's windows; a user who left at seq 500 never receives 501 through any path.
6. Volatile brokers versus durable logs
| Redis Pub/Sub | Redis Streams + AOF | Kafka / Scylla quorum | |
|---|---|---|---|
| Persistence | None | fsync ~1 s, async replication | Quorum on disk |
| Loss on crash | All in-flight and all offline subscribers | Up to ~1 s plus failover gaps | None after ACK (barring quorum loss) |
| Latency | Sub-ms | ~1 ms | ~5-15 ms |
| Replay | No | Limited | Yes, by offset/seq |
ACKing after a Redis publish breaks the core promise: a broker crash, or just a subscriber that is not connected, silently drops a message the sender believes was delivered. The extra ~10 ms of quorum latency fits comfortably in the 100 ms budget.
So: the durable log is the source of truth, and ephemeral pub/sub between fan-out and gateways is only an optimization. A lost push is harmless because the client detects the gap and pulls.
7. Reconnection protocol
- The client opens a stream and sends
last_delivered_seqper conversation. - The server compares each cursor with
head_seqand returns the missing range, clipped to membership windows, in pages. - The server then switches the client to live push, buffering anything that arrives during the replay so the handoff has no gap.
- The client deduplicates by
seq, so overlap is harmless.
After a gateway crash, clients reconnect to another gateway and repeat this; the registry is overwritten.
Common mistakes
- Acknowledging before a quorum commit.
- Using a global sequence or a timestamp for ordering (clock skew, bottleneck).
- Allowing two sequencers to write the same conversation (no fencing).
- Storing a copy per recipient for large groups.
- Handling membership outside the message sequence, which leaks messages after a leave.
- Using a non-idempotent send path, which produces duplicates on retry.