System Design Part 9 Design problems

Design Problem: A Chat System, Where Direct Messages and a 50,000-Person Live Chat Room Are Two Different Problems

Bill.Lin 17 min read

System Design series Part 9-3 | Previous: News Feed | Next: Flash Sale Ticketing | Series map

Read first: Part 5-5 Real-Time Updates.

Scenario and problem

The talk platform is adding two kinds of chat:

  1. Direct messages and small groups: an attendee and a speaker one on one, or a small group of a speaker and their teaching assistants. Messages must not be lost, the order must be right, the full history has to show up on another device too, and a push notification has to arrive while you are offline
  2. Live chat room: when a popular talk is streamed live, 50,000 viewers post in the same chat room. What viewers want to see is “what everyone is saying”, not every single message

The Real-Time Updates post handled “pushing changes on the server to the browser”: WebSocket, fan-out across servers, merging updates, slow clients. This problem goes one level further down, to the messages themselves: how to order them, how to keep them from duplicating, and how to catch up after being offline.

Scale estimate

Item Estimate
Direct messages 2 million daily active users, 10% of whom use direct messages, 20 messages each a day → 4 million messages a day, about 46 a second on average, about 500 at peak
Direct message storage About 300 bytes per message (body, conversation ID, sequence number, time) → about 1.2 GB a day, about 440 GB a year
Live chat room 50,000 viewers, 200 messages a second at peak
Live chat room, pushing each message 200 messages × 50,000 people = 10 million deliveries a second
Two kinds of chat, two hard parts1 / 5
Two kinds of chat, two hard partsAttendeeChat serviceSpeaker50k viewersLive chatMessage logAttendeeChat serviceSpeakermessagedeliveredNo loss, right orderChat serviceMessage logAttendeeSpeakersave historyHistory on a new devicePush when offlineAttendeeChat service500/s at peak50k viewersLive chat200 msgs/sPer-message push: 10M/s50k viewersWhat is everyone saying?
  1. Direct messagesAn attendee and a speaker chat one on one. Messages must not be lost, and the order must be right.
  2. New device, offlineThe full history has to show up on another device too, and a push notification has to arrive while offline.
  3. The volume of direct messages2 million daily active users, 10% of whom use direct messages, 20 messages each a day: about 500 a second at peak. The volume is small; the hard part is correctness.
  4. Live chat roomWhen a popular talk is streamed live, 50,000 viewers post in the same chat room, 200 messages a second at peak. Pushing every message to every person is 10 million deliveries a second.
  5. Viewers want the moodWhat viewers want to see is "what everyone is saying", not every single message. The live chat room's volume is huge; the hard part is fan-out.

Direct messages are low volume, and the hard part is correctness; the live chat room is huge volume, and the hard part is fan-out. The two should get different designs.

The simplest approach and its limits

Write messages into one table and sort them by created_at; when the WebSocket receives a message, broadcast it to everyone in the conversation who is online.

  • Timestamps cannot decide the order: when two servers’ clocks differ by tens of milliseconds, a message sent later can be sorted first; two messages in the same millisecond have no defined order
  • Resends create duplicates: a phone sends a message on the MRT, the network drops before the acknowledgment arrives, and after reconnecting it sends the message again; the other person sees two identical messages
  • Offline messages vanish: pushing only to online connections means that an offline device, when it reconnects, does not know what it missed
  • Live chat room: no group of servers has the network bandwidth for 10 million deliveries a second, and nobody can read 200 messages in one second anyway

Core mechanism

One increasing sequence number per conversation

The only basis for order is an increasing sequence number the server assigns within each conversation (seq):

  • Messages in the same conversation get their sequence numbers assigned in order by one place, so the order is well defined
  • Different conversations need no global order, so you need no global sequence generator (Distributed IDs post)
  • Sequence numbers are contiguous: when a client sees seq jump from 41 to 43, it knows it missed 42

How to assign them: increment the last_seq column of the conversation table with a conditional update. This makes writes to the same conversation queue up on the lock of the same row (Transactions and Isolation Levels post), but a direct message conversation never gets more than a few messages a second, so it is not a bottleneck at all. At 200 messages a second, the live chat room is not a good fit for this; it is handled separately below.

Client message IDs: resends do not duplicate

Before sending, the client generates a UUID for each message (client_msg_id), and the server puts a unique key on (conversation_id, client_msg_id):

  • First arrival: write it, assign a sequence number, reply with {client_msg_id, seq}
  • Resend: the unique key conflicts, so reply with the sequence number assigned the first time, without creating a new message

This is the Idempotency Key from the Idempotency post, only carried inside a WebSocket message. Until the acknowledgment arrives, the client shows the message as “sending”; once it arrives, the client moves the message to the right position by its sequence number.

