Design a Real-Time Guild Chat Platform with Durable History
System DesignModel answerLast updated
Design backend infrastructure for a Discord-like platform with servers, channels, DMs, real-time delivery, message persistence, and strict per-channel ordering at scale.
Design a Real-Time Guild Chat Platform
You are building the backend for a community communication platform organized around guilds (think: persistent groups), text channels within those guilds, and one-on-one direct messages. The platform must deliver messages in real time to connected clients while also guaranteeing that no message is lost, even when recipients are temporarily offline.
What the System Must Do
- Users can belong to many guilds and browse channels inside each one.
- Sending a message to a channel pushes it to every currently-online member of that channel with minimal delay.
- When a client connects or reconnects, it can pull any messages it missed during its absence.
- Messages in a given channel have a total, unambiguous order — no two members should ever see them in a different sequence.
Quality Bar
- Message delivery latency stays low (sub-200 ms p99 within a region).
- The platform stays highly available; partial component failures do not silence users.
- The architecture scales to tens of millions of concurrent connections.
What to Cover in Your Answer
- API surface: REST endpoints and WebSocket events the client uses.
- Storage schema: How users, guilds, channels, memberships, and messages are persisted.
- Delivery path: How a message travels from sender to database to online recipients, and how offline clients catch up.
- Ordering guarantee: How strict per-channel ordering is maintained in a distributed setting where multiple servers handle writes.
Key Constraints
- The user base is global and network conditions vary; assume frequent disconnects and reconnects on mobile.
- Durability is non-negotiable: once the server acknowledges a message, it must survive any single-component failure.
Hints
Hint 1
Decouple message persistence from fan-out — ack only after a durable write, then publish asynchronously so a slow subscriber never blocks the write path.
Hint 2
Assign each channel to a single sequencer (Kafka partition or leased owner) so writes within that channel are totally ordered; clients render by sequence number, not arrival time.
Hint 3
Use an idempotency key (client nonce) so retries on flaky networks never create duplicate messages.
Hint 4
On reconnect, push recent missed messages for active channels but only send unread counts for stale ones — let the client lazy-load history on demand to avoid replay storms.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Solution Walkthrough
1. Establish Scale and Priorities
Before drawing boxes, anchor the design with numbers so each choice is defensible.
| Dimension | Estimate |
|---|---|
| Daily active users | ~100M, with 10M concurrent WebSocket connections at peak |
| Messages per user per day | ~40, giving ~4B/day total — roughly 46K/s average, 200K/s at peak |
| Message size | ~1 KB including metadata → ~4 TB/day, ~1.5 PB/year before replication |
| Read-to-write ratio | Read-heavy: each message fans out to every online member, plus frequent history scrolls |
| Guild sizes | Long tail: most guilds have under 100 members; a handful exceed 1M (the hot-channel problem) |
Two priorities shape every downstream decision. First, durability: once the server acknowledges a message, it must not be lost. Second, ordering is strict per channel — global ordering across channels is unnecessary. Target latency is under 200 ms p99 within a region.
2. API Design
REST for stateless request-response operations:
POST /guilds/{id}/join— join a guildGET /users/me/guilds— list the user's guildsGET /guilds/{id}/channels— list channelsGET /channels/{id}/messages?before={seq}&limit=50— paginated backward history scrollGET /channels/{id}/messages?after={seq}&limit=100— gap-fill after reconnectPOST /channels/{id}/messageswith body{content, client_nonce}— fallback send path for clients without an active socket
WebSocket (through a gateway) for real-time traffic:
IDENTIFY {token, resume: {session_id, last_seq_per_channel}}— authenticate and optionally resume a dropped sessionSEND_MESSAGE {channel_id, content, client_nonce}→ server repliesMESSAGE_ACK {client_nonce, message_id, seq}- Server-pushed:
MESSAGE_CREATE {channel_id, seq, message_id, author, content},PRESENCE_UPDATE,TYPING_START HEARTBEAT/HEARTBEAT_ACK— detect dead connections on unstable mobile links
The client_nonce is the idempotency key. Mobile clients retry on poor networks; the nonce guarantees a retry never duplicates a message.
3. Data Model
Relational store (Postgres, sharded by guild_id) for low-volume, strongly consistent metadata:
users(user_id PK, username, created_at)
guilds(guild_id PK, owner_id, name)
channels(channel_id PK, guild_id, name, type, last_seq)
memberships(guild_id, user_id, roles, joined_at, PK(guild_id, user_id))
channel_permissions(channel_id, role_id, allow_bits, deny_bits)
Message store (Cassandra/ScyllaDB) for write-heavy, append-only, range-queried data:
messages(
channel_id bigint,
bucket int, -- seq / 10000 to bound partition size
seq bigint, -- per-channel monotonic sequence
message_id bigint, -- Snowflake, globally unique
author_id bigint,
content text,
client_nonce text,
edited_at timestamp,
deleted boolean,
PRIMARY KEY ((channel_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC);
"Latest 50 messages" is a single-partition read. Bucketing prevents unbounded partitions in very busy channels. Writes use QUORUM with replication factor 3.
Read state is a lightweight counter, not per-message rows: read_state(user_id, channel_id, last_read_seq).
4. Architecture and Message Flow
Client ──WS──> Gateway (stateful, ~100K conns/node)
│ SEND_MESSAGE
▼
Message Service (stateless) ──authz──> Membership/Perm cache (Redis)
│ route by channel_id
▼
Channel Sequencer (owner of channel partition)
│ assign seq, write QUORUM ──> Cassandra
│ append ──> Kafka (topic partitioned by channel_id)
▼
Fan-out Service ──> Pub/Sub ──> Gateways ──> Clients
Write path:
- The gateway authenticates the session and forwards the message to the Message Service.
- The Message Service checks permissions against a cached bitmask in Redis.
- The request routes to the sequencer owning
channel_id. The sequencer atomically assigns the nextseqand generates a Snowflakemessage_id. - The message is durably persisted — a Cassandra quorum write, or Kafka with
acks=allas source of truth and a consumer materializing into Cassandra. - Only after the durable write succeeds does the server send
MESSAGE_ACK. This is what "durability first" means in practice. - A fan-out event is published asynchronously. Delivery is decoupled from persistence so a slow subscriber never blocks writes.
Routing to online users:
- Each gateway subscribes to pub/sub topics for the guilds or channels its connected users belong to.
- The fan-out service publishes once per gateway, not once per user. Each gateway then pushes to its local sockets.
- A session registry in Redis maps
user_id→gateway_idfor direct messages and targeted events.
Offline and reconnect sync:
- On
RESUME, the client sendslast_seqper open channel. - If the gap is small, the gateway replays missing messages from Kafka or a recent-message cache.
- If the gap is large (user was offline for hours), the server sends only unread counts. The client lazily pulls history via
GET ...?after=seqwhen the user opens that channel.
This push-for-active, pull-for-stale split prevents reconnect storms from replaying gigabytes of data.
5. Strict Per-Channel Ordering
Wall-clock timestamps fail because clocks skew across machines. Snowflake IDs are roughly time-ordered but two generators can interleave within the same millisecond. For strict ordering:
- Single sequencer per channel. Partition channels across sequencer nodes with consistent hashing, or place them on Kafka partitions keyed by
channel_id. The owner incrementsseqatomically. A Kafka partition already provides a total order, so its offset can serve as the sequence. - Failover with fencing. Channel ownership is a lease (etcd/ZooKeeper) carrying a fencing epoch. A new owner reads
max(seq)from storage before issuing new numbers. A stale owner's writes are rejected because its epoch is outdated. - Clients render by
seq, not arrival order. If a client receives seq 105 while holding 103, it detects a gap and fetches 104 before displaying. - The Snowflake
message_idremains useful as a globally unique, roughly sortable key for DMs, links, and search indexing.
6. Key Trade-offs
- Per-channel sequencer vs. leaderless writes: The sequencer adds a hop and a per-channel throughput ceiling, but ordering becomes simple and verifiable. Acceptable because nearly all channels are low-traffic. Hot channels can be special-cased with partitioned sub-channels if needed.
- Cassandra vs. SQL for messages: Cassandra provides linear write scaling and cheap range reads, but secondary queries are weak. Full-text search is offloaded to Elasticsearch via a Kafka consumer.
- At-least-once delivery plus client-side dedup (nonce + seq) is far simpler than trying to achieve exactly-once across the entire delivery path. The idempotency key absorbs duplicate deliveries transparently.
Common Mistakes
- Acknowledging the sender before the durable write completes — a crash between ack and persist loses the message.
- Fanning out directly from the write path — a slow subscriber backs pressure onto writes and spikes latency.
- Using timestamps for ordering — clock skew makes them unreliable across machines.
- Replaying full history on every reconnect — works for short gaps but causes thundering-herd load when many clients reconnect simultaneously after an outage.