SteelReed

Search

Search posts, questions…

7. System Design

Designing a Discord-style chat system: WebSocket gateways, message storage and fan-out for huge servers

A worked solution to the exercise 'design a messaging system like Discord': requirements, estimates with the arithmetic, a WebSocket gateway, a message data model on ScyllaDB keyed by channel and time bucket, ordering with Snowflake ids, delivering to a server with a million members, presence, read states, reconnects, and how to present it in 45 minutes.

18 Nov 20267 min readSenior

–

My solution to the exercise that follows the news feed post: design a Discord-style messaging system. Unlike a feed, chat must deliver within a few hundred ms over always-open connections, keep order per channel and store history forever.

1. The problem

One @everyone message in a 1-million-member server with 100K members online. Fanning out per user means 100K internal messages for one message, while the system already delivers 700K times per second.

2. Key idea

Split the send path (REST, stateless) from the receive path (WebSocket, stateful). The expensive part isn't 35K writes per second but 700K deliveries per second (35K × 20 online readers) and 10M always-open connections (~200 gateway nodes, ~50K connections each).

Component Job
Gateway holds WebSockets, heartbeats, pushes events; no business logic
Message service checks permissions, issues message_id, writes the DB at QUORUM, publishes to Kafka by guild_id
Guild service sharded by guild_id; knows which node holds each online session of the guild
Session registry Redis session:{user_id} → gateway_node, TTL refreshed by heartbeats

2.1 Where do messages live?

Choice Use when Don't use when
PostgreSQL guilds, channels, roles, permissions: few writes, relational 330 TB/year, 100K writes/s: you'd shard by hand
ScyllaDB/Cassandra messages: write-heavy, read by channel and time you need joins or multi-row transactions
Partition by channel_id only a busy channel becomes a multi-GB partition within years

Add a bucket (a 10-day window derived from message_id) to the partition key to keep the busiest channel's partitions under ~100 MB.

2.2 Million-member servers, lost connections

  • Fan-out per node: 100K members across ~200 nodes is 200 messages carrying session lists.
  • Lazy presence: send presence only for members visible in the member list; typing only to people viewing the channel.
  • Read coalescing: when many clients load the same channel's history, a data service in front of the DB merges them into one query.
  • Disconnects: a few minutes away, resume with session_id + last sequence number; longer, GET ?after=<last id>. A gateway dies: 50K clients reconnect with jitter.

3. In Java

JAVA
// Snowflake: 41 bits of milliseconds | 10 bits machine | 12 bits sequence
synchronized long nextId() {
    long now = clock.millis() - EPOCH;
    if (now == lastMs) {
        seq = (seq + 1) & 0xFFF;
        if (seq == 0) now = waitNextMs(now);          // 4096 ids/ms/machine
    } else seq = 0;
    lastMs = now;
    return (now << 22) | (machineId << 12) | seq;
}
static int bucket(long messageId) {                   // 10-day window
    long ms = (messageId >> 22) + EPOCH;
    return (int) (ms / Duration.ofDays(10).toMillis());
}
// SELECT ... WHERE channel_id = ? AND bucket = ? AND message_id < ? LIMIT 50
// when a bucket runs out, step back one; clients sort by message_id, not arrival order

Other languages: gateways are often written in Go, Elixir or Rust to hold many connections per node; the design is the same.

The send path in detail
  1. The client sends POST /channels/{id}/messages with a nonce. The server remembers (user_id, nonce) → message_id for a few minutes: a resend returns the original.
  2. Return success only after ScyllaDB accepts the write at QUORUM. If publishing to Kafka fails after the write, other clients still see the message when loading history; for stronger guarantees use an outbox.
  3. The guild service filters out members who can't see the channel and sends one copy to each gateway node with recipients.
  4. Delivery is at least once: clients deduplicate by message_id.
  5. Offline users who were @mentioned or DMed get a push via APNs/FCM.

4. Working with AI

Give the AI: the estimation table, the CQL schema, a sequence diagram of the send path, a failure-mode table.

Check in the AI's design:

  • The partition key includes a time window, not just channel_id.
  • Ordering relies on message_id (Snowflake), not client clocks.
  • Fan-out is grouped per gateway node.
  • Sends carry a nonce; clients deduplicate by message_id.
  • There's a cursor-based catch-up path after long disconnects.

5. Exercises

Exercise 1: An AI-proposed design

The AI proposes a PostgreSQL table messages(id serial, channel_id, created_at, body) with an index on (channel_id, created_at); on each message the service publishes individually to every online member through Redis pub/sub channel user:{id}. Name three problems at 35K messages/s and 1M members.

Solution to Exercise 1
  • serial + created_at: a single id issuer bottlenecks sharding; two messages in the same millisecond have no stable order. Use Snowflake.
  • PostgreSQL for 330 TB/year: manual sharding, and a huge append-only table is hard to VACUUM. Use ScyllaDB partitioned by (channel_id, bucket).
  • Per-user fan-out: an @everyone becomes 100K publishes. Group by gateway node, only online members with permission.

Exercise 2: Offline for 3 hours

A phone loses network for 3 hours, then reconnects; the user is in 40 channels. What does the client do to miss nothing, duplicate nothing, and not flood the server?

Solution to Exercise 2

It's past the resume window, so open a new session. Catch up only the open channel with GET /channels/{id}/messages?after=<last_message_id>; other channels need only unread counts (compare read_states with each channel's last_message_id) and load when opened. Snowflake as cursor means nothing is missed; deduplicating by message_id means no duplicates. Reconnect with jittered backoff.

Summary

  • Send over REST with a nonce, receive over the WebSocket gateway.
  • Messages in ScyllaDB, partitioned by (channel_id, bucket).
  • Snowflake is both order and cursor.
  • Fan out per gateway node; lazy presence; coalesced reads.
  • Report success after a QUORUM write; clients deduplicate by message_id.

Read more: Designing a URL shortener.

Practice interview questions on this topic

All System Design questions →

Loading comments…
Next on the roadmapDesigning a notification system: push, SMS, email, per-channel queues, deduplication and frequency caps