Offline sync and unread counts

Each device remembers, for every conversation, the highest sequence number it has received. On reconnect:

  1. Fetch the conversation list, with each conversation’s current last_seq
  2. For every conversation whose last_seq is greater than the local record, request the messages after it with after= set to the local sequence number

Unread counts do not need a record of “who has read it” for every message: each member keeps just one last_read_seq per conversation, and unread count = the conversation’s last_seq − the member’s last_read_seq. Read receipts use the same column: if the other person’s last_read_seq is greater than or equal to a message’s sequence number, that message has been read.

Delivery: which server is the user connected to

An online user can be connected to any of the WebSocket servers, and the same person may have a phone and a computer open at the same time. The delivery flow:

sequenceDiagram
    participant A as Attendee (server 1)
    participant S1 as Server 1
    participant DB as Message database
    participant B as Message broker
    participant S2 as Server 2
    participant L as Speaker (server 2)
    A->>S1: Send message (client_msg_id)
    S1->>S1: Check conversation membership
    S1->>DB: Assign seq and write (same transaction)
    S1-->>A: Ack (client_msg_id, seq)
    S1->>B: Publish to the speaker
    B->>S2: The speaker's connection is on this one
    S2-->>L: Push message (seq)
    Note over L: When offline, the notification service sends a push instead
  • Write first, then acknowledge, then deliver: the acknowledgment means the message is already persisted, so even if delivery fails, the other person will sync it on reconnect
  • Routing across servers: you can maintain a “user → server” mapping yourself, or use a STOMP broker relay (such as RabbitMQ’s STOMP plugin) and let the broker deliver the message to the server the user is actually connected to
  • Delivery is at-least-once: the sync on reconnect can overlap with the real-time push, and the client deduplicates by sequence number
  • Offline push: when the other person has no online connection at all, hand the message to the notification service (Notification System)

Live chat room: not everyone needs every message

A 50,000-person chat room is a different product:

  • Messages need no strict global order, and not every message has to reach every person. What viewers see is “the latest messages scrolling by”
  • Each server pushes in batches: every 250 milliseconds, each WebSocket server packs the messages from that interval into one frame and pushes it to its own viewers; when there are too many messages, it samples only some of them (for example at most 5 per batch, with messages from the speaker, teaching assistants, and paying members shown first)
  • Fan-out estimate: 50,000 people × 4 frames a second = 200,000 frames a second; at about 1 KB per frame that is about 200 MB/s in total, or about 20 MB/s per server spread over 10 servers. Compared with 10 million per-message deliveries a second, that is two orders of magnitude less
  • The write path: a message goes first to the chat room’s Redis Pub/Sub channel, and every server subscribes to it and batches locally (the cross-server fan-out from the Real-Time Updates post). Messages are also written to storage asynchronously for replay and moderation, off the critical path of the push
  • Slow mode and moderation: each viewer can post at most one message every 3 seconds, links and keywords are filtered, and the speaker can mute people

Storage

  • Direct messages use (conversation_id, seq) as the primary key, so messages in the same conversation sit next to each other on disk, and “fetch the messages after a given sequence number” is a single range read
  • Shard by conversation_id (Sharding post): all messages of a conversation live on the same shard, and sequence numbers are assigned within that shard too
  • Write-heavy, read-light, and appended in time order, this also suits LSM-Tree databases (B-Tree vs LSM-Tree post); the live chat room has a large message volume, so its partition key should include a time bucket (for example (room_id, hour)) to keep any single partition from growing without bound

End-to-end encryption

End-to-end encryption keeps the server from reading message contents, but the cost is: no content moderation or reporting, no server-side search, and multi-device sync and key management get complicated. Direct messages on the talk platform have to handle harassment reports, and the live chat room needs real-time moderation, so the choice is encryption in transit plus encryption at rest, with the privacy policy stating the conditions under which the platform can access messages. This is a product decision, not a technical default.

Comparing options

Decision Direct messages Live chat room
Order An increasing sequence number per conversation The order each server receives messages in is enough
Delivery Every message is delivered, at-least-once, deduplicated by sequence number Batched pushes every 250 milliseconds, sampled when needed
Loss Not allowed: persist first, then acknowledge A small amount of loss is acceptable
Storage Sharded by conversation, kept permanently (subject to the retention policy) Written asynchronously, used only for replay and moderation
Offline Sync by sequence number on reconnect; offline push No catch-up; on rejoining, only the latest messages are shown

In Java

1. Tables

sql
CREATE TABLE conversation (
    id        BIGINT PRIMARY KEY,
    last_seq  BIGINT NOT NULL DEFAULT 0
);

