Backend Architecture for a Scalable Group Messaging Platform
System DesignModel answerLast updated
Design the server-side core of an enterprise chat product: APIs, storage, idempotent and ordered message delivery, versioned membership access control, and real-time fan-out at scale.
Scenario
You are building the backend infrastructure for a workplace communication tool (think Slack or Microsoft Teams). The platform needs to handle both one-on-one direct messages and large group conversations (up to 2,000 members). Messages must be delivered reliably, ordered consistently within each conversation, and access must be tightly controlled as membership evolves over time.
Functional Requirements
- Conversation Types: Support both 1:1 direct messages and group chats with up to 2,000 participants.
- Duplicate-Free Ingestion: When a client retries a send due to a network timeout or failure, the system must not produce duplicate messages.
- Monotonic Per-Conversation Ordering: Every participant in a given conversation must observe messages in the same strict, monotonically increasing order.
- Membership-Aware Visibility: A user who joins a conversation mid-stream should only see messages from their join point onward (unless a full-history policy is specified). A user who is removed must immediately stop receiving new messages in that conversation.
- Paginated History Retrieval: Clients should be able to page through message history forward or backward from a specific sequence number or timestamp efficiently.
Non-Functional Requirements
- Traffic: 50 million daily active users. Approximately 500 million messages per day (roughly 6,000 messages/second average, 25,000/second at peak).
- Latency: P99 push-to-online-client latency under 100 ms. History read queries under 50 ms.
- Reliability: Once the server acknowledges a message, it must never be lost. Sequence assignment within a conversation must be linearizable.
What to Cover in Your Design
- API Contracts: Define the request/response shapes for sending a message, fetching history, and updating conversation membership.
- Storage Schema and Partitioning: Describe the data model for conversations, messages, membership, and idempotency tracking. Justify your database choice and partitioning approach.
- Sequence Allocation and Deduplication: Explain how each conversation gets gap-free monotonic sequence numbers, how client retry tokens prevent duplicates, and how concurrent senders are handled.
- Membership Versioning and Read Authorization: Describe how join/leave/kick events are recorded and how the read path enforces visibility windows without expensive runtime joins.
- Write Path and Real-Time Fan-Out: Walk through the flow from message ingestion through persistence to real-time delivery to connected recipients.
Hints
Hint 1
Think about what level of consistency you actually need — is a global total order required, or is per-conversation linearizability sufficient?
Hint 2
Consider modeling membership changes as events in the same ordered log as messages, so there is never ambiguity about whether a message came before or after a join or removal.
Hint 3
Separate the concerns of sequence generation (a per-conversation monotonic counter) from bulk storage scaling (partitioning by conversation key range) so each can scale independently.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Capacity Planning
First, confirm what is in and out of scope. This design covers text messages with references to attachment blobs (stored in object storage). Edits become tombstone markers; deletes are soft deletes. Search, threading, and reactions are excluded.
Load estimates:
- Average write rate: 500M messages/day ≈ 6,000/s, peaking at ~25,000/s.
- Fan-out: most conversations are small. Assuming an average of ~10 recipients, peak push rate is ~250,000/s. The worst case is a 2,000-member group, producing 2,000 fan-out writes per message.
- Storage: ~1 KB per message → ~500 GB/day, ~180 TB/year raw, ~550 TB with 3x replication. This calls for a hot/cold tier split: recent messages in the primary store, older ones archived to object storage.
- Connections: 50M DAU with perhaps 15M concurrent WebSocket connections. At ~50K connections per gateway node, you need roughly 300 gateway nodes.
Key consistency insight: Linearizability is only needed within a single conversation. There is no global message ordering requirement. This is the fundamental property that lets the system scale horizontally.
2. API Design
Clients maintain a persistent WebSocket for real-time push. RPC endpoints are also exposed over HTTP/gRPC for command operations.
SendMessage(conversation_id, client_msg_id, body, attachments[])
-> { message_id, seq, server_ts }
GetMessages(conversation_id, anchor: {seq | timestamp},
direction: BEFORE | AFTER, limit)
-> { messages[], next_cursor, has_more }
UpdateConversationMembership(conversation_id, op: ADD | REMOVE | LEAVE,
user_ids[], history_policy: FROM_JOIN | FULL,
request_id)
-> { membership_seq }
// Server-to-client push event
PushEvent: { conversation_id, seq, message | membership_event }
client_msg_id is a UUID generated by the client and serves as the idempotency key. Retries with the same UUID return the original response. request_id on membership updates plays the same role.
Gap detection protocol: Each client tracks last_seq per conversation. If a pushed event arrives with a sequence number that is not last_seq + 1, the client issues a GetMessages call with AFTER last_seq to backfill. This makes push best-effort while keeping history authoritative.
3. Storage Architecture
Database choice: A Raft-replicated, range-partitioned distributed SQL store such as Spanner, CockroachDB, or TiKV. The critical property is that every table key is prefixed with conversation_id, so all rows for one conversation live in a single range served by one leader replica. This means sequence allocation, idempotency deduplication, and message insertion all execute as a single-range transaction without any two-phase commit.
Schema:
conversations (conv_id PK, type, last_seq, created_at, retention_policy)
messages (conv_id, seq) PK, message_id, sender_id, server_ts,
body, kind (USER | MEMBERSHIP | TOMBSTONE), deleted
idempotency_keys (conv_id, client_msg_id) PK, seq, expires_at -- TTL 24-48h
membership (conv_id, user_id, interval_no) PK, join_seq, leave_seq, role
user_inbox (user_id, conv_id) PK, last_read_seq, last_msg_seq -- sharded by user
Read patterns: History retrieval is a primary-key range scan on (conv_id, seq), which is efficient and meets the 50 ms target. Timestamp anchors resolve to a sequence via a secondary index on (conv_id, server_ts).
Hot range splitting: Very large conversations can split by (conv_id, seq_bucket). Since sequence allocation only touches the tail range, splitting does not interfere with writes. Messages older than ~90 days are compacted into Parquet files in object storage, keyed by conv_id/seq-range.
4. Sequencing and Idempotency
SendMessage is handled by the conversation's range leader in a single transaction:
- Deduplication check. Look up
idempotency_keysby(conv_id, client_msg_id). If found, return the storedseqand skip all further work. - Sequence allocation. Compute
seq = conversations.last_seq + 1. - Atomic write. Insert the message row, insert the idempotency key, and update
last_seq— all in one transaction. - Quorum commit and ack. Commit through Raft (3 replicas across availability zones, ~5-10 ms), then acknowledge the client.
Why this is correct:
- No message loss: the client is only acknowledged after quorum commit.
- Gap-free sequences: aborted transactions never consume a sequence number. A new leader recovering after a failure reads
last_seqfrom the last committed Raft entry. - Concurrent senders: serialized by the single range leader, so no additional locking is needed.
- Throughput: the leader keeps
last_seqand recent idempotency keys in memory and uses group commit (batching multiple sends into one Raft entry), supporting thousands of messages per second per conversation.
Alternative approach: A dedicated sequencer service (etcd-style distributed counters, one per conversation shard) paired with a wide-column store like Cassandra. This gives cheaper storage but introduces allocated-but-never-written gaps that require explicit hole-marker tombstones. The single-transaction design is preferred for correctness simplicity.
5. Membership Lifecycle and Visibility
Membership changes are written as kind=MEMBERSHIP rows in the same conversation log and receive a sequence number in the same transaction that updates the membership interval table.
- Join: Creates a new interval row with
join_seq = S(orjoin_seq = 0for full-history policy) andleave_seq = NULL. - Remove/Kick: Sets
leave_seq = Son the open interval. - Rejoin: Creates a new
interval_no, so a user can have multiple non-overlapping membership intervals.
Because membership events and messages share the same ordered log, there is never ambiguity about whether a message was sent before or after a removal.
Read path enforcement:
- Load the user's membership intervals for the conversation (a few rows, cached in Redis with invalidation on membership events).
- Clamp the requested sequence range to the union of
[join_seq, leave_seq]intervals. - Execute the range scan. No runtime join against a member list is needed.
Write and push authorization:
- Sending requires an open membership interval at the time of the transaction.
- Fan-out uses the member set as of the message's sequence number.
- A removed user is dropped from fan-out starting at the removal sequence. The removal event also instructs gateway nodes to unsubscribe that user's WebSocket connection for the conversation.
6. Write Path and Real-Time Delivery
- The client sends a message over WebSocket to a gateway node, which forwards it to the Message Service.
- The Message Service routes by
conv_idto the appropriate range leader, which commits the message and returns an acknowledgment with the assignedseq(~15 ms round trip). - The committed message is published to Kafka, partitioned by
conv_idto preserve per-conversation ordering. A transactional outbox or CDC feed from the database guarantees no events are dropped between commit and publish. - Fan-out workers consume from Kafka, fetch the member set (cached in Redis), and look up each member's connected gateway node via a Redis presence map (
user_id → gateway_node). They then push the event over the gateway's WebSocket connection to each online recipient. - Offline recipients have their
user_inbox.last_msg_sequpdated so they can detect gaps on reconnection.
Common mistakes to avoid:
- Assuming a global sequence is needed — it is not. Per-conversation linearizability is sufficient and far more scalable.
- Handling membership changes outside the message log, which creates race conditions between a removal and in-flight messages.
- Acknowledging before the quorum commit, which risks message loss on leader failover.
- Forgetting to invalidate cached membership data on changes, leading to stale access checks.