Real-Time Chat Delivery for Live Broadcasts
System DesignModel answerLast updated
Design a low-latency comment system that fans out viewer messages to millions of concurrent watchers during a live video stream.
Real-Time Chat Delivery for Live Broadcasts
You are designing the chat feature for a live video streaming platform. During a broadcast, any viewer can send a short text message that all other viewers should see within a second or two.
What you need to support:
- Viewers send chat messages; every other viewer on that stream receives them quickly.
- A single popular broadcast can attract millions of simultaneous viewers.
- Broadcasters and moderators can remove or flag messages; removed messages must disappear for everyone.
- A viewer who joins mid-stream should see a recent backlog of messages.
- The system must enforce per-user send limits and a broadcaster-controlled "slow mode."
- Messages should appear in roughly chronological order.
Out of scope: advanced ML-based auto-moderation, full broadcaster dashboard tooling.
What is expected in your answer:
- Clarify requirements and estimate scale — writes, reads, and fanout numbers.
- Define a minimal API (send, fetch history, delete, flag, real-time channel).
- Sketch a data model with justification for your storage choices.
- Draw the high-level architecture, covering the write path and the live delivery path.
- Deep-dive at least three of the following: fanout strategy for hot streams, message ordering, moderation propagation, rate limiting, reconnect and replay.
- Call out trade-offs explicitly wherever you make a design choice.
Hints
Hint 1
Start with the math: figure out the write rate, then the fanout rate. The two numbers are very different and point at where the real problem lives.
Hint 2
Think about what 'delivery' actually means at scale — you don't need one connection per viewer in your core pub/sub layer. What intermediate layer eliminates the N² problem?
Hint 3
For a hot stream with thousands of messages per minute, no human can read that fast anyway. What does that unlock in terms of what you actually have to deliver to each viewer?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Functional requirements
- Post a message to a live stream; all viewers receive it in near real time.
- On joining, fetch the last N messages.
- Delete or flag a message; deletions must propagate immediately to all viewers.
- Per-user rate limiting and a broadcaster-configurable slow mode.
Non-functional requirements
- End-to-end delivery under ~1–2 s at p99.
- High availability; dropping a message for one viewer occasionally is acceptable. A message acknowledged to its sender must be durable.
- Approximate time ordering is sufficient — no global total order needed.
Back-of-envelope numbers
Assume 20M concurrent viewers across all streams, with one hot stream at 2M viewers. If 1% of viewers message per minute:
- Write rate for the hot stream:
2M × 0.01 / 60 ≈ 330 msg/s. Global writes are in the tens of thousands per second — modest. - Fanout rate:
330 × 2M ≈ 660M deliveries/sfor that one stream. This is the real problem. - No human can read 330 messages per second, so capping display at ~20/s and batching every 250 ms brings it to
2M × 4 = 8M frames/sacross gateway servers — achievable. - At ~100k persistent connections per gateway box, 20M viewers needs ~200 gateways with 2–3× headroom.
Key insight: this is a read-fanout problem, not a write problem. State this early.
2. API
POST /streams/{stream_id}/messages {text, client_msg_id} → {msg_id, ts}
GET /streams/{stream_id}/messages?before={cursor}&limit=50 → history page
DELETE /messages/{msg_id} (sender / broadcaster / mod)
POST /messages/{msg_id}/flag {reason}
WebSocket /live?stream_id=...&since={cursor}
server → client: {type:"batch", messages:[...]}
| {type:"delete", msg_id}
client_msg_id makes retries idempotent. The since cursor lets a reconnecting client fill any gap it missed.
3. Data Model
Messages table — wide-column store (Cassandra or equivalent)
| Field | Notes |
|---|---|
(stream_id, time_bucket) | Partition key; one bucket per minute prevents hot partitions |
msg_id DESC | Clustering key; Snowflake-style ID (timestamp + shard + seq) |
user_id, text, created_at | Core payload |
status | `visible |
flag_count | Incremented by flag calls |
A Snowflake ID sorts by time, needs no central coordinator, and doubles as the pagination cursor.
Recent buffer — Redis capped list per stream, holding the last ~200 visible messages. Serves joins and reconnects without hitting the DB.
Rate-limit state — Redis token bucket per user_id and per (user_id, stream_id).
4. High-Level Architecture
Client ──HTTPS──> Message Service ──> Rate Limiter (Redis)
│ validate, blocklist, assign Snowflake ID
├──> Messages DB (durable write, ack author)
├──> Recent Buffer (Redis list per stream)
└──> Pub/Sub broker (topic per stream_id, sharded)
│
┌─────────────┴─────────────┐
Gateway A Gateway B ... Gateway N (WebSocket / SSE)
│ fan out locally to connected viewers
viewers
Write path: authenticate → rate-limit check → cheap moderation → persist → return 200 to sender (optimistic local insert) → publish to topic.
Read path: on join, load recent buffer; open WebSocket to a gateway (load balancer maintains connection affinity); gateway subscribes to the topic on its first viewer for that stream.
5. Deep Dives
Fanout strategy
Never publish one message per viewer. The pub/sub layer delivers each event once per gateway that has at least one viewer of that stream — at most a few hundred copies, not millions. Each gateway then loops over its in-memory connection map.
A routing registry maps stream_id → set of subscribed gateways. A gateway unsubscribes when its last viewer for a stream disconnects. For extremely hot streams, insert a middle-tier relay so a single publisher isn't pushing to hundreds of gateways directly.
Trade-off: this adds a routing indirection layer, but the alternative — per-viewer delivery at the pub/sub layer — doesn't scale past tens of thousands of viewers.
Hot-stream sampling and batching
At 330 msg/s, install a per-stream aggregator between the message service and the gateways. Every 250 ms it selects up to K messages using priority: broadcaster and pinned messages first, then the viewer's followed accounts (resolved at the gateway), then a random sample. It emits one batch frame per tick.
Low-traffic streams skip sampling entirely.
Trade-off: viewers on a hot stream may not see every message in their chat window. All messages remain durable and visible in full history. Completeness is sacrificed for scalability and readability — and readability was already lost at 330 msg/s anyway.
Ordering
The Snowflake ID provides time ordering within a few milliseconds of clock skew. Clients sort by ID and render using a small reorder window; they don't block on gaps. A strict global total order would require a single sequencer per stream — a bottleneck with no practical user benefit.
Moderation propagation
Pre-publish: synchronous, cheap checks — blocklist words, banned users, link filters. Adds a few milliseconds.
Post-publish: flag counts increment in Redis. Past a configurable threshold, or on explicit moderator/broadcaster action, set status = deleted, remove from the Redis buffer, and publish a delete tombstone on the same topic. Gateways forward tombstones; clients remove the message from their local view. If the message never reached a client, the tombstone is a no-op.
A common mistake is only deleting from the DB and not propagating the tombstone — viewers who already received the message keep seeing it.
Rate limiting
Token bucket in Redis: for example, 1 message per 2 s per user per stream, burst of 3. Add a global per-user cap to stop cross-stream spam. Slow mode is a per-stream config the broadcaster adjusts at runtime. Enforce at the API layer; gateways additionally drop connections that are abusive at the transport level.
Reconnect and replay
A reconnecting client sends since=last_msg_id. The gateway checks the Redis buffer for the gap; if the cursor is found, it sends the missed messages and then resumes live delivery. If the gap is too old for the buffer, the client falls back to showing the most recent messages — perfect continuity is not a hard requirement. After the broadcast ends, full history is served from the DB, paginated by msg_id.
Common Mistakes to Avoid
- Conflating write scale with fanout scale and sizing the wrong bottleneck.
- Designing a direct pub/sub connection per viewer rather than a two-tier gateway model.
- Forgetting to propagate deletion tombstones to already-connected clients.
- Claiming strict global ordering is required — approximate time order is both sufficient and much cheaper.
- Using a single Cassandra partition per stream with no time bucketing — it becomes unbounded and causes hot partition issues within hours on a popular stream.