CREATE TABLE conversation_member (
    conversation_id BIGINT NOT NULL,
    member_id       BIGINT NOT NULL,
    last_read_seq   BIGINT NOT NULL DEFAULT 0,
    PRIMARY KEY (conversation_id, member_id),
    KEY idx_member (member_id)
);

CREATE TABLE message (
    conversation_id BIGINT       NOT NULL,
    seq             BIGINT       NOT NULL,
    client_msg_id   BINARY(16)   NOT NULL,
    sender_id       BIGINT       NOT NULL,
    body            VARCHAR(4000) NOT NULL,
    created_at      TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    PRIMARY KEY (conversation_id, seq),
    UNIQUE KEY uk_client_msg (conversation_id, client_msg_id)
);

2. Sending a message: membership check, deduplication, sequence assignment

java
@Service
public class MessageService {

    private final JdbcClient jdbc;
    private final ApplicationEventPublisher events;

    public MessageService(JdbcClient jdbc, ApplicationEventPublisher events) {
        this.jdbc = jdbc;
        this.events = events;
    }

    @Transactional
    public SendAck send(long conversationId, long senderId, UUID clientMsgId, String body) {
        boolean member = jdbc.sql("SELECT COUNT(*) FROM conversation_member WHERE conversation_id = :c AND member_id = :m")
                .param("c", conversationId).param("m", senderId)
                .query(Long.class).single() > 0;
        if (!member) {
            throw new AccessDeniedException("Not a member of this conversation");
        }
        // Resend: reply with the sequence number from the first time
        Optional<Long> existing = jdbc.sql("SELECT seq FROM message WHERE conversation_id = :c AND client_msg_id = :id")
                .param("c", conversationId).param("id", toBytes(clientMsgId))
                .query(Long.class).optional();
        if (existing.isPresent()) {
            return new SendAck(clientMsgId, existing.get());
        }
        // Lock the conversation row and increment the sequence; writes to the same conversation queue up here
        jdbc.sql("UPDATE conversation SET last_seq = LAST_INSERT_ID(last_seq + 1) WHERE id = :c")
                .param("c", conversationId).update();
        long seq = jdbc.sql("SELECT LAST_INSERT_ID()").query(Long.class).single();
        jdbc.sql("""
                        INSERT INTO message (conversation_id, seq, client_msg_id, sender_id, body)
                        VALUES (:c, :seq, :id, :sender, :body)
                        """)
                .param("c", conversationId).param("seq", seq).param("id", toBytes(clientMsgId))
                .param("sender", senderId).param("body", body)
                .update();
        events.publishEvent(new MessageStored(conversationId, seq, senderId, body));   // delivered only after commit
        return new SendAck(clientMsgId, seq);
    }

    private static byte[] toBytes(UUID id) {
        return ByteBuffer.allocate(16).putLong(id.getMostSignificantBits()).putLong(id.getLeastSignificantBits()).array();
    }
}
  • LAST_INSERT_ID(expr) is a MySQL idiom: while updating, it records the new value on this connection, so the next SELECT LAST_INSERT_ID() returns the value just incremented, unaffected by other connections
  • The resend check comes before the sequence number is taken. In the edge case where two resends arrive at the same time, the second one hits the unique key on INSERT and rolls back; querying once more at that point is enough (omitted here)
  • When the write fails, the whole transaction rolls back and the sequence number rolls back with it, so the sequence never has gaps

3. Deliver after commit, with the broker routing across servers

java
@Configuration
@EnableWebSocketMessageBroker
public class ChatBrokerConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic", "/queue")
                .setRelayHost("rabbitmq.chat.internal")
                .setRelayPort(61613);
        config.setApplicationDestinationPrefixes("/app");
        // When the user is connected to another server, broadcast messages that cannot be resolved locally so the other servers can try
        config.setUserDestinationBroadcast("/topic/unresolved-user-destination");
        config.setUserRegistryBroadcast("/topic/simp-user-registry");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws").setAllowedOrigins("https://lectures.example.com");
    }
}

@Component
public class MessageDispatcher {

    private final SimpMessagingTemplate messaging;
    private final ConversationMembers members;
    private final OfflinePush offlinePush;

