Design Live Comments

How to design live comments on a video stream: delivering each comment to millions of viewers, sampling busy streams, ordering, and reconnecting viewers.

Case study25 minLesson 7 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

Live comments let viewers of a live video post short messages and see everyone else's messages appear next to the video within a second or two. A viewer who joins late also sees the most recent comments. Each comment is small and cheap to store, but it has to be delivered to every viewer of that video, and on a popular stream that means millions of open connections.

The difficulty is on the delivery side: finding which servers hold viewers of a given video, and keeping the work bounded when thousands of people post at once. The steps follow A Framework for Any Design. Try each "Your turn" box before reading on.

Clarify the problem

The first five minutes
Interviewer

Design live comments for a video streaming platform.

You

Is this only for live streams, or also for recordings? And does every viewer need to see every comment, or is a readable stream enough?

Interviewer

Live streams only. A readable stream is enough, because nobody can read thousands of comments a second.

You

How many viewers are there at peak, how large is the biggest single stream, and how often does a viewer comment?

Interviewer

There are 50 million viewers at peak and up to 5 million on one stream. A viewer comments about once every 10 minutes, which adds up to about 2 billion comments a day.

You

Then delivery is the main design problem. I will store every comment, but on a busy stream I will show viewers a sample. A viewer may miss a comment while reconnecting but should never see one twice.

  • Functional: a viewer can post a comment, see new comments as they arrive, see recent comments when joining, and scroll back.
  • Non-functional: a comment is shown within 2 seconds, every comment is stored durably, one video can have up to 5 million viewers, no comment appears twice on a screen, and a failure in the comment panel never affects video playback.
  • Out of scope: replies, likes, recordings, and moderation tools beyond a basic text filter.

Estimate the scale

  • At peak, 50 million viewers each comment once every 600 seconds, which is about 83,000 comments a second across all videos.
  • On the biggest video, 5 million viewers give about 8,300 comments a second.
  • Storage is 2 billion comments × 200 bytes = 400 GB a day, or about 146 TB a year before replication.
Estimate: Naive fan-out on the biggest video

If every comment on the biggest video were sent to every viewer of that video, how many deliveries per second would that be?

You know
  • 5 million viewers on the video
  • Each viewer comments once every 10 minutes

Show the working
  1. Comments: 5,000,000 ÷ 600 s ≈ 8,300 a second
  2. Deliveries: 8,300 × 5,000,000 ≈ 4 × 1010, about 40 billion a second

Estimate 40 billion/s (anything from 10 billion/s to 100 billion/s is a good answer)

Nobody can read 8,300 comments a second, so the design shows a capped sample instead.

Suppose the design shows at most 10 comments a second per video and sends each viewer one batch every 500 ms. The biggest video then needs 5 million viewers × 2 batches = 10 million small messages a second. Spread over 1,000 realtime servers, that is 10,000 messages a second per server, and it no longer depends on how fast people type. The 1,000 servers come from 50 million viewers ÷ 50,000 connections per server, an assumption you would confirm with a load test.

Your turn: Define the API

Write the calls to post a comment, to receive new comments, and to load older comments. Which transport carries new comments to the viewer?

Compare with a model answer

Posting is a plain HTTP request, new comments arrive on a server-sent events stream that resumes from the last event id, and older comments are a paged read with a cursor.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP and SSE
POST /videos/{id}/comments          body: { "text": "what a goal",
                                            "request_id": "r-51f" }
  201 { "comment_id": "7193...", "created_at": "..." }
  400 empty or too long   403 blocked or muted
  404 not live            429 posting too fast
 
GET /videos/{id}/live               Accept: text/event-stream
                                    Last-Event-ID: 4121 (on reconnect)
  id: 4122
  data: { "comments": [ { "comment_id": "7193...", "user": "ana",
                          "text": "what a goal" }, ... ] }
 
GET /videos/{id}/comments?before=7193...&limit=50
  200 { "comments": [...], "next_before": "7101..." }

If the client retries a post after a timeout, the same request_id makes the server return the first comment instead of creating a second one. The transport for new comments is covered in the deep dives.

History is paged with a cursor, meaning "the 50 comments before this comment id", and not with an offset. At 8,300 new comments a second, an offset would skip or repeat comments, because "page 2" changes between requests.

Your turn: Model the data

What is the key of a comment, and how do you read "the 50 comments before this one" on a video that receives thousands of comments a second?

Compare with a model answer

