"Design live comments for Facebook Live" sounds like chat with more people in the room. Most answers treat it that way: a socket per viewer, a message per comment, and a plan to deliver every comment to every viewer. With a few hundred viewers that plan works. With five million viewers of one football match, it asks every phone to download about 10 megabits a second of text, scrolling past faster than anyone can read it.
The design starts from one observation. A person can read a handful of short comments a second. Past that, the list on screen turns into a blur, and sending more comments into it changes nothing the viewer can see. A viewer is owed a comment feed that looks alive, not a copy of every comment.
That sentence settles most of the decisions below. Delivery can be best effort, with no acknowledgements and no queue per viewer. A big stream can show a sample of its comments instead of all of them. Reactions can travel as counts. The order has to be the same for everyone, but it doesn't have to match the posting order to the millisecond. And a viewer who joins late sees the last few dozen comments, not the whole history.
Three things stay exact, and the design keeps them off the sampled path. A poster always sees their own comment on the device they posted from. A removed comment disappears from every screen. And every accepted comment is kept, so the stream can be replayed and moderated later.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
A live stream has a video player and, beside it, a list of comments that scrolls upward. Hearts and other emoji float over the video when people react. Anyone watching can post a comment or tap a reaction, and everyone else watching sees it within a second or two.
Four different products get called "live comments", and they need different systems.
- Comments on a live broadcast. One streamer, a large audience, and comments as a side channel. Facebook Live, YouTube Live and Instagram Live work this way. This is the problem here.
- A chat room. Everyone is a participant, every message matters to someone, and history is kept. That is the WhatsApp and Chat Systems problem, where the server holds each message until a device confirms it.
- Comments on a post. Threaded, ranked, stored forever and read hours later. That is a feed problem.
- The video itself. Encoding and serving video frames is a problem for a content delivery network (CDN), covered in YouTube.
Twitch chat sits between the first two. A channel with 40 viewers behaves like a chat room, and a channel with 400,000 behaves like a broadcast. The design below handles both, and the line between them falls out of one number in the requirements.
Functional requirements
Core:
- Post a comment on a live stream, and have everyone watching see it within about 2 seconds.
- React with an emoji, and see the audience's reactions as they happen.
- Join a stream that is already running, and see the recent comments at once.
- Moderate: limit how fast one user can post, let moderators remove comments and ban users, and have a removal reach every screen.
Out of scope, deliberately:
- The video pipeline: ingest, encoding and the CDN that serves the video.
- Replaying comments in time with the recording after the stream ends. The archive built here makes it possible, but playback is a separate read path.
- Threaded replies, comment ranking, and paid comments such as YouTube's Super Chat.
- How the spam classifier decides. This design decides where the classifier sits, not what model it runs.
Non-functional requirements
- Scale: 50 million concurrent viewers at peak, across 500,000 live streams. The largest single stream has 5 million concurrent viewers. These are assumptions, sized for a large platform's busiest evening.
- Latency: a comment reaches other viewers' screens within 2 seconds at p99. A comment reacts to something on screen, and 2 seconds keeps it close to that moment.
- Each viewer receives at most 10 comments a second, however many are posted.
- Delivery to viewers is best effort. An accepted comment is stored durably, a poster sees their own comment at once, and a removal reaches every screen within 5 seconds.
- Reactions: at a peak moment, a big stream sees a couple of million taps a second.
Requirement 3 carries the design. Here is what the stream from requirement 1 costs with and without it.
The question is whether the delivery tier can send every comment to every viewer. Count the deliveries, then the bytes. Assume each viewer posts once every 10 minutes on average, and a comment is ~150 bytes with its author and ids. viewers 5M comments posted 5M / 600 s ≈ 8,300/s Every comment to every viewer deliveries 5M × 8,300 ≈ 41B/s per viewer 8,300 × 150 B ≈ 1.2 MB/s ≈ 10 Mbps whole stream 41B × 150 B ≈ 6 TB/s At most 10 comments a second per viewer deliveries 5M × 10 = 50M/s per viewer 10 × 150 B = 1.5 KB/s ≈ 12 kbps whole stream 50M × 150 B = 7.5 GB/s ───────────────────────────────────────────────────────── The cap cuts the stream's delivery cost about 800 times, and the only thing it removes is text nobody could read.
Ten megabits a second of comments is more than many phones get for the video. The cap isn't an optimisation added later. Without it, no amount of hardware makes the big stream work, so it belongs in the requirements, stated out loud.
For a small stream, the cap never applies. A stream with 2,000 viewers posts about 3 comments a second, every one of them is delivered, and the stream behaves like a chat room. The same design covers both cases, and the cap decides which one a stream is in.
The set up
Core entities
- Stream. A live broadcast, with its settings: slow mode, who may comment, and its moderators.
- Comment. Stream, author, text, a client-generated id, and a sequence number the server assigns.
- Reaction count. How many of each emoji a stream received in one second. A single tap is never stored.
- Viewer connection. A held connection from one viewer to one gateway server, for one stream. This is the only interesting entity. There are 50 million of them, they come and go all evening, and where they sit decides the cost of every comment.
- Moderation state. Bans per stream, and the rate limits per user.
How does a comment reach a viewer at all?
Pick the transport before the interface. The traffic is lopsided: a viewer receives up to 10 comments a second and sends one every few minutes. So the question is how to get frames down to 50 million screens cheaply.
Short polling. The viewer asks for new comments on a timer. To stay inside 2 seconds at p99, it has to ask about once a second. That is 50 million requests a second, and on a quiet stream most of them return nothing.
Long polling. The viewer asks, and the server holds the request until something arrives. Each batch of comments then costs a full HTTP request and response, with headers, twice a second per viewer on a busy stream.
Server-sent events (SSE). The viewer makes one HTTP request, and the server keeps the response open and writes events into it. Nothing goes up the connection after the request.
WebSocket. One connection carries frames both ways, after an upgrade from HTTP.
The question is whether the upstream traffic needs its own
socket. Count both directions for one viewer on a busy stream.
Down
comment batches 2 a second, ~5 comments each
frame size 5 × 150 B + reactions + framing ≈ 900 B
per viewer 2 × 900 B ≈ 1.8 KB/s
Up
comments one every 10 minutes ≈ 0.002/s
reactions one batched count every 2 s,
only while the viewer is tapping ≤ 0.5/s
─────────────────────────────────────────────────────────
Down is a steady stream. Up is a comment every few minutes,
plus a small count every 2 seconds while the viewer taps.
Ordinary HTTP requests carry that fine.Take SSE for the downstream. It is plain HTTP, so it passes through the proxies and load balancers that already carry the rest of the site's traffic. Each event carries an id, and the SSE standard defines Last-Event-ID, the id of the last event a client received, so resuming after a drop has a standard shape. LinkedIn runs its live likes on SSE, and its engineers said SSE had never failed for them where WebSockets were sometimes blocked by firewalls. Facebook's public Live Video API offers live comments over SSE as well.
The upstream goes as ordinary POST requests. Over HTTP/2, many requests share one TCP connection, so a POST to the same host as the SSE stream opens no new connection and costs a few frames. That host is the viewer's gateway. It answers reaction POSTs itself, as high-level design 2 shows, and passes comment POSTs on to the comment service.
WebSocket is a fair answer too, and Twitch's chat edge speaks IRC (Internet Relay Chat) over WebSockets. It earns its place when the upstream is heavy, as in a chat room where most people talk. Here the upstream is a few requests a minute, so a two-way socket buys little. The WebSockets, SSE and Polling concept walks the full ladder.
System interface
GET /v1/streams/s_77/live?last_event_id=118204 the SSE stream, held open
Accept: text/event-stream
id: 118214
event: batch
data: {"comments":[{"id":"c_9fd2","seq":118210,"author":{"id":"u_41",
data: "name":"priya"},"text":"what a goal","client_id":"0f8e2c1a"}, ...],
data: "reactions":{"heart":41210,"laugh":3120},
data: "removed":["c_8f03"]}
POST /v1/streams/s_77/comments
{"client_id":"0f8e2c1a","text":"what a goal"}
→ 202 {"id":"c_9fd2"}
POST /v1/streams/s_77/reactions
{"counts":{"heart":4,"laugh":1}}
→ 204
Three details to note.
- The event id is a position in the stream's sequence. After a dropped connection, the app reopens the stream with
last_event_id=118204, and the gateway can send exactly the batches after it. It goes in the URL because the reconnect may go to a different gateway, and the browser'sEventSourcelets the app set no headers of its own. - Reactions are counts in both directions. The client sends "4 hearts in the last 2 seconds", and the server sends "41,210 hearts in the last second". No single tap ever crosses the network as its own message.
- The client names its own comment. The app draws the comment on screen as soon as it is posted, tagged with
client_id. When the same comment comes back in a batch, the app sees theclient_idand skips it. For retries, the comment service runsSET dedup:{s_77}:{u_41}:{0f8e2c1a} NX EX 60in Redis after its other checks pass and before appending. If the key already exists, the comment is a retry and is not appended again. If the append fails, the service deletes the key so the next retry can go through.
The three calls above are the data plane, at millions of calls a second. The control plane is streamers and moderators changing things: slow mode, bans, blocked terms, a few changes a minute across the platform. The two share nothing on the request path. A settings change is written to the data store and pushed to the comment servers, so a post never waits on a control plane call.
High-level design
1. Get one comment to everyone watching
Viewer connections land on gateway servers. A gateway holds tens of thousands of SSE connections, and keeps an in-memory table from stream id to the connections watching it. LinkedIn's frontends work this way, and LinkedIn fit about 100,000 connections on one machine. This design runs gateways at 80,000, leaving room to take on the viewers of a failed one.
A comment is accepted somewhere else, by a stateless comment service. So the question is how a comment for s_77 reaches exactly the gateways that hold viewers of s_77, and nothing else.
Every gateway reads every comment
Put every accepted comment on one Kafka topic, and have every gateway consume all of it and keep the comments for streams it serves. It is tempting because there is no subscription state at all. A new gateway starts reading and is ready.
The cost grows with the fleet. The platform posts about 83,000 comments a second, which is 50 million viewers each posting once every 10 minutes. With 750 gateways, that is 62 million messages read every second. Each gateway parses 83,000 comments a second to keep the handful its viewers watch. LinkedIn weighed the same design for live likes and rejected it, because each frontend has to consume every topic, and adding frontends stops helping.
One pub/sub channel per stream, subscribed by gateways
Each stream gets its own channel on a pub/sub tier, stream:s_77. When a gateway accepts its first viewer of s_77, it subscribes to that channel, once. When its last viewer of s_77 leaves, it unsubscribes. A comment is published to the channel once, and the pub/sub tier sends a copy to each subscribed gateway. The gateway looks up its table and writes the comment to every local connection watching s_77.
Redis pub/sub is the usual pick. Since Redis 7, sharded pub/sub (SSUBSCRIBE and SPUBLISH) sends a message only to the shard that owns the channel's hash slot, so capacity grows as shards are added. LinkedIn built the same shape with its own dispatcher nodes, which keep the subscription table in a shared key-value store.
This is the standard answer, and it works. Its cost is in the placement. The load balancer puts viewers on gateways at random, so a stream's viewers end up scattered. A stream with 50 viewers has about 50 gateways subscribed, each one serving a single viewer. For small streams, sending to gateways costs nearly as much as sending to viewers.
Place viewers by stream, so a stream touches few gateways
Question the premise that a viewer can land on any gateway. Before opening its SSE stream, the app asks a small connection router where to connect. The router hashes the stream id onto a ring of gateways, using consistent hashing, and answers with one gateway's hostname. Every viewer of a small stream then shares a gateway, and the stream costs one subscription.
A big stream can't fit on one gateway, so the router keeps a group for it. When every gateway in the group holds 80,000 viewers, the router adds the next free gateway, and new viewers are spread across the group. A gateway in a big stream's group takes no new small streams. A stream with 5 million viewers ends up on about 63 gateways instead of all 750.
The question is how much placement changes the internal fanout. Count comment copies, one per comment per subscribed gateway. Use an assumed mix of streams that adds up to about 50M viewers, each viewer posting once every 10 minutes. class streams viewers each comments/s (all streams) small 490,000 50 24.5M / 600 ≈ 41,000 medium 10,000 1,000 10M / 600 ≈ 16,700 large 100 100,000 10M / 600 ≈ 16,700 huge 1 5,000,000 5M / 600 ≈ 8,300 Random placement on 750 gateways small ~50 gateways each 41,000 × 50 ≈ 2.0M/s medium ~550 gateways each * 16,700 × 550 ≈ 9.2M/s large all 750 16,700 × 750 ≈ 12.5M/s huge all 750 8,300 × 750 ≈ 6.2M/s total ≈ 30M/s Placed by stream, 80,000 viewers per gateway small 1 gateway 41,000 × 1 = 41,000/s medium 1 gateway 16,700 × 1 = 16,700/s large 2 gateways 16,700 × 2 = 33,400/s huge 63 gateways 8,300 × 63 ≈ 523,000/s total ≈ 614,000/s * a gateway misses all 1,000 viewers with odds (749/750)^1000 ≈ 26%, so about 550 of 750 get one ───────────────────────────────────────────────────────── Placement cuts the comment copies about 50 times. What is left is almost all the one huge stream.
What you give up. Switching streams now means a new connection to another host, which costs a TCP and TLS handshake, about two round trips. The router is a new component, though its state is small: one ring and a group list for the hundred or so big streams. And load is lumpier. A stream that grows from 1,000 to 500,000 viewers in a minute fills its first gateway before the router widens the group, so the router has to watch fill levels every few seconds, not every few minutes.
The huge stream's 523,000 comment copies a second are still too many for one channel, which lives on one Redis shard. Deep dive 1 brings that line down by about 830 times.
Where does the order come from?
The comment service is a fleet of stateless instances, and two comments for s_77 can arrive on two of them at the same moment. If each instance published straight to the channel, viewers on different gateways could see the two in different orders. Something has to put each stream's comments in one line.
So the comment service doesn't publish. It appends the comment to a Kafka topic, comments, partitioned by stream id, and replies 202 once the append is acknowledged. All of a stream's comments land in one partition, in one order. Kafka is the right tool here because two different readers need the same comments: one delivers them now, and one stores them for later. The Message Queues vs Event Streams concept covers why a log fits that and a queue doesn't.
A stream worker consumes a set of partitions. For each stream it collects comments for half a second and publishes one batch to stream:{id}. An archive writer consumes the same partitions separately and writes comments to the data store. If the archive writer falls behind, nobody watching notices.
A comment's number is its Kafka offset, its position in the partition. The stream worker and the archive writer both read it from the log, so they agree without talking. A batch's id is how far the worker had read in the partition when the window closed, and each batch also carries the id of the stream's previous batch. Each gateway remembers the highest comment number it has sent for a stream and drops any comment at or below it. So a worker that restarts and reads part of the log again puts no duplicates on screen.
Which store, and what forces it
The archive serves replay after the stream ends, moderators looking up a user's history, and the rare backfill when no faster source has the comments. Nothing on the live path reads it.
The question is which store can hold the comments. Size the write rate and a year of storage. Assume the day averages half the evening peak, and a stored row is ~200 B with its keys and overhead. peak writes 50M viewers / 600 s ≈ 83,000/s average writes 83,000 / 2 ≈ 41,500/s per day 41,500 × 86,400 ≈ 3.6B comments bytes per day 3.6B × 200 B ≈ 720 GB per year 720 GB × 365 ≈ 260 TB with 3 replicas 260 TB × 3 ≈ 790 TB ───────────────────────────────────────────────────────── The write rate is high but steady. A year of storage, close to a petabyte with replicas, is what rules out one machine.
One Postgres table of comments
One relational database is where to start, because it gives indexes, ad hoc moderator queries and transactions for free. At 83,000 inserts a second at peak, a single primary is already working hard. The storage settles it: 260 TB a year can't sit on one machine, so you would be sharding Postgres by hand within months.
A wide-column store, partitioned by stream and minute
Use Cassandra, or ScyllaDB, which speaks the same protocol. It spreads writes across nodes by partition key and adds capacity one node at a time. Partition by (stream_id, minute), so one partition holds one minute of one stream, sorted by sequence. Replay reads one partition per minute in order. The archive writer batches its inserts, so the cluster sees a steady write load rather than bursts. This is what most teams run, and its cost is a cluster to operate for data that is read rarely.
Treat the archive as files, since nothing live reads it
Question the premise that the archive needs a database. Replay reads one stream from start to end, in order, and so does every other common read. So the archive writer can write one object per stream per minute to object storage such as S3, holding that minute's comments in sequence order. A small stream writes one object an hour instead, since its minute holds a handful of comments. Replay fetches the objects in sequence, and object storage costs much less per terabyte than a database cluster with three replicas.
What you give up: a removed comment can't be deleted from an object in place, so replay checks a small removed-comments table before it draws. Moderators need "every comment by this user", which files can't answer, so a small comments_by_user table is kept in a database alongside. Most designs should take the senior answer. The files answer wins when the archive grows into petabytes and replay is rare.
The tables
-- Cassandra (CQL). One partition is one minute of one stream.
CREATE TABLE comments (
stream_id text, minute timestamp, seq bigint,
comment_id text, author_id text, text text, client_id text,
PRIMARY KEY ((stream_id, minute), seq)
) WITH CLUSTERING ORDER BY (seq ASC);
-- A moderator's lookup: one user's recent comments, newest first.
CREATE TABLE comments_by_user (
author_id text, day date, posted_at timestamp, comment_id text,
stream_id text,
PRIMARY KEY ((author_id, day), posted_at, comment_id)
) WITH CLUSTERING ORDER BY (posted_at DESC);
-- Read on every post, from an in-process copy on each comment server.
CREATE TABLE stream_bans (
stream_id text, user_id text, banned_until timestamp,
PRIMARY KEY (stream_id, user_id)
);
CREATE TABLE stream_settings (
stream_id text PRIMARY KEY,
slow_mode_seconds int, followers_only boolean, version bigint
);
Three details to note.
- The partition key carries the minute. A big stream writes 8,300 rows a second. One partition per stream would keep growing for the whole broadcast and pile every write on the same three replicas. A minute bucket caps a partition at about 500,000 rows and moves the writes to fresh partitions every minute.
comments_by_useris a second copy, written on purpose. The archive writer inserts both rows. Moderation is the only reader, and it needs a key the main table can't give.stream_settingshas a version. Comment servers cache settings, and a moderator turning on slow mode bumps the version so every server knows its copy is stale.
The queries that carry the product
-- 1. Archive writer, batched, 41,500 rows a second on average.
INSERT INTO comments (stream_id, minute, seq, comment_id, author_id, text, client_id)
VALUES (?, ?, ?, ?, ?, ?, ?);
-- 2. Replay: one minute of one stream, in order.
SELECT seq, author_id, text FROM comments
WHERE stream_id = 's_77' AND minute = '2026-11-26 20:14:00';
-- 3. Cold backfill, only when a gateway has nothing in memory.
-- Read the minute before too if this one has fewer than 50.
SELECT seq, author_id, text FROM comments
WHERE stream_id = 's_77' AND minute = '2026-11-26 20:14:00'
ORDER BY seq DESC LIMIT 50;
-- 4. Moderation: what has this user said today?
SELECT stream_id, comment_id FROM comments_by_user
WHERE author_id = 'u_41' AND day = '2026-11-26';
The insert runs most, by far. The interviewer will push on the third one, because 5 million people joining a match in its first minutes would turn it into the hottest read in the system. High-level design 3 keeps it from running at all.
2. Reactions
A reaction is a heart or a laugh floating over the video. Nobody reads them one by one. A viewer sees a swarm that gets thicker when something happens, plus perhaps a running total. Before any design, put a number on the peak.
The question is where per-tap traffic has to stop. Assume 1 in 5 viewers taps at the peak, twice a second each. tapping viewers 5M / 5 = 1M taps 1M × 2 = 2M/s One request per tap 2M req/s The client sends a count every 2 seconds requests 1M / 2 s = 500,000/s to one counter 500,000 INCRBY/s one Redis shard ~100,000 simple ops/s ───────────────────────────────────────────────────────── Batching on the phone is not enough. One counter key would need five times what one Redis shard can do.
A reaction is a tiny comment
Send each tap through the comment path and deliver it to every viewer. It is tempting because the pipeline already exists. But 2 million taps a second, each sent to 5 million viewers, is 10 trillion deliveries a second. The cap from requirement 3 already rules out delivering comments that way, and reactions are 240 times more numerous.
One counter per stream, broadcast once a second
The client batches taps and sends a count every 2 seconds. The server adds it to a Redis counter per stream and emoji, rx:s_77:heart. Once a second, the stream worker reads the counters and puts the totals in its next batch. Viewers get one small summary a second, not 2 million events.
The cost is the hot key. At 500,000 increments a second, one key on one shard is five times past its limit. The usual fix is to split it into 10 sub-keys, rx:s_77:heart:0 to :9, and sum them on read. That works, and it is a lot of machinery for a number that only has to look right.
Count where the taps land, and never send a tap anywhere
Question the premise that reactions need a central counter at all. Each reaction POST goes up the HTTP/2 connection the viewer already holds, and that connection ends on the viewer's own gateway. So the gateway answers the POST itself and adds the count to an in-memory total for that stream. Once a second, for each stream that had taps, it appends one message with its totals to a separate Kafka topic, reactions. That topic is partitioned by stream id the same way as comments, so the same stream worker reads both. The stream worker sums the gateways' messages and puts the total in the next batch. The archive writer and the classifier never read reactions.
For the big stream, that is 63 messages a second reaching the backend, one per gateway in its group, instead of 500,000 increments. The client turns the totals into a swarm on screen: it draws a number of floating hearts that grows with the count, without drawing one per tap.
What you give up: if a gateway dies, up to a second of its taps is lost. Nobody can see that, and the requirement never asked for an exact count.
3. Joining a stream that is already running
A viewer who opens a stream sees an empty list until the next batch, unless the server sends the recent comments first. So every join starts with a backfill: the last 50 comments, sent before the live batches. The same question comes up after a dropped connection, when the app reconnects with last_event_id and wants the batches it missed.
The load is uneven. When a big match starts, millions of people join in a few minutes.
The question is whether backfill can read from shared storage. Assume half the 5M viewers arrive in 5 minutes. joins 2.5M / 300 s ≈ 8,300/s all for one stream, so one key or one partition If every gateway restarts at once, as after a bad deploy, the whole audience comes back within a minute reconnects 5M / 60 s ≈ 83,000/s ───────────────────────────────────────────────────────── At 83,000 a second on one key, backfill becomes the busiest read on one shard in the whole system.
Read the last 50 from the archive on every join
Run query 3 against Cassandra. It is the obvious source, because the comments are there. At 8,300 joins a second, every read goes to the same partition, which lives on three replicas. A fleet-wide restart pushes that to 83,000 reads a second on those same three machines, while they are also taking the stream's writes.
Keep the last 50 in a Redis list per stream
The stream worker pushes each comment it publishes into a capped list, recent:s_77, with LPUSH and then LTRIM recent:s_77 0 49, so the list holds the last 50 comments. On a removal, it deletes the comment from the list with LREM. A join runs LRANGE recent:s_77 0 49. One shard serves 8,300 of those a second with ease. A reconnect storm at 83,000 a second is close to the ~100,000 ops a second one shard can take, on a key that can't be split, because every reader needs the same 50 comments.
The gateway already has the recent comments
Question the premise that backfill is a read from shared storage. A gateway that serves any viewer of s_77 is subscribed to its channel and receives every batch. So it keeps the last 50 comments and the last 60 seconds of batches in a small ring buffer per stream, in memory. A join or a resume on that gateway is a local read, with no network call.
Only the first viewer of a stream on a gateway finds the buffer empty, and that gateway reads the Redis list once to fill it. With viewers placed by stream, the big stream causes 63 such reads in total, one per gateway in its group. A resume with a last_event_id still in the buffer gets exactly the missed batches. An id older than the buffer gets the latest 50 instead, and the app replaces its list with them, which is what the viewer would see on a fresh join anyway.
What you give up: each gateway holds a buffer for every stream it serves. For the big stream, a minute of batches is 120 batches of about 900 bytes, about 110 KB, plus 7.5 KB for the 50 comments. A small stream posts a few comments a minute, so its buffer is a few kilobytes, and even 10,000 of them on one gateway take tens of MB. The Redis list stays, as the source for cold buffers.
A joining viewer gets 50 comments, not the whole broadcast. That is the thesis applied again: the viewer is owed a feed that looks alive from the first second, and 50 comments do that. Scrolling back further is a replay feature, served from the archive.
4. Moderation and rate limits
Every comment passes four checks in the comment service before it is appended. Twitch's chat runs the same kind of step in a service it calls Clue, which asks questions such as "Is the user banned in the channel they're speaking in?" before a message goes out.
- Ban check. Each comment server holds the stream's ban list in memory. When a moderator bans someone, the change is pushed to every server, so the check never makes a network call.
- Rate limit. A token bucket per user per stream, in Redis, keyed
rl:{u_41}:s_77. Twitch documents limits of this kind for bots and chat clients: 20 messages per 30 seconds, and 100 when the user is the channel's broadcaster, a moderator or a VIP. A stream's slow mode lowers the rate for everyone in it. The mechanics are in Distributed Rate Limiter. - Blocked terms. The stream's list of banned words, matched in process.
- Size and format. Length limits, links, repeated characters.
All four together take a few milliseconds. A spam and abuse classifier is slower, say tens of milliseconds, and putting it in front of the 202 would add that to every post. The batching step offers a better place.
The stream worker already holds comments for up to half a second before publishing. It holds each one for at least 100 ms, so a comment that arrives late in a window goes into the next batch instead. The classifier reads the same Kafka partition and writes a verdict per comment to a small topic of its own, which the stream worker also reads. A comment flagged before its batch closes is never published. A verdict that arrives late turns into a removal.
Removals must reach everyone, so they never go through the sample. A moderator's delete becomes a removal event, appended to the stream's Kafka partition like a comment. The stream worker puts it in the removed list of every batch for the next 10 seconds, and the cap never applies to that list. Each gateway drops the comment from its ring buffer and forwards the batch, and each app hides the comment if it is on screen. The first copy arrives in under a second, inside the 5 second requirement.
The repeats are there because batches can go missing. Redis pub/sub delivers at most once, and a gateway skips batches for a slow viewer, as deep dive 4 explains. A removal id is a few bytes, so sending it 20 times costs almost nothing. When a batch's previous id doesn't match the last batch a gateway saw, the gateway knows it missed one and refills its 50 comments from the Redis list, where removals are already applied. So a missed removal cannot stay in the buffer for new viewers.
A ban adds one step. The ban list change goes out to every comment server, and a removal for each of the user's comments still inside the gateways' buffers goes out on the stream's path. Comments from before the ban that already scrolled off screens need nothing.
Deep dives
Deep dive 1 comes up in nearly every interview. Deep dives 2 and 3 come up most often after that.
1. The hot stream
The big stream posts 8,300 comments a second, and requirement 3 lets each viewer see 10. Somewhere between the two, 8,290 comments a second are left out. The question is where that happens and who chooses.
Doing it on the gateway is the obvious place, because the gateway knows its viewers. But the channel would still carry all 8,300 comments a second to 63 gateways, which is the 523,000 comment copies left over from high-level design 1. Batching already packs them into 126 messages a second, 2 per gateway, but each message holds about 4,150 comments. At 150 bytes a comment, one Redis shard pushes about 78 MB/s for this one stream.
So the stream worker samples, because it is the one process that sees every comment for the stream. Each half-second window gets at most 5 comments, picked in this order:
- The streamer and the moderators. Their comments always go through. A viewer who missed the streamer's comment would notice.
- Comments the classifier scored highly, if it scores quality at all.
- A random pick from the rest. Random is fair, and it shows the audience as it is.
The channel still carries 126 messages a second, but each holds 5 comments instead of 4,150. That is about 95 KB/s from the shard instead of 78 MB/s, about 830 times less.
A poster whose comment was not picked still sees it, because their app drew it when they posted. Nobody else can tell it was skipped, and to the poster the stream behaves as though every comment went out. This is the thesis at its sharpest: the poster is owed their own comment, and the audience is owed a feed that looks alive, and neither is owed every comment.
If the product wants friends' comments to win, the stream worker can publish 50 a second instead of 10, and each gateway picks 10 per viewer from those 50, friends first. Each batch gets 5 times larger, and the channel still sends 126 copies a second.
Everything here depends on the number of viewers per stream, which is heavily skewed. Half a million streams have a few dozen viewers, and one has 5 million. A design tuned for the average stream fails on the big one, and a design built only for the big one wastes gateways on the rest. Placement by stream and sampling at the worker each handle one end.
2. How many servers, and which tier grows?
The question is which tier sets the fleet size. Size the
gateways by connections first, then check bandwidth and
memory on one gateway, then the rest of the system.
Gateways
connections 50M / 80,000 per gateway ≈ 625
spare for a failed gateway and for deploys → ~750
One gateway
frames 80,000 × 2 a second = 160,000/s
bandwidth 160,000 × 900 B ≈ 144 MB/s ≈ 1.2 Gbps
memory 80,000 × ~30 KB per conn ≈ 2.4 GB
(TLS and socket buffers, assumed)
Everything else
comment service 83,000/s / ~5,000 per instance ≈ 17 → ~25
stream workers 256 partitions, 8 per worker → 32
pub/sub ~614,000 comment copies/s before sampling,
far fewer after → a few nodes
Kafka comments 83,000 × ~300 B ≈ 25 MB/s
Kafka reactions at most 500,000 streams with taps
a second × ~100 B ≈ 50 MB/s
─────────────────────────────────────────────────────────
About 750 gateways and under 100 of everything else. The
connection count sets the fleet, not the comment rate.The gateway count follows the number of viewers, not the number of comments. A quiet evening with 50 million viewers needs the same 750 gateways as a busy one. The bandwidth check matters too: 1.2 Gbps per gateway fits a 10 Gbps network card, so connections run out first. LinkedIn's engineers reported the same kind of limits at around 100,000 connections a machine: file descriptors, ports and memory.
Scaling up is cheap. A new gateway joins the router's ring, and only new viewers of the streams that now hash to it land there. Existing viewers stay where they are, so for a while some streams have two gateways subscribed instead of one, and nothing breaks.
Scaling down is the part to plan. A gateway with 80,000 connections can't be removed in one step without 80,000 reconnects, which deep dive 4 covers.
3. Where do the 2 seconds go?
The question is whether a half-second batch fits the
2 second p99. Add up one comment's path.
POST to comment service, open connection 60 ms
ban, rate limit, blocked terms 5 ms
Kafka append, acknowledged by replicas 10 ms
wait for the batch to close, at most 600 ms
(100 ms minimum hold, then the next window)
classifier 0 ms (inside the wait)
pub/sub to the gateways 5 ms
gateway writes to 80,000 connections 100 ms
network to the viewer 100 ms
─────────────────────────────────────────────────────────
total, worst case in the window 880 ms
Under 1 second, leaving over a second of the 2 second p99
for slow mobile networks, retries and pauses.The batch wait is the largest line, and it is a choice. A 250 ms window roughly halves it and doubles the frames on every gateway. Half a second keeps the frame rate low and still leaves most of the 2 seconds unused.
4. What happens when a gateway dies, or is deployed?
When a gateway dies, its 80,000 viewers lose their connections at the same moment. The browser's EventSource would retry the same URL, which points at the dead gateway, so the app handles the reconnect itself. It closes the stream, waits, asks the connection router again, and opens a new stream with last_event_id in the URL. If every app waits the same time, all 80,000 come back in the same second.
So each app waits a random delay between 1 and 10 seconds. The 80,000 reconnects then arrive at about 8,000 a second, spread over 10 seconds. The connection router sends each one to another gateway in the stream's group, whose ring buffer is already warm. That gateway sends the batches after last_event_id from its buffer, and the viewer carries on. A small stream has no group, so its viewers go to the next gateway on the ring, which fills its buffer from the Redis list once. Most viewers see a pause of a few seconds and miss nothing.
A deploy is a planned shutdown, so it can go slower. The gateway stops taking new viewers, then sends each connection a reconnect event with a random delay spread over several minutes, and exits when its connections are gone. Deploying the whole fleet this way takes a while, and that is the cost of never pushing 50 million reconnects through the router at once.
When something upstream is overloaded, the design has dials to turn before anything breaks. Lower the cap from 10 comments a second to 3. Widen the batch window from half a second to 2 seconds. Stop sending reaction totals. Each one keeps the feed looking alive, which is the requirement, and none of them touches removals or the archive.
5. Ordering, and why "good enough" is enough
Every viewer of s_77 sees the same order, because every comment for s_77 passes through one Kafka partition, whose offsets number them, and one stream worker. Viewers on different gateways can't disagree.
That order is the order of arrival at Kafka, not the order of posting. Two comments posted 20 ms apart on different comment servers can land either way round. Nobody can see that. People don't post with millisecond timing, and the half-second batch already shows them together.
Client clocks play no part. A phone with a clock 30 seconds off posts a comment, and it is numbered by when it arrived, so it appears in the right place for everyone else. The one exception is the poster's own app, which draws the comment where the poster sent it. When the batch arrives, the app keeps its own copy where it is and drops the server's one by client_id, so the comment never jumps.
A strict global order, with one sequencer numbering every comment on the platform, would buy nothing anyone can see. And a single sequencer would put 83,000 comments a second through one process. Per-stream order needs nothing beyond the partition the design already has.
6. Viewers in many regions
A stream from São Paulo is watched in Mumbai, Paris and Ohio. Viewers connect to gateways in their nearest region, so the question is how a comment posted in Mumbai reaches viewers in Paris.
Facebook described its answer for live comments on posts back in 2011 as "write locally, read globally". Each data center recorded who was viewing what locally, and on each comment the system fetched viewership information from all of its data centers. LinkedIn chose the same direction for live likes: subscriptions stay inside each data center, and a published event is forwarded to the dispatchers in every other data center.
Here, each stream has a home region, chosen by where the streamer broadcasts from. Its Kafka partition and its stream worker live there, so the order is decided in one place. Comments are partitioned by home region, not replicated, and a comment posted in Mumbai for a São Paulo stream is forwarded to São Paulo's Kafka before it is numbered. The stream worker publishes each batch to its own region's pub/sub, and to one relay in each other region that has viewers. Each relay republishes the batch to its region's channel, where local gateways are subscribed as usual.
The costs:
- A poster far from the home region waits for a round trip, a couple of hundred milliseconds, before their comment is numbered. Their own screen shows it at once, so they don't notice.
- If the home region fails, the stream's comments pause until another region takes over its partition. No synchronous cross-region copy exists, so a few seconds of comments can be lost. The thesis allows that: viewers are owed a feed that looks alive, and it resumes within seconds.
- The archive is copied to other regions afterwards, asynchronously, for replay near the viewer.
7. How do you know it is working?
Four questions must have answers during an incident.
- How long does a comment take to reach a screen? A synthetic viewer in each region watches test streams and measures post to screen. LinkedIn measured one-way latency from its likes backend publishing an event to the frontend sending it on the client connection, and reported 75 ms at p90.
- What fraction of batches is a gateway dropping? Slow clients get skipped rather than queued, so count the skips per gateway and alert when the rate rises.
- How long does a removal take to disappear? Track the time from the moderator's click to the batch that carries it, per stream.
- How far behind is the stream worker? Consumer lag on the
commentstopic, per partition. Rising lag is the first sign of a stream that outgrew its worker.
Final design
The read path, one viewer joining
- The app asks the connection router for
s_77. The router hashes the stream id, or picks a gateway in the stream's group if it is big, and returns a hostname. - The app opens
GET /v1/streams/s_77/liveon that gateway. The gateway adds the connection to its table and subscribes tostream:s_77if it is the first viewer there. It sends the last 50 comments from its ring buffer, filling the buffer from the Redis list first if it was empty.
The write path, one comment end to end
- The viewer posts. Their app draws the comment at once, tagged with its
client_id. The gateway passes thePOSTto the comment service, which checks the ban list, the rate limit and the blocked terms, then the retry key. - The comment service appends the comment to the stream's partition of the
commentstopic and answers202. The classifier reads the same partition and writes its verdict. - The stream worker gathers half a second of comments, removals, and gateway reaction totals from the
reactionstopic. It leaves out flagged comments, samples down to 5 comments per window if the stream is big, and numbers the batch. - It publishes the batch to
stream:s_77and pushes its comments ontorecent:s_77. For viewers in other regions, it also sends the batch to each region's relay. - Each subscribed gateway adds the batch to its ring buffer and writes it to every local connection for
s_77. The poster's app drops the copy of its own comment byclient_id. - The archive writer reads the same partition and writes the comment to Cassandra, or to minute files, in batches.
The shape comes from a few numbers. Each viewer receives at most 10 comments a second, so the big stream costs 50 million deliveries a second instead of 41 billion. Placement by stream cuts the internal comment copies from 30 million a second to about 614,000, and sampling at the stream worker removes most of what is left. On the big stream, two million reaction taps a second reach the backend as 63 messages. And 50 million connections at 80,000 per machine make the gateway tier about 750 servers, about nine in ten of all the servers in the design.
What is expected at each level
Mid-level
Get the moving parts right: a held connection per viewer, a gateway tier that holds the connections, and a pub/sub channel per stream so a comment isn't sent to every gateway. Choose between SSE and WebSocket with a reason, and explain how a new viewer sees recent comments. Being led to the hot stream is fine. Proposing to deliver every comment to every viewer is expected at first, as long as the arithmetic changes your mind once the interviewer brings it up.
Senior
Drive the design, and raise these without being asked.
A cap on what each viewer receives. Without it, the big stream costs 10 Mbps of text per viewer, and no design can fix that. A senior candidate states the cap as a requirement.
Reactions as counts. Sending taps one by one, or counting them in one key, has to be ruled out with the 2 million taps a second, not by instinct.
Removals that reach everyone. Sampling is fine for comments and never for removals, and the design has to say how a removal gets past the sample.
Having no answer for 5 million viewers joining in five minutes, or for a gateway dying with 80,000 connections on it, is disqualifying at this level.
Staff+
A correct design is still the bar. What sets a staff+ answer apart is noticing assumptions and trading them on purpose.
Place viewers by stream. Random placement makes small streams as costly as their viewer count. A connection router cuts internal copies about 50 times.
Sample once, at the source. The stream worker is the one place that sees everything, so the channel carries only what viewers will see.
Reuse the batch window. The classifier runs inside the half-second wait, and late verdicts become removals on a path that already exists.
Backfill from the gateway's memory. The subscribed gateway already has the recent comments, so joins and reconnects make no network call.
Order per stream, and nothing more. One partition per stream gives every viewer the same order, and a global sequencer buys nothing anyone can see.
And be able to say what you would not build. No per-viewer queue or acknowledgements, since nobody is owed a particular comment. No exactly-once delivery. No exact reaction counter, and no global ordering service. No WebSocket fleet tuned for upstream traffic that never comes. And no cross-region synchronous replication for comments that scroll off screen in four seconds.
Sources
The company numbers below come from what each company published. The traffic and fleet sizes are assumptions, worked through in the article.
- Akhilesh Gupta, LinkedIn, Streaming a Million Likes/Second: Real-Time Interactions on Live Video (QCon London 2020): SSE for live likes, in-memory subscription tables, about 100,000 connections on one machine and the rejected Kafka design. Also cross-data-center publish, 75 ms at p90, and the choice of speed over delivery guarantees.
- Twitch, Twitch Engineering: An Introduction and Overview (2015): the chat Edge over IRC and WebSockets, Pubsub fanout across Edge nodes, and Clue's checks before a message goes out.
- Twitch, Chat documentation: the per-user limits for bots and chat clients, 20 messages per 30 seconds and 100 for broadcasters, moderators and VIPs.
- Facebook Engineering, Live Commenting: Behind the Scenes (2011): why polling was rejected, and "write locally, read globally" across data centers.
- Meta, Live Video API: Interacting with Viewers: live comments and reactions available by polling or by server-sent events.