Real-Time Chat for Mass-Audience Livestreams
System DesignModel answerLast updated
Design a chat feed for livestreams where one broadcast may have over a million viewers, with sub-half-second delivery, durable storage and live moderation.
Scenario
You are building the chat feature for a livestreaming product. During a popular broadcast, viewers type short messages that everyone else watching sees scroll by in near real time. A single stream can attract hundreds of thousands to over a million simultaneous viewers, and traffic can jump sharply when a well-known streamer goes live.
What the system must do
- A viewer can send a chat message to a stream they are watching.
- Every viewer sees a continuously updating feed of messages from the stream.
- The system absorbs a very large number of people posting at once.
Quality targets
- Speed: a message should reach viewers in under 500 ms.
- Scale: at least 100k simultaneous viewers on one stream, with room to grow beyond that.
- Durability vs. freshness: every accepted message must eventually be stored, but it is acceptable for a live viewer to miss an occasional update.
What you should cover
- A high-level architecture, and how its components interact.
- The API surface (WebSocket and/or REST).
- A data model for storing messages.
- How you deliver each message to a huge audience (the fan-out problem).
- How you moderate content in real time.
State your assumptions about traffic numbers and justify the trade-offs you make.
Hints
Hint 1
Multiply write rate by audience size. If 10k messages per second must each go to 1M viewers, the raw delivery count is absurd. Ask what a human can actually read, and what that implies for how much you send each viewer.
Hint 2
Separate the write path (accept, validate, make durable) from the delivery path (push to live viewers). Durability can be settled once the message is in a replicated log, without waiting on the database or on any viewer.
Hint 3
Fan-out should be a tree: one pub/sub publish reaches a modest number of edge gateways, and each gateway holds many sockets and does batching, sampling and per-viewer filtering locally.
Hint 4
Moderation should be layered: very cheap synchronous checks before accepting, slower ML or human review afterward, with a way to retract a message that has already been shown.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and sizing
Assumptions:
| Item | Value |
|---|---|
| Viewers, typical big stream | ~100k |
| Viewers, peak stream | 1M+ |
| Inbound messages | ~1k/s typical, 10k+/s at peak |
| Message size | ~200 B text, ~500 B with metadata |
| Post-to-screen latency | < 500 ms at p99 |
| Storage | Every accepted message persisted |
| Live push | Best effort |
| Ordering | Roughly chronological, no strict global order |
Key observation: 10k msgs/s × 1M viewers = 10 billion deliveries/s, which is infeasible and also useless, since nobody can read more than ~10-20 messages per second. So cap what each viewer receives (say 20 msgs/s) and send it in batches every ~200 ms. That is about 5 frames/s per viewer, or ~5M frames/s across a 1M-viewer fleet: large but spread across many gateway machines. Writes are the easy part; fan-out is the hard part.
2. APIs
Post a message (REST)
POST /v1/streams/{stream_id}/messages
{ "text": "...", "client_msg_id": "uuid" } // idempotency key
-> 202 { "message_id": "...", "created_at": ... }
REST keeps auth, rate limiting and retries simple, and client_msg_id makes retries safe.
History (REST, cursor-based)
GET /v1/streams/{stream_id}/messages?before={message_id}&limit=50
Live feed (WebSocket)
WS /v1/live?stream_id=...
server -> client: { "type":"batch", "seq":1042, "messages":[...] }
server -> client: { "type":"retract", "message_ids":[...] }
client -> server: { "type":"resume", "last_seq":1030 }
Why push instead of poll: 1M viewers polling every 2 s is 500k QPS, mostly empty, with 1-2 s staleness. A persistent connection pushes only when there is data. SSE also works since the live channel is one-directional; keep long-polling as a fallback for hostile networks.
3. Data model
A wide-column store (Cassandra-like) suits append-heavy, time-range reads.
messages
PRIMARY KEY ((stream_id, time_bucket), message_id DESC)
message_id time-sortable unique ID (snowflake)
user_id, text, created_at
status visible | hidden | deleted
mod_score float
time_bucket(e.g. 5 min) prevents one hot stream from creating an unbounded partition.- Time-sortable IDs give ordering without a central sequencer.
- A Redis capped list
recent:{stream_id}(~500 items) serves new joiners and reconnect backfill.
4. Architecture
Client -> API gateway -> Message Write Service -> Kafka (partition by stream_id)
(auth, rate limit, |
sync moderation) +---------+-----------+
v v v
Persist worker Async mod Distribution
-> Cassandra (ML) router / pub-sub
-> Redis recent | |
retracts Gateways 1..N
(~100k sockets each)
Write path: validate, run cheap synchronous moderation, produce to Kafka with acks, then return 202. Once the log has it, the message is durable. Persisting to the database is asynchronous and live delivery never waits on it.
Delivery path: distribution workers consume Kafka and publish to a per-stream channel. A gateway subscribes to a stream only if it has at least one viewer of it. This yields a two-level tree: 1 publish to N gateways, each to M sockets, so the pub/sub layer never sees individual viewers.
5. Fan-out in depth
- Audience partitioning: a load balancer sends each viewer to any gateway. A registry (in router memory or Redis) maps stream to gateways. A 1M-viewer stream over 10-20 gateways means each batch is sent only ~20 times by the router.
- Batching: each gateway buffers per stream for 100-200 ms, then writes one frame per socket.
- Throttling and sampling: if the rate exceeds the per-viewer cap, the gateway samples, prioritizing the streamer, moderators, friends or verified users, and high-engagement messages. Different viewers seeing different subsets is fine.
- Personalization at the edge: blocklists, language filters and always showing a viewer their own messages are applied in the gateway, so the upstream stream is identical for everyone.
Latency budget: write + moderation ~20 ms, Kafka 10-30 ms, router ~10 ms, gateway batching 100-200 ms, network 50-100 ms. Total comfortably under 500 ms.
Reliability: no per-message acks to a million clients. Each batch has a seq; on reconnect the client sends last_seq and the gateway backfills from Redis. Unnoticed gaps are acceptable. Handle gateway failure by letting clients reconnect with jittered backoff to avoid a thundering herd.
6. Real-time moderation
Layer it so the hot path stays fast.
- Synchronous (<5 ms): per-user and per-IP rate limits, banned-user checks, banned-term matching with an in-memory Aho-Corasick automaton, streamer-defined blocked words, and slow mode (e.g. one message per 10 s per user).
- Asynchronous ML: a classifier consumes the same Kafka topic in parallel, flags toxicity or spam within about a second, updates
status, and emits aretractevent that travels the same fan-out path so clients remove the message. - Human moderation: streamer and moderator deletes and bans also publish retract events, and a ban immediately blocks further posts at the write service.
Trade-off: stricter synchronous filtering reduces harm but adds latency and false positives; async review is more accurate but lets some bad content appear briefly. Retraction bridges that gap.
7. Common mistakes
- Proposing to push every message to every viewer, without computing the delivery count.
- Writing to the database before delivering, which puts storage latency on the live path.
- Using one partition per stream with no time bucketing.
- Demanding strict global ordering or exactly-once live delivery, which adds cost the product does not need.
- Having no reconnect or backfill story.
- Treating moderation as only a post-hoc batch job with no way to retract.
8. Possible follow-ups
Multi-region deployment (regional gateways, cross-region log replication), handling a stream that suddenly goes viral (autoscaling gateways, pre-warming), and shadow-banning (the author sees their message, nobody else does).