Partition by video and a time bucket, and sort by a time-ordered comment id, so that reading history is one range scan from newest to oldest.

Model the data

Records
comments                       -- wide-column store, about 200 B a row
  video_id     BIGINT
  bucket       INT             -- time bucket, sized per video
  comment_id   BIGINT          -- time-ordered 64-bit id
  user_id      BIGINT
  text         VARCHAR(200)
  status       TINYINT         -- visible | removed
  PRIMARY KEY ((video_id, bucket), comment_id DESC)
 
recent:{video_id}              -- in-memory list of the last 200 shown
  [ { seq, comment_id, user, text }, ... ]

Comments are only appended, reads ask for the newest N comments before an id, and nothing needs a join. That access pattern suits a wide-column store such as Cassandra, which is built for heavy writes, and a time-ordered id gives newest-first order without a separate index.

The bucket limits the size of each partition. A quiet stream can use one-hour buckets, but the biggest video writes about 8,300 × 3,600 ≈ 30 million rows, or 6 GB, an hour into one partition, which is too much. Busy videos therefore use one-minute buckets of about 500,000 rows and 100 MB.

Your turn: High-level design

Sketch the path from a POST to storage and on to 5 million open connections. How does a comment find the servers that hold the viewers of its video?

Compare with a model answer

Store the comment and append it to a stream partitioned by video. A fan-out worker reads that partition, samples busy videos, and publishes to a pub/sub channel for the video, and every realtime server that holds a viewer of the video is subscribed to that channel.

High-level design

Storing and delivering are separate paths. The comment service makes a comment durable, and the fan-out path decides what is shown and to which servers it goes. The realtime servers only hold connections.

Comments are stored, then flow through a stream partitioned by video to fan-out workers, which publish a sampled feed to every subscribed realtime server.Viewers to Realtime servers (SSE); Viewers to Comment service (POST, history); Comment service to Comment store (insert); Comment service to Comment stream (by video id), asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments (last 200); Fan-out workers to Pub/sub (video:77); Pub/sub to Realtime servers (subscribed); Realtime servers to Recent comments (on join).ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersComment streamComment storeSSEPOST, historyinsertby video idlast 200video:77subscribedon join

request and replyasynchronous message

Comments are stored, then flow through a stream partitioned by video to fan-out workers, which publish a sampled feed to every subscribed realtime server.
Join, post, deliver, then a server diesUse the arrows or ← → keys
  1. Join, post, deliver, then a server dies, step 1Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serverssub video:77Comment servicePub/subRecent commentsFan-out workersComment streamComment store
    Ben's last id
    none

    1Ben opens video 77. His SSE request reaches realtime server R1, which has no other viewer of video 77, so R1 first subscribes to the channel video:77.

  2. Join, post, deliver, then a server dies, step 2Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsup to seq 4,121Fan-out workersComment streamComment store
    Ben's last id
    4121

    2R1 then sends Ben the last 50 comments from the recent list. Subscribing first means no comment falls between the two steps.

  3. Join, post, deliver, then a server dies, step 3Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersComment streamComment store
    Ben's last id
    4121

    3Ana posts "what a goal". The comment service checks her rate limit and assigns a time-ordered comment id.

  4. Join, post, deliver, then a server dies, step 4Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersComment streamComment storestored
    Ben's last id
    4121

    4The service stores the comment and returns 201.

  5. Join, post, deliver, then a server dies, step 5Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersComment streamComment store
    Ben's last id
    4121

    5The service appends the comment to the stream keyed by video id, so all comments of video 77 go to one partition and keep one order.

  6. Join, post, deliver, then a server dies, step 6Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersseq 4,122Comment streamComment store
    Ben's last id
    4121

    6The worker that owns that partition sees video 77 at 6 comments a second, which is under the cap of 10, so it keeps the comment as number 4,122 and adds it to the recent list.

  7. Join, post, deliver, then a server dies, step 7Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workersComment streamComment store
    Ben's last id
    4122

    7The worker publishes the comment to video:77. Each subscribed server adds it to its next 500 ms batch, so Ben sees it about a second after Ana posted it.

  8. Join, post, deliver, then a server dies, step 8Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversdownComment servicePub/subRecent commentsup to 4,126Fan-out workersComment streamComment store
    Ben's last id
    4122

    8R1 crashes and drops its 50,000 connections. Comments 4,123 to 4,126 are published meanwhile.

  9. Join, post, deliver, then a server dies, step 9Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversR2Comment servicePub/subRecent commentsFan-out workersComment streamComment store
    Ben's last id
    4126

    9Ben's browser waits a random few seconds and reconnects with Last-Event-ID: 4122. Server R2 is already subscribed and sends comments 4,123 to 4,126 from the recent list, so Ben misses nothing.

  10. Join, post, deliver, then a server dies, step 10Viewers to Realtime servers; Viewers to Comment service; Comment service to Comment store; Comment service to Comment stream, asynchronous; Comment stream to Fan-out workers, asynchronous; Fan-out workers to Recent comments; Fan-out workers to Pub/sub; Pub/sub to Realtime servers; Realtime servers to Recent comments.ViewersRealtime serversComment servicePub/subRecent commentsFan-out workerskeep 10 of 8,300Comment streamComment store
    posted per s
    8300
    shown per s
    10

    10At the final whistle video 77 jumps to 8,300 comments a second. All of them are stored, but the worker publishes only 10 a second, so pub/sub load stays almost unchanged.

