Part 5 · Blueprint 24
Real-Time Distributed Chat System
16 min reading · Sources · Editorial review pending
A live socket acknowledgment is not the same as durable acceptance or recipient reading.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: Message Queues & Event Streams: Kafka vs. RabbitMQ, Database Sharding & Consistent Hashing, Idempotency Keys & Distributed Retries, Time, Clocks & Distributed Ordering: Lamport to TrueTime.
Sixty-second mental model
Problem: A live socket acknowledgment is not the same as durable acceptance or recipient reading.
Use: Persist message identity and support replay after reconnect.
Design boundary: Support private conversation messages, offline catch-up and live delivery. Persist conversation order before claiming durable acceptance; socket delivery is an observation, not the durable history. Exclude voice/video and unlimited group fan-out from the first design.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing distributed chat. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one message means and which component owns the conversation history.
Think of a post office with live couriers and retained mailboxes. Separate the requester from conversation history, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Long polling
- A request held until an update arrives or a waiting limit expires. Analogy: Asking the clerk to wait for news before answering.
- Polling
- Repeated client requests to discover whether state has changed. Analogy: Asking the front desk for updates at intervals.
- SSE
- Server-sent events: a text event stream from server to client over HTTP. Analogy: A live announcement feed sent in one direction.
- WebSocket
- A protocol providing a persistent bidirectional message channel after establishment. Analogy: An open phone line both sides can speak on.
Architecture and worked reasoning
Design boundary: Support private conversation messages, offline catch-up and live delivery. Persist conversation order before claiming durable acceptance; socket delivery is an observation, not the durable history. Exclude voice/video and unlimited group fan-out from the first design.
Responsibilities on the request path
Domain interface and access patterns
POST /conversations/{id}/messages → message_id, sequence; GET /conversations/{id}/messages?after_sequence=N → committed suffix
messages(conversation_id, sequence, client_message_id, sender_id, body_ref); UNIQUE(conversation_id, sequence) and UNIQUE(conversation_id, sender_id, client_message_id). memberships controls access; device_cursors track delivery/read evidence separately from the durable log.
Workload and limiting resource
Hypothetical 200,000 simultaneous sockets at 20 KB of selected connection state require 4 GB before buffers and runtime overhead. If 50,000 senders each send once per 20 seconds, ingress is 2,500 messages/s. With four recipients/message, fan-out is 10,000 deliveries/s; at 1 KB payload that is 10 MB/s before protocol overhead. A single large group violates the average-recipient model.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Authorize membership and bind a client message identity.
- Assign conversation sequence and append the durable message.
- Route notifications to the current connection locations after commitment.
Observation and recovery path
- Reconnect with a conversation cursor.
- Read the missing committed sequence interval.
- Merge live events with catch-up by sequence, deduplicating overlap.
Failure that changes the decision
Hypothetical scenario: A gateway dies after the durable append but before receipt acknowledgement. The sender retries the same client identity and the receiver catches up from its last committed cursor, preventing a duplicated message or permanent delivery gap.
Attempt this decision before reading the explanation
Can online presence determine whether a message must be persisted?
No. Presence can be stale, a socket can fail immediately after routing, and multiple devices may disagree. Keep durable history independent of the live route and define separate sent, delivered-to-device and read-by-person states.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
In short. A live socket is a delivery path, not the chat history. Commit one logical send, fan it out asynchronously, and let authorized devices catch up from a durable position.
A socket write can succeed locally while the peer disconnects before processing it. A server can receive a frame and crash before durable storage. Presence can remain stale after a lost connection. These are ordinary partial failures, not unusual exceptions to add after the happy path.
RFC 6455 specifies WebSocket handshake and framing for a persistent communication channel. It does not establish the application's durable history, deduplication, membership policy or offline synchronization. Polling and sockets can both serve a sound application contract; choose transport from latency, connection and operational requirements.
Do not use a connection identifier as the identity of the human, message or conversation. A person can have several devices and connections, while one logical send can have several attempts. Losing a connection must not erase the operation identity needed for reconciliation.
Route each conversation to an authoritative write boundary. Authenticate the sender, validate current membership and atomically assign a conversation sequence with the accepted message. Preserve the client operation identifier so a repeated send returns the existing logical result instead of appending another message.
After commit, fan-out notifies connected devices. A missed notification is recoverable because the authoritative log remains available. A reconnect request supplies its last confirmed sequence and fetches a bounded next page. Do not advance the device cursor merely because a gateway attempted delivery.
For Northwind’s initial support service, a Postgres transaction can bind a client send identity to one accepted conversation sequence. Redis can hold disposable presence or connection hints, but those hints do not replace the durable conversation history. At the scaled workload below, conversation-owned storage partitions need measured capacity and a recovery plan; the design does not claim that one Postgres instance serves the entire exercise.
Keep gateways responsible for authenticated connections and owners responsible for accepted history. Publish fan-out intent after the durable commit and make repeated deliveries recognizable by message identity. A slow offline device then consumes recovery budget rather than holding the sender’s commit open indefinitely. The per-conversation owner is also the place to define membership changes relative to new messages.
Hypothetical scaled planning scenario. Northwind is a fictional 40-person business; this is a capacity exercise for its chat architecture, not a claim about current users. Choose 100 million daily active users, each sending 50 messages per day. Accepted logical messages total 100,000,000 × 50 = 5,000,000,000 per day. Dividing by 86,400 seconds gives approximately 57,870 messages/s on average. A chosen peak multiplier of three gives about 173,611/s, rounded to 174,000/s for planning. The multiplier is an assumption.
At a chosen 500 bytes of message payload and metadata, daily logical growth is 5,000,000,000 × 500 = 2,500,000,000,000 bytes, or 2.5 decimal TB. Thirty days retain 2.5 × 30 = 75 TB. Three full payload copies retain 75 × 3 = 225 TB. Indexes, replication logs, backups, attachments and physical allocation are additional. These byte counts establish neither database throughput nor the number of machines.
Suppose each accepted message needs delivery to ten recipient devices. Daily delivery opportunities are 5,000,000,000 × 10 = 50,000,000,000. Peak fan-out under the same chosen multiplier is about 173,611 × 10 = 1,736,110 device deliveries/s before retries. A large conversation can concentrate that work on one owner even when unrelated conversations are distributed evenly.
Choose a reconnect wave involving 1% of the daily active users, modeled here as one million devices. Each lacks 40 messages, so catch-up requires 1,000,000 × 40 = 40,000,000 message transfers. At 500 bytes each, payload is 20,000,000,000 bytes = 20 GB. Transferring this in a chosen 100-second recovery window requires an average 20 GB ÷ 100 = 200 MB/s, before transport and authorization overhead.
Choose one authorized catch-up stream per device and a page capacity of 100 messages. Each device missing 40 messages needs ceil(40 ÷ 100) = 1 page; unused page capacity cannot be filled with another device’s response. The wave therefore requires 1,000,000 × 1 = 1,000,000 device-facing page requests. Meeting the same 100-second target requires 1,000,000 ÷ 100 = 10,000 successful pages/s alongside live work. At a separately chosen mean page-slot holding time of 0.2 seconds, stable average occupancy is 10,000 × 0.2 = 2,000 slots. A pool size alone is not proof that storage, network or membership checks can sustain the target.
For one conversation within that workload, suppose durable sequence 120 exists and a device last confirmed 117. The missing range is 118 through 120, containing 120 − 117 = 3 messages. The cursor locates history; current membership decides whether the device may receive it. Advance the cursor only after the defined delivery acknowledgement, so a lost notification can be replayed without losing durable history.
Slack’s Flannel engineering report describes loading less user and channel information at startup and fetching details on demand through an application-level edge cache. It also describes using cached startup information to reduce backend pressure during reconnects. The case shows that connection recovery involves metadata demand as well as message bytes.
The report discusses moving additional event fan-out toward the edge as future work at that time. Treat that distinction as part of the evidence: an announced next step is not a completed feature in the described system. Northwind can investigate whether startup metadata dominates its own reconnect path without copying Slack’s implementation or claiming its reported scale.
Per-conversation order is often sufficient. A universal order across unrelated conversations adds coordination without necessarily helping users. Client timestamps can describe local composition time, but they do not safely assign one authoritative order across disconnected devices.
Edits and deletions should identify the target message and a version or ordered event. The display can derive current state while retaining an appropriate audit history. Decide what deletion means for offline copies and notifications already delivered; the server cannot retroactively erase what a recipient has seen.
Presence is deliberately weaker state. An expiry or heartbeat policy can estimate whether a device appears connected, but should not authorize business actions or establish that a person is reading. Resource recovery and user meaning need different indicators.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Persistent bidirectional channel | Supports server and client messages on one live connection. | Reconnect, gateway ownership and missed-message recovery remain necessary. |
| Request-based update retrieval | Fits occasional updates and existing HTTP infrastructure. | Polling frequency trades freshness against repeated request work. |
Recovery decision
Hypothetical scenario: A gateway dies after the durable append but before receipt acknowledgement. The sender retries the same client identity and the receiver catches up from its last committed cursor, preventing a duplicated message or permanent delivery gap.
No. Presence can be stale, a socket can fail immediately after routing, and multiple devices may disagree. Keep durable history independent of the live route and define separate sent, delivered-to-device and read-by-person states.
Write your design before revealing the review
Can online presence determine whether a message must be persisted?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
No. Presence can be stale, a socket can fail immediately after routing, and multiple devices may disagree. Keep durable history independent of the live route and define separate sent, delivered-to-device and read-by-person states.
A gateway dies after the durable append but before receipt acknowledgement. The sender retries the same client identity and the receiver catches up from its last committed cursor, preventing a duplicated message or permanent delivery gap.
Check your understanding
Can online presence determine whether a message must be persisted?
No. Presence can be stale, a socket can fail immediately after routing, and multiple devices may disagree. Keep durable history independent of the live route and define separate sent, delivered-to-device and read-by-person states.
How would you recover from this failure: A gateway dies after the durable append but before receipt acknowledgement. The sender retries the same client identity and the receiver catches up from its last committed cursor, preventing a duplicated message or permanent delivery gap.
Start with the exact boundary that failed. Authorize membership and bind a client message identity. Assign conversation sequence and append the durable message. Route notifications to the current connection locations after commitment. Then recover evidence through the observation path: Reconnect with a conversation cursor. Read the missing committed sequence interval. Merge live events with catch-up by sequence, deduplicating overlap. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical 200,000 simultaneous sockets at 20 KB of selected connection state require 4 GB before buffers and runtime overhead. If 50,000 senders each send once per 20 seconds, ingress is 2,500 messages/s. With four recipients/message, fan-out is 10,000 deliveries/s; at 1 KB payload that is 10 MB/s before protocol overhead. A single large group violates the average-recipient model. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Support private conversation messages, offline catch-up and live delivery. Persist conversation order before claiming durable acceptance; socket delivery is an observation, not the durable history. Exclude voice/video and unlimited group fan-out from the first design.
Which component in this topology could be removed from a smaller first deployment?
Socket gateway, Conversation owner, Message log, Delivery router name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Authorize membership and bind a client message identity.
What evidence must a caller have before relying on the observation path?
Reconnect with a conversation cursor. Read the missing committed sequence interval. Merge live events with catch-up by sequence, deduplicating overlap. No. Presence can be stale, a socket can fail immediately after routing, and multiple devices may disagree. Keep durable history independent of the live route and define separate sent, delivered-to-device and read-by-person states.
45-minute interview rubric
- 00–05: scope message and conversation history.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw conversation history, numbered writes and reads.
- 28–40: challenge recovery: Persist message identity and support replay after reconnect.
- 40–45: defend conversation_id placement, observations and remaining assumptions.
Go deeper
- RFC 6455: The WebSocket Protocol · Primary document · www.rfc-editor.org. Persist message identity and support replay after reconnect. Verified 2026-10-26.
- Flannel: An Application-Level Edge Cache to Make Slack Scale | Engineering at Slack · Primary document · slack.engineering. Persist message identity and support replay after reconnect. Verified 2026-10-26.
Decision log
Persist message identity and support replay after reconnect.
Preserve message identity and conversation history ownership.
Revisit changed workload, observations or recovery objectives.