    public MessageDispatcher(SimpMessagingTemplate messaging, ConversationMembers members, OfflinePush offlinePush) {
        this.messaging = messaging;
        this.members = members;
        this.offlinePush = offlinePush;
    }

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void dispatch(MessageStored message) {
        for (String recipient : members.otherMembers(message.conversationId(), message.senderId())) {
            messaging.convertAndSendToUser(recipient, "/queue/messages", MessagePush.from(message));
            offlinePush.ifNoActiveSession(recipient, message);       // push only when there is no online connection
        }
    }
}
  • @TransactionalEventListener(AFTER_COMMIT): deliver only after the transaction commits, so a message that ends up rolled back is never pushed. If the process crashes after the commit but before delivery, the message is still in the database, and the other person will sync it on reconnect
  • Authorization for connections, subscriptions, and each message follows the approach in the Real-Time Updates post: messages to /app/** require login, subscriptions to private destinations outside /user/** are rejected, and the rules end with anyMessage().denyAll()

4. The sync API

java
@GetMapping("/v1/conversations/{id}/messages")
public List<MessageView> after(@PathVariable long id, @RequestParam long afterSeq,
                               @AuthenticationPrincipal Jwt jwt) {
    long me = CurrentMember.from(jwt).memberId();
    boolean member = jdbc.sql("SELECT COUNT(*) FROM conversation_member WHERE conversation_id = :id AND member_id = :me")
            .param("id", id).param("me", me)
            .query(Long.class).single() > 0;
    if (!member) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);       // not 403: do not reveal whether this conversation exists
    }
    return jdbc.sql("""
                    SELECT m.seq, m.sender_id, m.body, m.created_at
                      FROM message m
                      JOIN conversation_member cm ON cm.conversation_id = m.conversation_id AND cm.member_id = :me
                     WHERE m.conversation_id = :id AND m.seq > :after
                     ORDER BY m.seq
                     LIMIT 200
                    """)
            .param("me", me).param("id", id).param("after", afterSeq)
            .query(MessageView.class)
            .list();
}

A non-member gets 404, in line with the “404, not 403” principle from the Authorization post; the query still keeps the membership condition as a second line of defense. It returns at most 200 messages at a time, and the client continues from the sequence number of the last one.

The code above is written against the official documentation for Spring Boot 4.1, Spring Framework 7 (WebSocket/STOMP), and MySQL 8.4, and has not been compiled or run. ConversationMembers and OfflinePush are illustrative components.

Pitfalls and gotchas

  • Sorting by timestamp: clock skew and messages in the same millisecond make the order undefined
  • No client message ID: when the network is unstable, a resent message shows up twice
  • Push first, then write: the push succeeds, the write fails, and a message the other person has already seen disappears after a refresh
  • Recording every person’s read state for every message: the bigger the group, the more writes. Use one last_read_seq per person per conversation
  • Reusing the direct message design for the live chat room: the row lock on the sequence number and per-message pushes collapse at 200 messages a second and 50,000 people
  • Sending offline pushes to every device: the user is reading the conversation on their computer while their phone keeps popping up notifications. Push only when there is no active connection, or decide based on recent activity
  • Mass reconnects: when a server restarts, tens of thousands of clients reconnect and sync at the same moment, so you need reconnect backoff with jitter (Timeouts, Retries, Backoff, and Jitter)

Threat model

STRIDE Threat On the talk platform Defense
Spoofing Sending messages as someone else; cross-site WebSocket hijacking The senderId in a message comes from the client; a malicious site opens a WebSocket connection in the victim’s browser Take the sender from the connection’s identity; check Origin (Real-Time Updates post)
Tampering Editing someone else’s messages; forging sequence numbers The edit API only checks that you are logged in; a sequence number or time sent by the client is used as is Object-level authorization; sequence numbers and times are assigned only by the server
Repudiation A harasser denies having sent a message By the time of the report, the sender has already deleted the message “Delete for everyone” only hides the message, and the server keeps it for a period set by policy; audit logs for moderation actions
Information disclosure Reading conversations that are not yours; push content showing on the lock screen Changing the conversation ID to read someone else’s direct messages; the lock screen of the speaker’s phone shows the content of an attendee’s direct message Put the membership condition in every query and subscription; pushes show only “You have a new message” by default, and users can choose whether to show the content
Denial of service Message floods, huge messages, masses of connections Spamming the live chat room; a 10 MB message; opening WebSocket connections in bulk Slow mode and per-user rate limits; a message size limit; caps on connections per account and per IP (8-5)
Elevation of privilege XSS in messages; malicious attachments; SSRF through link previews Chat content rendered as HTML; an attachment that is malware Always escape as plain text; scan attachments and serve downloads through short-lived presigned URLs (Object Storage post); apply SSRF protection to previews

When to use it, and when not to

  • Build it yourself: chat is core to the product and needs deep integration with your existing accounts, permissions, and moderation workflow
  • Use an off-the-shelf service: chat is only an add-on feature. Message ordering, sync, push notifications, moderation, multiple devices: each one is more complicated than it looks
  • Design direct messages and large chat rooms separately: the two have completely different correctness requirements and scale, and sharing one design makes both of them worse
  • When to re-evaluate: when a single conversation’s write rate gets so high that the row lock on the sequence number becomes the bottleneck, have a single processor assign sequence numbers instead (for example a Kafka consumer partitioned by conversation ID)

References

Comments