1 / 10

Deep dives

Delivering comments to the browser

The viewer's browser needs new comments without asking for them each time. There are three ways to do this.

Polling means the browser asks every couple of seconds for comments newer than the last one it has. It is simple, but 5 million viewers polling every 2 seconds is 2.5 million requests a second for one video, and almost all of them return nothing new.

WebSockets keep one two-way connection open per viewer. They suit chat apps where the client sends a lot upstream, but here a viewer posts about once every 10 minutes, so the upstream half is almost never used.

Server-sent events (SSE) keep one long-lived HTTP response open, and the server writes events into it. They work through ordinary HTTP infrastructure, and browsers reconnect automatically and send the id of the last event they received, which lets the server resume the stream after a failure. Posting stays a normal POST. SSE is the choice for this design. Realtime communication compares the transports in more detail.

Routing a comment to the servers that hold the viewers

Viewers of one video are spread over many of the 1,000 realtime servers, and a comment arrives at an unrelated comment service. A comment on video 77 has to reach exactly the servers that hold viewers of video 77. There are three approaches.

Sending every comment to every realtime server needs no state, because each server simply ignores comments for videos it has no viewers of. The cost is 83,000 comments a second × 1,000 servers = 83 million internal messages a second, most of them thrown away.

A pub/sub channel for each video avoids that. A realtime server subscribes to the channel of a video when its first viewer of that video connects, and unsubscribes when the last one leaves. The fan-out worker publishes to the channel, and only subscribed servers receive the comment. This is the choice for this design. The cost is constant subscription changes.

Routing viewers by video id uses consistent hashing so that all viewers of a small video connect to the same one or two servers, and comments for it go there directly. The problem is that load becomes uneven and a viral video has to be spread over many servers anyway, so it only helps as an addition to pub/sub for small streams.

Each channel lives on one pub/sub node, chosen by hashing the video id, and that node knows its subscribers. When a realtime server dies, its subscriptions disappear with its connection. The biggest video is subscribed to by all 1,000 servers, which is acceptable with the cap: 10 comments a second × 1,000 servers is 10,000 messages a second from one node. Without sampling it would be about 8.3 million.

Limiting the comments shown on a very busy video

The biggest video produces 8,300 comments a second, which no viewer can read, so something has to decide which are shown. There are three options.

Sending everything is simple and hides nothing, but it produces about 40 billion deliveries a second, and the screen would scroll too fast to read. It is not possible at this size.

Slowing down posters, for example one comment per user every 30 seconds, reduces spam, but viewers post about once every 10 minutes anyway, so it removes almost nothing from the load. It is a moderation tool to use next to sampling.

Sampling at the fan-out worker caps what is published to 10 comments a second per video, whatever the posting rate. The stream is partitioned by video id, so exactly one worker sees all comments of a video and can measure its rate. Below 10 a second every comment passes. Above that, the worker always keeps comments from the creator and from moderators, drops exact repeats (3,000 copies of "GOAL" are mostly noise), and fills the remaining slots with a random pick from each 100 ms window. Posters see their own comment because their client shows it locally.

The cost is that on the biggest streams almost all comments are stored but never broadcast.

Handling a video with 8,300 comments a second
OptionGood atBad atPick it when
Send everythingSimple, and no comment is hidden.Unreadable for viewers, and about 40 billion deliveries a second.This cannot be used at this size.
Sample at the fan-out worker Usual defaultDelivery is capped at 10 comments a second per video, and everything is still stored.Most comments on a huge stream are never shown live.Use it for busy videos. This is my choice.
Slow mode for postersLess spam and less to store and filter.It limits people and not delivery, so a 30-second limit barely changes the load.Use it as a moderation tool alongside sampling.

Ordering, duplicates and gaps

Comment ids come from several servers whose clocks differ by a few milliseconds, so they are only roughly in order. The live order does not come from them. It comes from the single worker that owns the video, which numbers the comments it keeps 4,121, 4,122 and so on. Most pub/sub systems keep one publisher's messages on a channel in order, so every viewer sees the same sequence. Stored history is sorted by comment id and can differ from it by a few milliseconds.

Gaps happen because pub/sub stores nothing, so a restarted server misses messages. When a viewer reconnects, the server sends the comments after the viewer's Last-Event-ID from the recent list. The list keeps 200 comments, about 20 seconds at 10 a second, so a viewer who was away longer skips ahead.

Duplicates happen when a worker restarts and replays the stream from its last committed position, so a comment can be published twice. The client keeps the highest sequence number it has shown and ignores anything at or below it, which is where the guarantee of never showing a comment twice comes from.

Bottlenecks and failures

What breaks first at 10x

At 10x there are 500 million viewers and up to 50 million on one stream, which needs about 10,000 realtime servers. Outbound bandwidth is the first limit, because delivery cost grows with the number of viewers and not with the number of comments, so you add servers.

The hottest channel is then subscribed to by 10,000 servers, so its pub/sub node would send 10 × 10,000 = 100,000 messages a second. A few dozen relay servers between the node and the realtime servers share that work.

Storage grows to 4 TB a day, which is solved by adding nodes. The hottest video receives 83,000 writes a second into one partition, so you add a shard number from 0 to 15 to its partition key and merge the 16 results when reading history.

What happens when a component fails

When this failsWhat happensWhat you do
A realtime serverIts 50,000 viewers lose their comment stream, but the video keeps playing.Browsers reconnect after a random delay, about 1,700 a second over 30 seconds, and resume from Last-Event-ID.
A pub/sub nodeThe channels on that node stop delivering.Realtime servers resubscribe on the replacement node and fill any gap from the recent list.
A fan-out workerIts videos stop updating live, but their comments are still stored.Another worker takes over its partitions, resumes from the last committed position and continues numbering from the last sequence number in the recent list.
The recent-comments cacheJoining viewers see an empty panel, and gaps cannot be filled.Run replicas, and rebuild the list from the newest bucket in the comment store.
A comment store nodeWith 3 replicas and quorum writes, posting keeps working while 2 replicas of a partition are up.Replace the node. If a partition loses 2 replicas, posting returns 503 while viewers keep reading.

What a strong answer sounds like

LevelWhat the answer does
JuniorStores comments and lets clients poll. Needs a hint to see that the posting server and the viewers' servers differ.
Mid-levelChooses SSE or WebSockets and gives a reason, uses a pub/sub channel per video, and pages history with a cursor.
SeniorComputes the naive fan-out, agrees a display cap, samples at one worker per video, and explains where ordering and no-duplicate guarantees come from.
The hottest videoStrong answer
Interviewer

One stream has 5 million viewers and 8,300 comments a second. What breaks?

You

Sending everything would be about 40 billion deliveries a second, and no viewer can read 8,300 comments a second anyway. So the worker that owns the video caps the live feed at 10 comments a second. It keeps the creator's and moderators' comments, removes repeats and picks randomly from the rest, and every comment is still stored.

Interviewer

Won't people complain that their comment never appeared?

You

Their own client always shows their comment to them. On a stream that size, showing everything was never possible, so the real decision is which comments get priority.

Follow-up questions

How would comments replay along with a recording?

Store the offset into the video with each comment. During playback the client fetches the next minute of comments by offset and shows each at its moment, which is a normal cacheable read.

A moderator removes a comment that was already shown. What happens?

The comment is marked as removed in the store, and a small "remove 7193..." event is published on the video's channel. Clients delete it when they receive the event, and the recent list drops it so new joiners never see it.

How would you run this across several regions?

Give each region its own realtime servers and pub/sub, and have the video's worker publish once to each region, so a comment crosses the ocean once per region and not once per viewer.

How do you stop spam and abusive comments?

Rate-limit posting per user at the comment service and run a text filter before the comment is stored, which is why the post call can return 403 or 429. Accounts that are muted or blocked are rejected there, and moderators remove anything that still gets through using the removal event described above.

Self-review: live comments0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure