Skip to content

Design Live Comments (Facebook Live)

Advanced 90 min read Part 17 of 18

Design Facebook-scale live comments: SSE push, pub/sub partitioned by video, viewer co-location, mega-stream sampling, CDN snapshots, ordering and catch-up.

The Problem#

When someone goes live on Facebook, Instagram, YouTube, Twitch, TikTok or LinkedIn, viewers can type comments that scroll past next to the video. A comment typed in São Paulo should appear on the screens of everyone else watching the same stream, in Mumbai or Seattle, within a blink. A viewer who opens the stream ten minutes late should see the recent conversation, and be able to scroll up for older comments. That is the whole product: post a comment, see everyone's comments arrive live, and see what was said before you arrived.

It sounds like chat, but the shape of the traffic is very different, and that shape drives every decision in this design:

  • Extreme fan-out. In a chat, a message goes to a few people. In a live stream, one comment goes to every viewer. A stream with 1 million viewers turns one comment into 1 million deliveries.
  • Very lopsided reads and writes. Most viewers never comment. They only read. A stream might have 1 million viewers and 2,000 commenters. The system is a broadcasting system with a small write path attached.
  • A heavy-tailed popularity curve. At any moment there are millions of live videos. Almost all have a handful of viewers. A few (a World Cup final, a celebrity launch, a breaking news event) have tens of millions, and those few produce most of the load.
  • Freshness beats perfection. A comment that arrives 10 seconds late is useless, because the moment has passed. A comment that is occasionally lost during a network blip is a minor annoyance. This is the opposite of payments or chat, where every message must arrive.
  • Ephemeral attention. Comments matter most in the few seconds after they are posted. After the stream ends, they are mostly an archive.

A real-world analogy. Imagine a stadium with a giant screen that shows text messages from the crowd. Fans text a number, an operator puts the messages on the screen, and everyone in the stadium reads them at once. Now imagine a million stadiums, each with its own crowd, and a few stadiums so large that a million texts arrive every few minutes. The operator of a small stadium can show every message. The operator of the largest stadium cannot: the screen would scroll faster than anyone can read, so they pick a representative sample that captures the mood. And because people keep arriving late, each stadium also keeps a printed log of recent messages at the entrance. The engineering problem is to build the network of operators and screens: get each text to the right screens quickly, without every operator reading every text from every stadium, and handle the giant stadiums with a different strategy from the small ones.

This case study designs that system. It starts with a simple post-and-poll design, replaces polling with server push over Server-Sent Events, scales the push tier to hundreds of millions of connections with pub/sub partitioned by video and viewer co-location (and an alternative dispatcher design), then handles mega-streams with sampling and CDN snapshots. It also covers comment storage and pagination, ordering, reconnects and catch-up, and the operational side. It builds on Pattern: Pushing Realtime Updates and Polling, Long Polling, SSE, WebSockets and Webhooks.

Clarifying Questions#

Spend the first few minutes agreeing on scope. Every answer below changes something in the design.

QuestionTypical answerWhy it matters
What can a viewer do: post, read live, read history?All three. Replies and reactions on comments are out of scope.Defines the three functional requirements and keeps threads and likes out of the core.
How many concurrent live videos and viewers?Millions of concurrent videos, hundreds of millions of concurrent viewers at peak.Sets the size of the connection tier and the need for horizontal scaling.
How many comments per second on a single video?Usually a few per minute; on the biggest streams, thousands per second.Drives the hot-stream design: sampling and CDN delivery.
What latency is acceptable?Under about 200 ms end to end for typical streams.Rules out slow polling and points to persistent push connections.
Must every viewer see every comment?No. Eventual consistency is fine and a sample is acceptable on huge streams.Lets us choose availability over consistency and drop or sample comments under load.
Does a commenter need to see their own comment immediately?Yes.Requires read-your-own-writes on the client, even if others see it later.
Do viewers need history before they joined?Yes, with infinite scroll back through older comments.Requires durable storage and cursor pagination.
Web, mobile or both?Both, including flaky mobile networks.Reconnects, catch-up and battery use become real requirements.
Do comments need to line up with the video timeline?Nice to have; required for replays after the stream ends.Adds a video-time field to each comment and client-side alignment.
Moderation, spam and authorisation?Assume an existing auth system; spam and abuse filtering are below the line.Keeps trust and safety as a hook, not a core component.
Is the video itself in scope?No. Another team owns live video ingest and playback.We integrate with the live video service only for metadata and status.

Requirements#

Functional#

  1. Viewers can post comments on a live video. A comment is short text tied to one live video and one author.
  2. Viewers see new comments while they watch. New comments appear on screen in near real time without the viewer refreshing.
  3. Viewers can see comments posted before they joined. On joining, they see the most recent comments; scrolling up loads progressively older ones (infinite scroll).

Below the line (out of scope): replying to comments (threads), reacting to comments, editing comments, comment search, and the video pipeline itself. We will touch on reactions and replays as variants at the end, because interviewers like to ask "what would change if...".

Non-Functional#

  1. Scale. Millions of concurrent live videos, hundreds of millions of concurrent viewers, and thousands of comments per second on the largest single videos.
  2. Availability over consistency. Viewers may briefly see slightly different sets of comments. Eventual consistency is acceptable. The comment feed must keep flowing even when parts of the system fail. In CAP Theorem and PACELC terms, this is an AP system that also favours latency over consistency in normal operation.
  3. Low latency. Under about 200 ms from "post" to "visible on other viewers' screens" under typical network conditions. About 200 ms is roughly where people stop perceiving a delay as a delay. Interface research has long treated around 100 to 200 ms as the threshold where a response feels instant.
  4. Read-your-own-writes for the commenter. The author sees their own comment immediately.
  5. Graceful degradation. Under overload, show fewer comments rather than slower comments, and never take down the video experience.

Below the line: security (only authorised users can post), integrity (filtering spam and hate speech), and analytics. In a real system these are essential. In this design they are hooks on the write path, discussed briefly in the deep dives.

The key insight to state early: this is a read-heavy broadcast problem with a tiny write path. The interesting work is not storing comments. It is getting each comment to the right subset of hundreds of millions of open connections quickly, and changing strategy when one stream becomes enormous.

Capacity Estimation#

Rough numbers decide where the design will break. We use round figures and state each assumption, the way Back-of-the-Envelope Estimation recommends.

Assumptions at global peak:

  • 1 million concurrent live videos.
  • 100 million concurrent viewers in total, so about 100 viewers per video on average. The real distribution is very skewed: most videos have fewer than 10 viewers, and a few have millions.
  • 1 in 50 viewers comments at all during a session, and an active commenter posts about one comment a minute.
  • Comment text is up to 500 characters, about 100 bytes on average. With author id, video id, timestamps and display metadata the stored record is about 400 bytes, and the delivered event (with the author's display name and avatar URL) about 300 bytes.

Write rate. 100 million viewers × 1/50 commenters × 1/60 comments per second ≈ 33,000 comments per second globally, which we round to 50,000 per second at peak to leave room for spikes. That is a modest write rate for a sharded key-value store. A single large video can produce 5,000 comments per second on its own, which is the real write hotspot.

Storage. 50,000 comments per second × 400 bytes = 20 MB/s, or about 1.7 TB per day before replication, about 5 TB per day with three replicas. Live comments are written once and rarely updated, so the store is append-heavy. If we keep all comments for a year that is about 600 TB raw, so older comments should move to cheaper tiers.

Fan-out deliveries. This is the number that matters. If every comment went to every viewer of its video, the delivery rate would be the sum over videos of (comment rate × viewers). The skew makes this explode:

  • A typical video: 0.05 comments per second × 100 viewers = 5 deliveries per second. Trivial.
  • A big stream: 100 comments per second × 100,000 viewers = 10 million deliveries per second.
  • A mega-stream: 5,000 comments per second × 10 million viewers = 50 billion deliveries per second. Impossible, and pointless, because nobody can read 5,000 comments per second.

So we cap what each viewer receives. If each viewer is sent at most about 10 comments per second (more than anyone can read), the worst case is 100 million viewers × 10 = 1 billion deliveries per second. The realistic average is far lower, because most streams are quiet. Assume an average of 2 deliveries per viewer per second: about 200 million push messages per second across the fleet. At 300 bytes each that is 60 GB/s, or about 480 Gbit/s of egress, before compression and protocol overhead.

Connections. 100 million concurrent viewers means 100 million long-lived connections. A well-tuned server on an event loop (epoll on Linux) can hold hundreds of thousands of idle connections; with TLS, real message traffic and headroom for failover, plan for about 100,000 active connections per server. That gives about 1,000 realtime servers at peak, plus spares. Each server then pushes about 200,000 messages per second (60 MB/s, about 480 Mbit/s), which fits a 10 or 25 Gbit/s NIC comfortably.

Memory per connection. Kernel socket buffers, TLS state and the application's per-connection object together cost roughly 10 to 50 KB per connection, depending on buffer tuning. At 100,000 connections that is 1 to 5 GB per server, which is fine.

Internal pub/sub traffic. If every comment were broadcast to every realtime server (the naive design), that is 50,000 comments per second × 1,000 servers = 50 million internal messages per second, almost all of them thrown away. If instead viewers of the same video are co-located on as few servers as possible, a comment goes only to the servers that host its viewers: one server for small videos, about viewers / 100,000 servers for large ones. That cuts internal traffic by two to three orders of magnitude. This single estimate is the argument for partitioned pub/sub.

History reads. Each viewer loads one page of recent comments on join, and a small fraction scroll back. If 100 million viewers join over the course of about an hour, that is roughly 30,000 joins per second at peak, with joins clustered at stream start. Most of these read the same "latest 50 comments" for popular videos, so a cache in front of the store absorbs nearly all of them.

QuantityEstimate
Concurrent live videos1 million
Concurrent viewers / connections100 million
Comment writes50,000 per second peak (5,000 per second on one mega-stream)
Push deliveriesabout 200 million per second average, capped per viewer
Egressabout 480 Gbit/s before compression
Realtime serversabout 1,000 at 100,000 connections each
Comment storageabout 1.7 TB per day raw
Join (history) readsabout 30,000 per second peak, mostly cacheable

For more on these orders of magnitude see Numbers Every Engineer Should Know.

Core Entities#

Only three nouns matter at this stage. The data model will grow from them later.

  • User. Anyone who watches or comments. A user can be a viewer or the broadcaster. Users are owned by the existing identity system.
  • Live Video. A stream being broadcast by a user. It is owned and managed by another team (the live video service). We need its id, its owner, its status (scheduled, live, ended) and, at runtime, an approximate viewer count.
  • Comment. A short message posted by a user on a live video: id, video id, author id, text, created-at time, and optionally the point in the video timeline at which it was posted.

There is also a runtime notion that is not stored in a database but is central to the design: a Subscription (which connection is watching which video), held in memory by the realtime servers and, in some designs, in a coordination service.

API Design#

The write path and the history path are ordinary HTTP. The live stream of new comments is a long-lived push channel.

# 1. Post a comment. The user id comes from the auth token, never the body.
POST /v1/live-videos/{liveVideoId}/comments
Authorization: Bearer <JWT or session token>
Idempotency-Key: 6f1c...            # client-generated, makes retries safe
{ "text": "Cool video!", "videoTimeMs": 754210 }
-> 201 { "commentId": "1789346123456782336", "createdAt": "...", "status": "visible" }
 
# 2. Load history before joining, newest first, cursor pagination.
GET /v1/live-videos/{liveVideoId}/comments?cursor={commentId}&limit=50&order=desc
-> 200 { "comments": [ ... ], "nextCursor": "1789345987654321408" }
 
# 3. Catch up after a short disconnect, oldest first.
GET /v1/live-videos/{liveVideoId}/comments?since={lastSeenCommentId}&limit=200
-> 200 { "comments": [ ... ], "truncated": false }
 
# 4. Subscribe to new comments (Server-Sent Events).
GET /v1/live-videos/{liveVideoId}/comments/stream
Accept: text/event-stream
Last-Event-ID: 1789346123456782336  # sent automatically on reconnect
-> 200 Content-Type: text/event-stream
   id: 1789346123456782337
   event: comment
   data: {"commentId":"1789346123456782337","author":{...},"text":"wow"}

A few points to call out:

  • Identity comes from the token. The client never sends a user id in the body. The server validates the JWT or session token and extracts the user id. Otherwise any client could impersonate any user by editing the request. See Authentication and Authorization.
  • Idempotency key on posts. Mobile clients retry when a request times out. Without a key, a retry after a lost response creates a duplicate comment. See Idempotency and Safe Retries.
  • Two kinds of cursor. cursor with order=desc means "give me the N comments older than this one" (scrolling back). since means "give me comments newer than this one" (catching up). Both use the comment id as the position, so comment ids must be sortable by time.
  • The stream endpoint carries the video id in the path. That matters later: a Layer 7 load balancer can read the path and route all viewers of one video to the same servers.
  • Why REST plus SSE and not one WebSocket? Posting is rare and fits a normal request with normal auth, retries and rate limiting. Reading is constant and one-way. We justify this choice in the first deep dive. For general guidance see API Design Best Practices.

High-Level Design#

We build the design one functional requirement at a time, starting simple, and let the non-functional requirements drive the upgrades. If you already know the final design, you can jump to it in an interview, but say why each piece is there.

1) Viewers can post comments on a live video#

Posting is the easy part. The viewer's app sends POST /v1/live-videos/{id}/comments. A Comment Management Service validates the request and writes the comment to a Comments Database.

The pieces:

  • Commenter client. A web or mobile app. It holds the user's session token, sends the comment, and shows it immediately in the user's own feed (optimistically), before the server confirms.
  • Comment Management Service. A stateless service that creates and queries comments. It authenticates the request, checks the text (length, empty, banned words as a cheap first filter), applies a per-user rate limit, assigns a time-sortable comment id, and stores the comment. It also serves history reads.
  • Comments database. A key-value or wide-column store such as DynamoDB or Cassandra fits well: comments are simple records with no joins or multi-row transactions, the access pattern is always "comments for one video, by time", and the store must absorb a high, spiky write rate. PostgreSQL or MySQL would also work at moderate scale, with sharding by video id at large scale. We discuss the choice in the Data Model section.

The steps are: the user drafts a comment, the client posts it, the service validates and stores it, and returns the id. Nobody else sees it yet. That is the next requirement.

2) Viewers see new comments while watching#

Now every other viewer of the same video must see the comment. The simplest working approach is polling: each viewer's client calls GET /comments?since={lastCommentId} every few seconds and appends whatever is new.

This works for a demo and fails at scale, for three reasons:

  1. Most polls return nothing. A typical video gets a comment every few seconds at most. Polling every second means most requests are wasted round trips that still cost a TLS-terminated HTTP request, an auth check and a database query.
  2. Latency is tied to the poll interval. With a 3-second interval the average delay is 1.5 seconds and the worst case is 3 seconds plus processing. Hitting 200 ms would require polling five times a second.
  3. The load scales with viewers, not comments. 100 million viewers polling every 3 seconds is about 33 million requests per second, even when nobody is commenting. Polling five times a second would be 500 million requests per second. The database cannot serve that, and caching helps only partly because every client has a different since value.

Polling is a fine first step in an interview because it is obviously correct and sets up the real question: how can the server tell clients about new comments instead of clients asking? That is the first deep dive, where we switch to server push.

3) Viewers can see comments made before they joined#

A viewer who joins needs two things at once: the live tail of new comments from now on, and the recent history they missed, with the ability to scroll back further (infinite scroll, the same pattern chat apps use).

The since parameter from the polling design gives comments newer than a point. For history we need the opposite: "give me the N most recent comments older than this point". That is pagination, and there are two main ways to do it.

Bad: offset pagination. GET /comments?offset=0&limit=10, then offset=10, offset=20, and so on. It is easy to implement but has two problems in a live feed:

  • It gets slower as you go back. The database must walk and discard all rows before the offset. OFFSET 100000 reads 100,010 rows to return 10. In SQL this is a known performance trap. In DynamoDB there is no offset at all, so you would have to scan.
  • It is unstable. Offsets count from the newest comment, and new comments arrive constantly. If 5 comments arrive between page 1 and page 2, then "offset 10" now points 5 rows earlier than before, so the viewer sees 5 duplicate comments. If a comment is deleted by moderation, they skip one. In a stream receiving 100 comments per second, offsets are wrong almost immediately.

Great: cursor pagination. The client sends the id of the oldest comment it has: GET /comments?cursor={oldestSeenId}&limit=50&order=desc. The server returns the 50 comments immediately older than that id, and a nextCursor (the id of the oldest comment in the page). Because comment ids are time-sortable and the table is sorted by id within each video, this is a single index seek plus a short range read, the same cost on page 1 or page 1,000. New comments arriving at the head do not shift the cursor, so there are no duplicates or gaps. In DynamoDB the query is "partition key = video id, sort key less than cursor, descending, limit 50":

{
  "TableName": "comments",
  "KeyConditionExpression": "liveVideoId = :v AND commentId < :cursor",
  "ExpressionAttributeValues": { ":v": "lv_123", ":cursor": "1789346123456782336" },
  "ScanIndexForward": false,
  "Limit": 50
}

Cursor pagination still costs one database query per page. For the first page, which every joining viewer requests and which is identical for everyone watching the same video, we add a cache of the most recent comments per video (a Redis list or sorted set), so that a celebrity stream with a million viewers joining serves "latest 50" from memory rather than from the database. We return to this in the storage deep dive.

The full high-level design#

Putting it together after the deep dives, the design separates the write path (post a comment, store it, publish it) from the read path (long-lived push connections), because the two scale very differently. Writes are about 50,000 per second; connections are about 100 million.

Mega-streams get a second delivery path, switched on automatically when a stream crosses a size threshold:

Components:

  • API gateway. Terminates TLS, authenticates, applies per-user and per-video rate limits, and routes to the Comment Management Service. See API Gateway and Backend-for-Frontend.
  • Comment Management Service. Stateless. Validates, assigns ids, persists to the database, appends to the recent-comments cache, and publishes to pub/sub. Scales by adding instances.
  • Comments database. The durable record, partitioned by video id and sorted by comment id. Serves deep history pages.
  • Recent-comments cache. A bounded per-video buffer of the last few minutes of comments in Redis. Serves the first history page on join and replays missed comments after reconnects, from any server.
  • Pub/Sub. Moves each comment from the write path to the realtime servers that host viewers of that video. Partitioned into N channels by hash of video id. Redis Pub/Sub is a good fit; we compare it with Kafka in the deep dives.
  • Layer 7 load balancer. Routes each viewer's stream request to a realtime server chosen by consistent hashing on the video id, so viewers of one video cluster on few servers. Envoy, NGINX or HAProxy can do this. See Load Balancing and Consistent Hashing.
  • Realtime Messaging Servers. Hold the SSE connections. Each keeps an in-memory map from video id to the set of connections watching it, subscribes to the channels for those videos, and writes each incoming comment to the matching connections.
  • Hot-stream aggregator, ring buffer and CDN. For mega-streams only: sample comments, keep the latest few hundred in a ring buffer, publish a snapshot every second to a CDN, and let clients poll the edge. See Content Delivery Networks (CDN).
  • Stream-mode controller. Watches viewer counts and comment rates per video and flips a video between normal push, sampled push and CDN snapshot delivery, with hysteresis so it does not flap.

Key Flows#

Flow 1: Post a comment and broadcast it to viewers#

  1. Optimistic display. The commenter's app shows the comment immediately as pending, so the author gets read-your-own-writes without waiting for the server. If the post fails, the app marks it as failed and offers a retry.
  2. Validate and assign an id. The service authenticates the token, checks per-user and per-video rate limits and text rules, and assigns a time-sortable id (see the ordering deep dive). The idempotency key means a retried request returns the original comment instead of creating a second one.
  3. Persist, then publish. The comment is written to the database first, then published. If we published first and the write then failed, viewers would see a comment that does not exist in history. If the publish fails after the write succeeds, the comment is still in history, and viewers who reconnect or scroll will see it. That is acceptable under our availability-over-consistency requirement. Some designs publish in parallel with the write to save a few milliseconds; that is also defensible if you accept the rare phantom.
  4. Fan-out. The pub/sub system delivers the message to the realtime servers subscribed to that channel. Each server looks up the connections watching this video in its local map and writes an SSE event to each. With viewer co-location, a typical video's viewers are all on one server.
  5. Client dedupe. The commenter's own app also receives the comment over SSE. It matches the commentId (or the idempotency key echoed in the event) against its pending entry, replaces it, and does not show it twice.

Latency budget for the 200 ms target, inside one region: client to edge 20 to 50 ms on mobile, gateway and auth 2 to 5 ms, database write 5 to 10 ms, publish and pub/sub hop 1 to 5 ms, realtime server lookup and write under 1 ms, server to viewer 20 to 50 ms. Total roughly 50 to 120 ms, leaving margin for the tail. Cross-region viewers add 60 to 150 ms of round-trip time, discussed in the multi-region deep dive.

Flow 2: A viewer joins a live video#

  1. Open the live stream first. The client opens the SSE connection before loading history. If it loaded history first and then subscribed, any comment posted between the two steps would be missed. Subscribing first means such a comment arrives on the stream, and possibly also in the history page; the client dedupes by id.
  2. Route by video. The Layer 7 load balancer hashes the video id from the path and picks a realtime server from a consistent-hash ring, so viewers of the same video land on the same server (or the same small group of servers for big streams).
  3. Subscribe lazily. The realtime server adds the connection to its in-memory map. If this is the first local viewer of the video, it subscribes to the pub/sub channel for that video's partition. When the last local viewer leaves, it can unsubscribe after a short delay, to avoid churn when viewers bounce.
  4. Load history. The client fetches the latest page. For an active video this comes from the recent-comments cache. Older pages come from the database by cursor.
  5. Merge. The client merges the history page with any events that already arrived on the stream, sorts by comment id, and removes duplicates.

Flow 3: Reconnect and catch up after a disconnect#

  1. Remember the position. Every SSE event carries an id: line set to the comment id. The browser's EventSource remembers the last one it saw. Mobile apps store it in app storage.
  2. Reconnect with backoff and jitter. After a drop the client waits a randomised delay before reconnecting. Without jitter, a server crash makes 100,000 clients reconnect in the same instant (a reconnect storm). EventSource has a built-in retry interval that the server can set with a retry: line.
  3. Send Last-Event-ID. On reconnect EventSource automatically sends the Last-Event-ID header. The new server may not be the old one, so it cannot rely on local memory. It reads the recent-comments cache for that video and replays everything after that id.
  4. Bounded replay. Replay is limited to a window, such as the last 5 minutes or the last 200 comments. After an hour away, replaying thousands of stale comments would overwhelm the viewer and the server. Beyond the bound, the server returns a "truncated" marker and the client jumps to live, with history available by scrolling.
  5. Good UX for the gap. Rather than dumping 47 missed comments at once, the client can play them at 2 to 3 times speed or show "You missed 47 comments" with a "jump to live" button.

Flow 4: A stream becomes a mega-stream#

  1. The stream-mode controller watches each video's concurrent viewers and comment rate, using counters updated by the realtime servers and the comment service.
  2. When a video crosses the upper threshold (for example 100,000 viewers or 500 comments per second, sustained for 30 seconds), the controller marks it as sampled and later as CDN mode.
  3. In sampled mode, the realtime servers still push over SSE, but the hot-stream aggregator only forwards a sample of comments, adapted to the comment rate, so each viewer receives a readable 5 to 10 per second.
  4. In CDN mode, the controller sends a control event over the existing SSE connections: "switch to snapshot polling at this URL". Clients close SSE and poll the CDN every second. The aggregator writes a fresh snapshot of the last 100 to 200 selected comments each second.
  5. When viewers and rate fall below a lower threshold (for example 60,000 viewers, sustained for a few minutes), the controller switches back. The gap between upper and lower thresholds is the hysteresis that prevents flapping.

Data Model#

Comments table (DynamoDB or Cassandra).

  • Partition key: liveVideoId. Every read is "comments for one video", so all comments of one video should live together.
  • Sort key: commentId, a 64-bit time-ordered id (Snowflake-style, explained in the ordering deep dive). Sorting by id is sorting by time, which makes both cursor directions a single range query: commentId < cursor descending for history, commentId > since ascending for catch-up.
  • status is visible, hidden (by moderation) or deleted. Moderation flips status rather than deleting rows, so cursors still work and audit is preserved. Reads filter out hidden rows.
  • videoTimeMs is the commenter's playback position when they posted. It lets replays show comments in sync with the video, and lets live viewers who are behind the live edge avoid "spoilers" (see the ordering deep dive).
  • idempotencyKey with a short TTL in a separate small table or cache makes retried posts safe.
  • Author display data is not stored per comment in the normalised form, but the delivered event includes the author's display name and avatar URL, denormalised at write time from a user cache, so realtime servers never need to look anything up per delivery.

Why a key-value or wide-column store? The access patterns are few and fixed: append a comment, read a time range of one video's comments. There are no joins, no multi-row transactions, and no ad hoc queries on the hot path. DynamoDB and Cassandra both give predictable single-digit millisecond writes and range reads on a partition, scale horizontally, and are highly available across zones. DynamoDB's sort key and ScanIndexForward=false map directly onto newest-first pagination. Cassandra's clustering order WITH CLUSTERING ORDER BY (comment_id DESC) does the same. PostgreSQL works too, with an index on (live_video_id, comment_id), and is a sensible choice for a smaller product, but you would need to shard it by video id to reach 50,000 writes per second with headroom. See Choosing a Database: A Decision Guide, Amazon DynamoDB in Practice and Apache Cassandra in Practice.

The hot-partition problem. Partitioning by video id puts a mega-stream's 5,000 writes per second on a single partition. A DynamoDB partition supports roughly 1,000 write units per second, so one partition cannot take it, even with adaptive capacity. The fix is write sharding for hot videos: use partition key liveVideoId#bucket, where bucket = commentId mod B (for example B = 8 to 16 for hot videos, 1 for everyone else). Reads of history then query all B buckets in parallel and merge by comment id, which is cheap because each bucket query returns a sorted page. The stream-mode controller records B per video so readers know how many buckets exist. In Cassandra the same trick also keeps partitions from growing beyond the recommended size (on the order of 100 MB): add a time bucket such as (liveVideoId, hourBucket) to the partition key. See Partitioning and Sharding and Pattern: Scaling Writes.

Recent-comments cache (Redis). Per video, a sorted set keyed by comment id (or a capped list, or a Redis Stream with MAXLEN), trimmed to the last 5 minutes or last 500 comments. It serves the first history page and reconnect replay. Writes are ZADD plus ZREMRANGEBYRANK (or XADD ... MAXLEN ~ 500). Entries expire a short while after the stream ends. See Redis in Practice.

Stream state. A small record per live video: delivery mode (push, sampled, CDN), write-shard count, smoothed viewer count and comment rate. It lives in a replicated in-memory store and is cached by every service, because every write and every connection consults it.

Retention. Comments for a live video are hot while it is live and for a short time after, when people watch the replay. A reasonable policy: keep the full record in the primary store for 30 to 90 days, then move it to columnar files in object storage (Parquet on S3 or similar) for replays, analytics and compliance, with the primary table entries expired by TTL. Hidden comments are retained for trust-and-safety review periods required by policy, and deleted when a user deletes their account, following privacy rules.

Deep Dives#

1) How do we push comments to viewers in real time?#

Polling made the client guess when new comments exist. We want the opposite: the server pushes each comment to interested clients the moment it exists. There are four candidate transports, and the right one depends on the direction and ratio of traffic.

Bad: short polling. Covered above. Load proportional to viewers times poll rate, latency proportional to the poll interval. It fails both the scale and the 200 ms requirement.

Okay: long polling. The client sends a request and the server holds it open until a new comment arrives (or a timeout of, say, 30 seconds), then responds. The client immediately sends the next request. Latency is now near real time and empty responses are rare. But every delivered batch costs a full HTTP request and response, with headers, auth and routing, and there is a gap after each response while the client re-requests, during which new comments queue up. At 5 to 10 comments per second per viewer that overhead dominates. Long polling is a good fallback for networks that break streaming, not a primary transport.

Good: WebSockets. A WebSocket starts as an HTTP request with an Upgrade: websocket header; after the handshake the TCP connection becomes a full-duplex, message-framed channel (RFC 6455, 2011). The server can push any time, and the client can send any time. For chat, multiplayer games and collaborative editing, where both sides talk often, this is the right tool (see the chat system case study).

For live comments, the traffic is badly unbalanced. A viewer reads every comment but almost never writes. A two-way channel adds cost without benefit:

  • WebSockets are a separate protocol after the upgrade. Every layer (load balancers, proxies, WAFs, observability) needs WebSocket-aware handling, and HTTP features such as standard auth middleware, caching headers and HTTP/2 multiplexing do not apply in the usual way.
  • If comments are posted over the socket, the write path loses the standard HTTP toolkit: request-level rate limiting at the gateway, idempotency keys, retries with clear status codes, and request logging. You end up reimplementing them inside your socket protocol.
  • The server must hold state for a bidirectional session it hardly uses.

Great: Server-Sent Events (SSE). SSE is a plain HTTP response that never ends. The client makes a normal GET with Accept: text/event-stream. The server responds with Content-Type: text/event-stream and keeps writing small text events to the response body. In browsers the built-in EventSource API parses events and reconnects automatically. Posting a comment remains a normal HTTP POST. This matches the read/write ratio exactly: a cheap one-way stream for the constant reads, and ordinary requests for the rare writes.

The wire format is just lines of text, which makes it easy to debug with curl:

retry: 3000
id: 1789346123456782337
event: comment
data: {"id":"1789346123456782337","u":"Ana","t":"what a goal"}
 
: keep-alive comment line, sent every 15 s so proxies do not time out
 
event: control
data: {"mode":"cdn","url":"https://cdn.example/lc/lv_123/snap.json"}
  • id: sets the event id. EventSource remembers it and sends it as Last-Event-ID on reconnect. Using the comment id here gives us resumption almost for free.
  • event: names the event type, so one stream can carry comments, control messages (mode switches, "stream ended") and viewer-count updates.
  • retry: tells the client how long to wait before reconnecting.
  • Lines starting with : are comments that the client ignores. They are the standard heartbeat to keep idle connections from being closed by proxies and NATs.

SSE's real-world problems, and the fixes.

  1. Buffering proxies. Some proxies, load balancers and corporate middleboxes buffer response bodies until they are complete or a buffer fills, which turns a stream into nothing at all. Fixes: disable response buffering for the stream route (in NGINX, proxy_buffering off, or send the X-Accel-Buffering: no response header), send Cache-Control: no-cache, avoid compressing the stream at intermediaries that buffer for compression, and send an initial padding or heartbeat event so the client knows the stream is live. Detect broken paths on the client (no event or heartbeat within N seconds) and fall back to long polling.
  2. Per-domain connection limits. Browsers limit HTTP/1.1 connections per origin to about six. Each open EventSource consumes one, so a user with several tabs or several streams open can exhaust them and block other requests to that domain. Fixes: serve SSE over HTTP/2 or HTTP/3, where many streams share one connection (the default limit is usually around 100 concurrent streams), and multiplex several videos onto one stream per client where the product allows it (for example GET /stream?videos=a,b). See HTTP, HTTP/2, HTTP/3 and HTTPS.
  3. Idle timeouts. Load balancers commonly close idle connections after 60 seconds or so. Heartbeats every 15 to 30 seconds keep the connection alive, and the timeout on the stream route should be raised.
  4. Monitoring long-lived requests. Request-duration metrics are meaningless when a request lasts an hour. Instead track connection counts, connection lifetime distributions, events per second, write-queue depth per connection and, most importantly, delivery lag: the time from comment creation to the event being written to the socket, measured per server and sampled per client.
  5. Native mobile apps have no EventSource, but an SSE client is about 100 lines on top of any HTTP library with streaming responses (OkHttp on Android, URLSession on iOS). Some teams prefer WebSockets or a custom protocol over MQTT on mobile; SSE remains a sound default.

What about gRPC streaming or WebTransport? gRPC server streaming over HTTP/2 is the same idea as SSE with binary framing, a good fit for native clients and service-to-service, but awkward in browsers. WebTransport over HTTP/3 offers streams and datagrams with no head-of-line blocking and is promising for very high message rates, but browser and infrastructure support is still uneven, so it is a future option rather than the default.

Decision. SSE for delivery, HTTP POST for writes, long polling as the fallback. Be ready to say why WebSockets would be the right call in a different problem (chat, games), and that "WebSockets everywhere" is also an acceptable answer if you explain the cost. For a fuller comparison see Polling, Long Polling, SSE, WebSockets and Webhooks.

2) How many connections can one server hold, and what limits it?#

With SSE we need one open connection per viewer: 100 million at peak. The first question is how many fit on one machine.

The 65,535 myth. A common misconception is that a server can hold only 65,535 connections because that is the number of ports. But a TCP connection is identified by the four-tuple (source IP, source port, destination IP, destination port). A server listening on port 443 can accept connections from millions of distinct client address and port pairs, all to that one port. The port limit applies to outbound connections from one client IP to one server IP and port, which matters for proxies and load balancers that open many upstream connections from a few IPs (they use multiple source IPs or upstream addresses to avoid running out).

What actually limits a connection server:

  • File descriptors. Each socket is a file descriptor. Raise the per-process and system limits (ulimit -n, fs.file-max, fs.nr_open) to well above the target.
  • Memory. Kernel socket buffers dominate. Default receive and send buffers can be tens to hundreds of KB per socket if autotuning grows them. For mostly idle connections, cap them (net.ipv4.tcp_rmem, tcp_wmem) so each connection costs a few KB in the kernel. Add TLS session state (on the order of 10 to 30 KB per connection in common TLS libraries, less with careful tuning) and the application object.
  • CPU for TLS and writes. TLS handshakes are expensive, so reconnect storms are CPU storms. Session resumption and TLS 1.3 reduce the cost. The steady-state cost is encrypting and writing each event, roughly proportional to messages per second, not connections.
  • The programming model. One thread per connection fails at this scale because of thread stacks and context switches. Use an event loop (epoll on Linux, kqueue on BSD) with a small number of threads, or a runtime designed for millions of lightweight tasks: Netty or Vert.x on the JVM, Go goroutines, Erlang/Elixir processes, Rust with Tokio, or Node.js.
  • Network bandwidth. About 480 Mbit/s per server in our estimate, well within a modern NIC.

Real reference points. The "C10K problem" (Dan Kegel, 1999) asked how to serve 10,000 clients on one server. Event loops solved it, and since then teams have shown far more: WhatsApp's engineers wrote in 2012 about reaching about 2 million TCP connections on a single FreeBSD server running Erlang, and the Phoenix framework team showed about 2 million WebSocket connections on one large machine in 2015. Those were benchmarks with mostly idle connections. Production servers that also push hundreds of thousands of messages per second and must survive the failure of a neighbour typically run at 100,000 to 500,000 connections each.

Plan for headroom, not the maximum. If one server in a group of 10 dies, its viewers reconnect to the other 9, which must absorb an 11% jump at once. Run at 60 to 70% of tested capacity. With 100,000 connections per server as a planning number, 100 million viewers need about 1,000 servers, plus spare capacity across zones.

Kernel and runtime checklist for an SSE server: raise fd limits, tune socket buffers, enable TCP keepalive with sensible intervals (or rely on application heartbeats), set SO_REUSEPORT to spread accepts across worker threads, use TLS 1.3 with session resumption, bound each connection's outbound queue (see the slow-consumer discussion below), and expose per-connection metrics cheaply. For more on capacity work see Capacity Planning and Load Testing.

Slow consumers. A viewer on a poor mobile link may read slower than we write. The kernel send buffer fills, then the application's queue for that connection grows. Unbounded queues turn one slow phone into a memory leak. Each connection gets a small bounded queue (for example 100 events). When it is full, drop the oldest comments for that connection (they are stale anyway) and, if the connection stays stuck, close it and let the client reconnect and catch up from the cache. Dropping comments for one slow viewer is consistent with our availability-first, freshness-first requirements.

3) How do realtime servers learn about new comments? Pub/sub partitioned by video#

Once we have 1,000 realtime servers, viewers of the same video are spread across machines. UserA watches video 1 on server 1. UserB watches video 1 on server 2. A comment on video 1 is posted through the Comment Management Service, which is a different fleet. How does the comment reach both servers? This is the coordination problem, and it is the heart of the design.

The first step is structural: separate the write service from the realtime servers. The Comment Management Service handles about 50,000 requests per second and is stateless. The Realtime Messaging Servers hold 100 million connections and are stateful. They scale on different dimensions (requests versus connections and bytes pushed), they deploy differently (draining connections takes minutes) and they fail differently. Keeping them separate lets each scale independently.

Good: naive pub/sub, every server gets every comment. Use a load balancer with round robin (or least connections) to spread viewers across realtime servers. On connect, the client says which video it watches, and the server records it in a local map:

{
  "lv_1": ["conn_17", "conn_942", "conn_5003"],
  "lv_2": ["conn_88"],
  "lv_9": ["conn_23", "conn_4410"]
}

The Comment Management Service publishes every new comment to a single pub/sub topic. Every realtime server subscribes to that topic, receives every comment, looks up the video in its map, and forwards it to matching connections, or discards it.

It works and is simple, which is why it is the right first answer. But at scale it is wasteful. With round robin, each server holds viewers of tens of thousands of different videos, yet it must process all 50,000 comments per second, most of which it throws away. Across 1,000 servers that is 50 million internal messages per second, and each server spends CPU deserialising and discarding. Worse, the waste grows with the product of comment rate and server count: double the traffic and you double both factors, so internal load quadruples.

Great: partitioned pub/sub plus viewer co-location. Two changes together fix this.

Change 1: partition the stream into channels. Instead of one topic, use N channels and publish each comment to channel hash(liveVideoId) mod N. A realtime server subscribes only to the channels for videos its viewers are watching. A channel per video would be the most precise, but with a million concurrent videos (and churn as streams start and end) a channel per video may be too many for some systems. Kafka in particular is not designed for millions of short-lived topics or partitions. Hashing into a fixed N (say 10,000 to 100,000 channels) bounds the channel count, at the cost of some false sharing: a server receives comments for other videos that hash to the same channel, and discards them.

Change 2: co-locate viewers of the same video. Partitioning alone is not enough. With round robin, each server still has viewers of thousands of videos, so it ends up subscribed to most channels anyway, and we are back to receiving nearly everything. The fix is intelligent routing: a Layer 7 load balancer inspects the request path (/live-videos/{id}/comments/stream) and uses consistent hashing on the video id to choose the server. All viewers of video 1 go to server 7. Now each server hosts a coherent set of videos and subscribes only to their channels. NGINX (hash $video_id consistent), Envoy (ring hash or Maglev load balancing on a header or path-derived key) and HAProxy all support this.

What this buys. A small video's viewers are all on one server, so each comment crosses the pub/sub layer once and is delivered to one server. Internal traffic falls from "comments × servers" to roughly "comments × servers per video", which is 1 for almost every video. The realtime servers now spend their CPU on delivery, not on discarding.

Big videos need more than one server. A video with 2 million viewers cannot fit on one server that holds 100,000 connections. Consistent hashing alone would send all 2 million to one machine and melt it. Two common fixes:

  • Bounded-load consistent hashing. Each server has a capacity cap (for example 1.25 times the average load). If the hash target is full, the request walks clockwise to the next server on the ring. A hot video naturally spreads over consecutive servers, and each of them subscribes to that video's channel. This technique was described by Mirrokni, Thorup and Zadimoghaddam in "Consistent Hashing with Bounded Loads" (SODA 2018), and Google and Vimeo have written about using it in load balancing.
  • Explicit sub-sharding. For videos marked hot by the stream-mode controller, route to hash(videoId, viewerId mod K), spreading viewers across K servers deliberately. K grows with the viewer count.

Either way, a comment on a video with 2 million viewers is delivered to about 20 servers, and each writes it to its 100,000 local connections. The pub/sub layer handles 20 messages; the realtime tier handles 2 million socket writes. That is the right split: socket writes are what realtime servers are for.

The hard part: keeping routing and subscriptions in sync. When a server's set of hosted videos changes, its subscriptions must follow:

  • On the first viewer of a video arriving on a server, subscribe to its channel. On the last viewer leaving, unsubscribe after a grace period (for example 30 seconds) to avoid thrashing when viewers flap.
  • When servers are added (scale-out at the start of a big event), consistent hashing moves about 1/M of the videos to the new server. New connections for those videos go to the new server, but existing connections stay on the old one until they reconnect, so for a while a video's viewers are split across old and new servers. That is fine: both subscribe to the channel. Over time, connections naturally migrate as viewers reconnect, or the old server can gently shed connections for videos that no longer hash to it, telling clients to reconnect (with jitter) so they land on the new owner.
  • When a server dies, its viewers reconnect and are routed by the hash ring to the next server, which subscribes to their channels on the first connection. Replay from the recent-comments cache covers the gap.

Which pub/sub system?

  • Redis Pub/Sub is a strong fit. It is in-memory, adds well under a millisecond of latency inside a data centre, and handles dynamic subscribe and unsubscribe cheaply, which matters because servers change their subscriptions constantly. It is fire-and-forget: a subscriber that is disconnected misses messages, and there is no replay. That is acceptable here because comments are persisted in the database and the recent-comments cache, and reconnecting servers or clients catch up from there. A caveat: in classic Redis Cluster, a PUBLISH is broadcast to every node in the cluster, which limits scaling. Sharded pub/sub, added in Redis 7.0 (SPUBLISH and SSUBSCRIBE), keeps each channel on the node that owns its hash slot, so the cluster scales with nodes. Use sharded pub/sub, or run several independent Redis instances and pick one by channel hash.
  • Kafka is durable, replayable and very high throughput, but it is designed for a moderate number of long-lived topics and partitions with consumer groups that rebalance. Subscriptions that change every second (servers adding and dropping videos) do not fit consumer-group semantics well; a realtime server would have to consume whole partitions and filter, which recreates the naive waste. Kafka is a great choice behind the write path, for durable event logs feeding moderation, analytics and the CDN snapshotter, not for the last-hop fan-out. See Apache Kafka in Practice.
  • NATS (a lightweight, subject-based pub/sub system with cheap dynamic subscriptions and wildcard subjects) and purpose-built in-house brokers are other good fits. Google Cloud Pub/Sub and SNS are better at durable, moderate-rate topics than at millisecond fan-out with high subscription churn.

For a broader treatment of these systems see Pub/Sub and Event Streaming and Delivery Guarantees: At-Most, At-Least and Exactly-Once. Here, at-most-once delivery on the hot path plus a durable store for catch-up is exactly the right trade.

4) An alternative: a dispatcher service instead of pub/sub#

Pub/sub makes the realtime servers responsible for deciding what they want (they subscribe). The dispatcher design inverts this: a central routing service knows which servers host viewers of which video, and pushes each comment directly to exactly those servers.

How it works.

  1. When a realtime server gains its first viewer of a video, it registers with the dispatcher: "server 17 now hosts video lv_1". When it loses its last viewer, it deregisters. It also sends periodic heartbeats listing its videos, so the dispatcher can expire entries for servers that die without deregistering.
  2. The dispatcher keeps a map from video id to the set of servers, for example lv_1 -> {s17, s203, s988}. The authoritative copy lives in a coordination store such as ZooKeeper or etcd, or in a replicated key-value store, and each dispatcher instance caches it in memory.
  3. When the Comment Management Service accepts a comment, it calls the dispatcher (or the dispatcher consumes the write log). The dispatcher looks up the servers for that video and sends the comment to each one over a persistent RPC connection (gRPC streams or a custom TCP protocol).
  4. Each realtime server forwards to its local connections, as before.

Why choose it.

  • No subscription management in the brokers. There are no channels and no false sharing; a comment goes to exactly the servers that need it.
  • Centralised routing logic is easier to reason about, test and change. Load-aware routing, region-aware fan-out, priority lanes for broadcaster comments, or per-video rate shaping can live in one place without changing the realtime servers.
  • Works with any load-balancing policy. Because the dispatcher knows exactly where viewers are, co-location becomes an optimisation rather than a correctness requirement. Round-robin routing still works; it just means more servers per video.

The costs.

  • Keeping the map fresh. During a viral spike, thousands of servers register for a video within seconds. The dispatcher must see these quickly, or it will miss servers, and those servers' viewers will miss comments until the map catches up. Multiple dispatcher instances must agree on the map, which needs either a watched coordination store (ZooKeeper or etcd watches) or short-lived caches with frequent refresh, and careful invalidation.
  • Another hop and another tier to scale. The dispatcher must handle 50,000 comments per second multiplied by servers per video. Shard dispatchers by video id so each instance owns a slice of videos and their maps, which also removes most cross-instance cache coherence problems.
  • Failure semantics. If a dispatcher instance fails mid-forward, some servers get a comment and others do not. As with pub/sub, the recent-comments cache and client catch-up make this tolerable.

A note on coordination stores. ZooKeeper and etcd are built for small, strongly consistent metadata with watches, not for very high write rates. Registrations for 1 million videos across 1,000 servers, with churn as viewers come and go, can be a lot of writes. Batch registrations (each server heartbeats its full video set every few seconds rather than writing on every change), or keep the map in a sharded in-memory store and use the coordination service only for dispatcher membership. See ZooKeeper and etcd and Leader Election and Coordination Services.

Real-world echo. A LinkedIn engineer described a design of this shape in a QCon talk on real-time likes and comments for live videos ("Streaming a Million Likes/Second: Real-Time Interactions on Live Video"): frontend servers hold persistent SSE connections and record which live videos their clients watch in a subscription table, and a dispatcher layer consults that table to send each event only to the frontends that need it, with dispatchers in each data centre.

Pub/sub or dispatcher? Both are strong answers. Partitioned pub/sub with co-location has fewer moving parts and fewer corner cases, because a mature broker already handles subscriber membership. It is the one to reach for first in an interview. The dispatcher is attractive when you need rich routing rules or when your organisation already runs a good service-discovery and coordination stack. Mentioning that you considered both, and why you chose one, is what interviewers look for.

5) What happens when one stream goes mega-viral?#

Our coordination designs handle typical videos and even large ones. Now consider a World Cup final or a global product launch: tens or hundreds of millions of viewers on one video, and thousands of comments per second.

Start with a human fact. At 5,000 comments per second with about 4 words each, a viewer would need to read 20,000 words per second. That is roughly the length of a long novel such as War and Peace (well over half a million words) in under 30 seconds. If the screen shows the last 20 comments, each one is visible for about 4 milliseconds. Nobody can read that. At this scale the goals change. Viewers are not following a conversation; they are feeling the energy of a crowd. Delivering every comment with 200 ms latency is not just expensive, it is pointless.

So the requirements themselves shift at extreme scale. Recognising that is the staff-level insight. The design responds in layers.

Layer 0: a fan-out tree inside the realtime tier. Even before reducing what we send, we should not have a single publisher push one message to 1,000 servers in a loop. For very hot videos, use a two-level tree: the pub/sub channel (or the dispatcher) delivers to a set of relay nodes, and each relay forwards to a group of realtime servers. Discord described a related technique for fanning out guild events across Elixir nodes: batching messages per destination node so that one inter-node message carries an event for many processes (their open-source "Manifold" library). Batching per destination and trees of relays both keep any single node's fan-out bounded.

Good: show a representative subset (sampling). Each viewer does not need every comment, only enough to sense the crowd. Keep a target display rate per viewer, for example 5 to 10 comments per second, and sample the stream to hit it:

  • At 20 comments per second, deliver all of them.
  • At 100 per second, sample about 10%.
  • At 5,000 per second, sample about 0.2%.

The sampling rate adapts to the observed comment velocity (for example an exponentially weighted moving average of the last few seconds), so every viewer sees a steady, readable flow regardless of how busy the stream is.

Sampling does not have to be uniform. We can bias the sample towards comments viewers are more likely to value:

  • Comments from people the viewer follows or is friends with (personalised, so it must be done per viewer or per small viewer cohort on the realtime server).
  • Comments from the broadcaster, moderators or verified accounts (always shown).
  • Comments that are getting reactions quickly (an early engagement signal).
  • Diversity: avoid showing ten copies of "GOAL" by de-duplicating near-identical text.
  • Down-weight low-quality signals: new accounts, comments flagged by spam classifiers, repeated text.

Sampling and ranking are covered in more depth in the next deep dive.

Sampling cuts the bytes pushed, but we still hold millions of SSE connections to one video and push to all of them several times per second. The connection and per-event costs remain large.

Great: CDN-based delivery with periodic snapshots. For the very largest streams, change the delivery model entirely: from push to pull from a CDN.

  • Server side. A hot-stream aggregator for the video keeps a ring buffer of the most recent 100 to 200 selected comments (sampled and ranked). Every second (or every 500 ms) it serialises the buffer into a small JSON snapshot, perhaps 20 to 40 KB, with a sequence number and a timestamp, and writes it to the CDN origin (an object store or a small origin service backed by Redis).
  • CDN. The edge caches the snapshot with a TTL of about 1 second. When thousands of clients request it at the same edge at once, the CDN's request coalescing (also called collapsed forwarding) sends a single request to the origin and serves everyone from the result. Millions of viewers become a few thousand origin requests per second, one per edge location per second.
  • Client side. Instead of an SSE connection, the client polls the snapshot URL every second. It compares sequence numbers, takes comments it has not seen, and animates them smoothly across the next second, spaced using their timestamps, so the feed looks continuous rather than jumping once per second.

A CDN is already built to send the same bytes to millions of people; that is its whole job. A comment snapshot is just another small, cacheable object, no different in kind from a video segment or a thumbnail. Live video itself is delivered this way: HLS and DASH players poll a playlist and fetch segments from the CDN, and Facebook's engineers have written about edge request coalescing for live video segments when a popular stream starts. Comments simply ride the same infrastructure.

Trade-offs of CDN delivery.

  • Latency rises from under 200 ms to 1 to 2 seconds (snapshot interval plus edge TTL plus poll interval). For a mega-stream this does not matter: the comments are a vibe, and the video itself is usually several seconds behind real time anyway.
  • Read-your-own-writes. The author must see their comment immediately. The client inserts it locally as soon as the post succeeds, independent of the snapshot, and dedupes when (or if) it appears in a later snapshot. Since sampling may never include it, the client must not wait for it.
  • Cost moves from realtime servers to CDN egress. At 30 KB per snapshot per second, 10 million viewers pull 300 GB/s at peak, about 2.4 Tbit/s. That is a lot, but CDNs are priced and provisioned for it, and delta encoding (only comments newer than the client's last sequence, served as small immutable "since N" objects) or compression (gzip or Brotli shrink JSON text by 3 to 5 times) cuts it substantially.
  • Mode switching. The controller flips a video into CDN mode when it crosses a threshold such as 100,000 viewers or 500 comments per second, and back when it falls below a lower threshold. The gap between the two is hysteresis: without it, a stream hovering at the threshold would flip back and forth, causing reconnect storms each time.

The switch itself is a control event sent over the SSE stream ("mode: cdn, url: ..."), or a field in the snapshot ("mode: push, reconnect now"). Clients that miss the control event discover the mode on their next reconnect, because the stream endpoint can reply with a redirect to the snapshot URL. To avoid a reconnect storm on the way back from CDN to push, the switch-back instruction includes a random delay window so clients reconnect over 30 to 60 seconds, not all at once.

Summary of the three regimes. For most videos, partitioned pub/sub with co-location (or a dispatcher) handles everything with full fidelity and sub-200 ms latency. For big videos, sampling keeps the push volume readable and bounded. For mega-streams, CDN snapshots make the cost almost independent of viewer count, at the price of about a second of latency that nobody can perceive in that context. Explaining sampling shows strong understanding; arguing for the CDN model, because the requirements change at extreme scale, shows staff-level thinking.

6) How do we sample and rank comments so a huge stream stays readable?#

"Show a sample" is easy to say. Doing it well, cheaply and fairly, is an algorithm problem in its own right.

Basic: uniform random sampling at a fixed rate. Keep each comment with probability p. Simple and stateless, but a fixed p is wrong almost all the time: too sparse when the stream is quiet, too dense when it peaks. It also treats a broadcaster's reply the same as spam.

Better: velocity-adaptive sampling. Measure the incoming rate λ (comments per second) with an exponentially weighted moving average over a few seconds, and set the keep probability to p = min(1, r / λ), where r is the target display rate (say 8 per second). At λ = 4, p = 1 and everything is shown. At λ = 800, p = 0.01. The expected output rate stays near r. Bursts are smoothed by the EWMA, and a short burst can be absorbed with a small token bucket (capacity a few seconds of r) so that a sudden "GOAL" moment shows a slightly higher rate before settling.

An alternative that avoids estimating λ is reservoir sampling per time window: in each 1-second window, keep a uniform random sample of exactly k comments from however many arrive, using one pass and O(k) memory. Vitter's "Random Sampling with a Reservoir" (ACM Transactions on Mathematical Software, 1985) is the classic reference. At the end of each window, emit the reservoir. This is a natural fit for the snapshot model, which already works in 1-second ticks.

Best: weighted, personalised and diverse selection. Real products want the best comments, not random ones:

  1. Score each comment at ingest with cheap features: author is the broadcaster or a moderator (always shown), author is verified, author's history and spam score, text quality (length, language, not all caps, not a repeat), and early engagement (reactions in the first second or two). This is a lightweight model or a hand-tuned formula, evaluated in microseconds.
  2. Weighted sampling. Use the score as a weight. Efraimidis and Spirakis ("Weighted random sampling with a reservoir", Information Processing Letters, 2006) give an elegant one-pass method: for each item with weight w, draw u uniformly in (0, 1), compute key = u^(1/w), and keep the k items with the largest keys (a min-heap of size k). Higher-weight comments are more likely to survive, but low-weight ones still have a chance, which keeps the feed feeling organic rather than curated.
  3. Diversity. Suppress near-duplicates: normalise text (lowercase, strip punctuation and repeated letters) and hash it; if a hash has appeared many times in the last few seconds, keep one representative and optionally show an aggregate ("2,300 people said GOAL"). For fuzzier matching, MinHash or SimHash signatures detect near-identical text cheaply. Counting how often each normalised text appears is a heavy-hitters problem that a Count-Min sketch (Cormode and Muthukrishnan, 2005) solves in fixed memory; see Probabilistic Data Structures for Big Data.
  4. Personalisation at the edge. A global sample is the same for every viewer and can be computed once per video. Personal boosts (friends' comments) must be applied per viewer. Do this on the realtime server: it receives the global sample plus a small "social" side stream (comments whose authors are friends with any of its local viewers, which requires a social graph check at fan-out time), and merges per connection. On the CDN path, personal comments cannot be in the shared snapshot, so a viewer's friends' comments can arrive over a tiny per-user channel (or are simply skipped for mega-streams, which is often acceptable).
  5. Guarantees. Some comments must bypass sampling: the viewer's own comments (shown locally), the broadcaster's comments, pinned comments and moderator messages.

Where sampling runs. For a hot video, run one aggregator per video (or a few, each handling a hash range of authors) that receives the full comment stream from the write path, scores and samples, and publishes the sampled stream to the video's pub/sub channel or the snapshot ring buffer. The full stream still goes to the database, so history and replays can show everything. Sampling is a delivery decision, not a storage decision.

Fairness and trust. Ranking decides whose voice is heard. Be explicit about the policy (for example, no paid boosting), keep it auditable, and expose a "show all comments" or "top comments" toggle where the product allows. YouTube Live, for example, offers a "Top chat" view that filters out potential spam and a "Live chat" view that shows everything.

7) How do we store comments and paginate history at this scale?#

We chose a partitioned key-value store with (liveVideoId, commentId) as the key. Several issues remain.

The join stampede. When a celebrity starts a stream and sends a notification, a million viewers may join within a minute, each asking for "the latest 50 comments". Sending these to the database would be a hot-key read storm on one partition. Layers of defence:

  • Recent-comments cache. A per-video bounded buffer in Redis serves page 1. Its hit rate for active videos is close to 100%.
  • Materialised first page. For hot videos, the hot-stream aggregator writes "latest 50" as a single precomputed blob every second. All joiners get the same bytes, which can even be served from the CDN with a 1-second TTL, exactly like the mega-stream snapshot.
  • Request coalescing in the service. If a cache entry is missing, only one request per video rebuilds it, and the others wait for that result (single flight). See Cache Failure Modes: Stampedes, Hot Keys and Penetration.
  • Replicating hot keys. A single Redis key can serve on the order of 100,000 simple reads per second on one node. For more, replicate hot keys to several nodes or read replicas, or cache the first page in the service's local memory for a second.

Deep history. Scrolling back past the cache goes to the database. With write sharding for hot videos (B buckets), the service queries all B buckets in parallel for "the 50 newest comments older than cursor", then merges the B sorted lists and returns the top 50. Each bucket query reads at most 50 items, so the cost is B small queries; with B = 8 that is fine for the small fraction of users who scroll back far.

Opaque cursors. Return the cursor as an opaque, signed token (for example base64 of {commentId, bucketCount, direction} with an HMAC) rather than a raw id. That lets you change the encoding (adding bucket positions, or a timestamp for time-bucketed partitions) without breaking clients, and stops clients from forging cursors that trigger expensive scans.

Deletes and moderation. Comments removed by moderation are marked hidden rather than physically deleted, so cursors that point at them still work. Reads filter them out, which can make a page come back short. The service keeps reading until it has a full page or reaches a scan limit, and returns the cursor of the last row it examined. Moderation also publishes a "remove comment X" event on the live channel so clients delete it from screen; this matters because harmful comments must disappear fast, not just from history.

DynamoDB specifics. A partition sustains roughly 1,000 write capacity units and 3,000 read capacity units per second; adaptive capacity helps but cannot make one partition infinitely hot. A single Query returns at most 1 MB per call, more than enough for a 50-comment page. Items are limited to 400 KB, which is irrelevant for comments. Use on-demand capacity for spiky live traffic, or provisioned capacity with auto-scaling plus write sharding for known big events.

Cassandra specifics. A partition is stored together on each replica. Very large partitions (many hundreds of MB) slow compaction and repairs, so time-bucket the partition key for long streams: PRIMARY KEY ((live_video_id, hour_bucket), comment_id) with CLUSTERING ORDER BY (comment_id DESC). Reads for history start in the current bucket and move back one bucket when exhausted. Use LOCAL_QUORUM for writes only if you need it; ONE or LOCAL_ONE is often enough for comments, in keeping with availability over consistency. See Quorums and Leaderless Replication.

What about writes during a mega-stream? 5,000 comments per second for one video is easy for the cluster as a whole once spread over buckets. The bigger risk is the side effects of each write: idempotency check, rate-limit check, spam classifier, publish. Keep them all O(1) and in memory, and push anything slow (such as an expensive moderation model) to an asynchronous consumer of a Kafka log that can hide the comment a second later if needed.

8) How are comments ordered, and does order matter?#

Order matters less than in chat, but it still matters: comments should appear in roughly the order they were written, history pages must be stable, and the same comment should not appear twice. And there is a subtle second ordering problem: comments versus the video timeline.

Basic: order by server arrival time. Assign createdAt from the Comment Management Service's clock and sort by it. Different servers' clocks differ by milliseconds (or more if NTP is misbehaving), so two comments posted 1 ms apart via different servers may be ordered wrongly. Timestamps also collide, so they cannot serve as unique cursors.

Better: time-ordered unique ids (Snowflake-style). Generate a 64-bit id with a millisecond timestamp in the high bits, then a worker id, then a per-worker sequence number. Twitter's Snowflake (2010) used 41 bits of time, 10 bits of machine id and 12 bits of sequence, enough for 4,096 ids per millisecond per worker. These ids are unique without coordination, sortable by time to within clock skew, and make perfect cursors because the table is sorted by them. Their weakness is the same clock skew: ordering across workers is only approximate. For live comments, approximate is fine: no one can tell whether two comments posted in the same 5 ms appeared in the "right" order. See Unique ID Generation.

Best when you need it: a per-video sequence. If the product needs a strict total order per video (for example to detect gaps exactly on the client), give each video a sequence number assigned by a single owner: a Redis INCR on seq:{videoId}, or the partition leader of a log partitioned by video. Each comment carries (videoId, seq). Clients can then detect gaps ("I have 1,204 and 1,206, so 1,205 is missing") and fetch exactly the missing ones. The cost is a serialisation point per video. At 5,000 comments per second, one Redis key handles it easily, but it is one more dependency on the write path. A reasonable compromise is to use Snowflake ids as the primary key and cursor, and add the per-video sequence only for hot videos where gap detection is useful. For background on why clocks cannot give a total order, see Time, Clocks and Ordering, which covers Lamport's 1978 paper "Time, Clocks, and the Ordering of Events in a Distributed System" and hybrid logical clocks.

Client-side ordering. Events can arrive out of order: a comment published by one service instance may overtake one published slightly earlier by another, and catch-up responses overlap with the live stream. The client keeps a small reorder buffer: it holds incoming comments for, say, 100 to 200 ms, sorts by id, and then renders. It dedupes by comment id using a bounded set of recently seen ids. This adds a little latency and removes visible jitter.

The video timeline problem. Live video is not live. HLS and DASH streams are typically several seconds to 30 seconds behind real time, depending on segment length and player buffer; low-latency modes bring this down to a few seconds. Comments over SSE arrive in about 200 ms. So a viewer whose player is 15 seconds behind sees "GOAL!!!" in the comments 15 seconds before the goal. Fixes:

  • Tag comments with video time. The commenter's client sends videoTimeMs, its playback position (derived from the stream's presentation timestamps) when the comment was typed.
  • Delay display on the viewer. Each viewer's client knows its own playback position. It holds each comment until its own playback reaches the comment's videoTimeMs (minus a small allowance), then shows it. Viewers far behind the live edge see comments in sync with what they are watching. Viewers at the live edge see them almost immediately.
  • Replays. After the stream ends, the same field lets a replay show comments in sync with the recording, the way YouTube's live chat replay and Twitch's chat replay on past broadcasts do, and the way Japanese and Chinese "danmaku" (bullet comment) sites such as Niconico and Bilibili overlay comments at specific video moments.

This is a nice point to raise unprompted in an interview because it shows you understand the whole product, not just the message bus.

9) How do we handle disconnections so viewers do not miss comments?#

Mobile networks are unreliable. People walk into lifts, switch between Wi-Fi and cellular, lock their phones and background the app. A good live comments client survives all of this and puts the viewer back where they were.

Bad: ignore disconnections. On reconnect, just start receiving new comments from now. Any comment posted during the gap is gone for this viewer. For a five-second Wi-Fi hiccup during a tense moment in a match, the viewer misses every reaction to the big play, and the feed visibly jumps. After a longer gap they return to a conversation with no context.

Good: client-driven catch-up over HTTP. The client stores the id of the last comment it rendered (in memory, plus localStorage on web or app storage on mobile). On reconnect it calls GET /comments?since={lastId}&limit=100 and merges the result with the new stream. This works with any transport and gives the client full control over the UX. Its weakness is coordination: comments arriving on the new stream while the HTTP request is in flight overlap with the response, so the client must dedupe by id and sort before rendering.

Great: SSE's Last-Event-ID, a shared recent-comments cache, bounded replay and smart clients.

  1. Built-in resumption. Every SSE event carries id: <commentId>. When the connection drops, the browser's EventSource reconnects automatically (after the retry: delay) and sends Last-Event-ID: <commentId>. The server sees the header and replays everything after that id before resuming the live stream. No client code is needed in the browser.
  2. Any server can replay. After reconnecting, the viewer probably lands on a different realtime server (the old one may have crashed, or scaling has moved the hash ring). So replay must not depend on local memory. The shared recent-comments cache in Redis (per video, last few minutes) lets any server answer "comments after X for video V" in a millisecond. See Distributed Caching with Redis and Memcached.
  3. Bounded replay. Replay at most the last 5 minutes or a few hundred comments. If Last-Event-ID is older than the cache window, send a truncated control event; the client shows "jump to live" and the viewer can still scroll back through history via the paginated API. Replaying an hour of comments would flood both the server and the viewer for no benefit.
  4. Replay through the same sampling. For sampled or mega streams, replay the sampled history, not the full firehose, so a reconnecting viewer does not get a 10,000-comment dump.
  5. Thoughtful UX. Instead of showing 47 missed comments instantly, animate them at 2 to 3 times speed or show "You missed 47 comments" with "jump to live". The viewer stays oriented.
  6. Mobile lifecycle. When the app is about to go to the background, close the SSE connection deliberately and record the last id. Mobile operating systems throttle or kill background sockets anyway, and holding them wastes battery and radio time. On foregrounding, reconnect with the stored id and catch up. See Client, Mobile and Frontend Considerations and Mobile System Design.
  7. Detect dead connections. A connection can die silently (a NAT drops state, a phone loses coverage) with no TCP reset. The server sends a heartbeat comment line every 15 to 30 seconds; if the client sees nothing for two heartbeat intervals, it assumes the connection is dead and reconnects. The server detects dead clients when writes start failing or the send queue stops draining, and frees the connection.

Avoiding gaps and duplicates in the merge. Because comment ids are time-sortable, the client's state is just "the highest id rendered" plus a bounded set of recent ids. Every source (live stream, replay, HTTP catch-up, CDN snapshot) is merged through the same function: drop ids already seen, sort the rest by id, render through the reorder buffer. If the product uses a per-video sequence, gap detection is exact: a missing sequence number triggers a targeted fetch.

Reconnect storms. When a realtime server with 100,000 connections dies, all 100,000 clients reconnect. If they all do it in the same second, the remaining servers face a wave of TLS handshakes and replay reads, and the Redis cache receives 100,000 replay requests for the same few videos. Defences:

  • Randomised exponential backoff with jitter on the client: first retry after a random 0 to 1 second, then up to 2, 4, 8 seconds and so on, capped. AWS's 2015 architecture blog post "Exponential Backoff And Jitter" by Marc Brooker showed why full jitter spreads load best.
  • Replay coalescing on the server. Many reconnecting viewers of the same video ask for nearly the same range. A server can fetch "last 5 minutes of video V" once and serve every local replay from that result.
  • Admission control. Servers cap their accept rate and the load balancer spreads new connections; clients that are refused retry with backoff.
  • Server-directed retry. The retry: field lets the server lengthen the reconnect interval during an incident.

See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

10) How do we protect the write path: rate limits, spam and bursts?#

Integrity is below the line in this problem, but the write path must still be designed so integrity checks can plug in without hurting latency.

Per-user and per-video rate limits. A token bucket per user (for example 1 comment per second, burst 5) stops a single account from flooding a stream. A per-video limit protects the system during mega-events; above it, the service still accepts comments into storage (so authors see them) but excludes them from fan-out, which is effectively sampling at the door. Redis-backed counters or a local approximate limiter per service instance work; see Rate Limiting and Throttling.

Slow mode and subscriber-only mode. Broadcasters can turn on slow mode (each user may comment once every N seconds) or restrict comments to followers or subscribers. YouTube and Twitch both offer slow mode. These are product controls, but they are also the best load-shedding lever, because they reduce comments at the source.

Synchronous versus asynchronous checks. The 200 ms budget leaves room only for cheap checks on the hot path: authentication, rate limit, length, a blocklist of words, and a fast reputation score. Heavier checks (machine-learning classifiers for hate speech and spam, link scanning, image checks if images are allowed) run asynchronously on a Kafka log of new comments. If a classifier flags a comment, the moderation service marks it hidden and publishes a removal event, and clients delete it from screen. Most harmful comments disappear within a second or two. For high-risk streams (for example, a broadcaster who is being targeted), the product can switch to hold-for-review, where comments are only fanned out after passing the classifier, accepting higher latency.

Shadow handling. A common trust-and-safety technique is to show a suspected spammer's comment to the spammer only (the client already shows it locally), while excluding it from fan-out. The spammer has no immediate signal that they were filtered.

Bursts. A goal in a football match produces a spike of comments within a second. The write tier must absorb a sudden multiple of the normal rate. Stateless service instances scale out over minutes, too slowly for a burst, so keep headroom and design every hot-path dependency to be O(1). If the database briefly throttles a hot partition, buffer writes in a durable log (Kafka) and let a consumer write them to the database, while publishing to the live fan-out immediately, because freshness matters more for live viewers than durability ordering.

Idempotency. Each post carries an Idempotency-Key. The service stores key -> commentId for a few minutes (in Redis with a TTL). A retry with the same key returns the stored comment. Without this, retries on flaky mobile links create duplicate comments, which are both ugly and a vector for accidental spam.

11) How do we deploy, balance and drain long-lived connections?#

Stateless services can be redeployed by replacing instances. A realtime server holding 100,000 connections cannot just be killed, because that triggers a reconnect storm and a visible gap for every viewer on it.

Graceful draining. To deploy a new version, take one server out of the load balancer pool so it receives no new connections. Then gradually close its existing connections over a few minutes (for example 1% every few seconds), sending each client a control event: "please reconnect", with a jittered delay. Clients reconnect with their Last-Event-ID, land on another server, and replay the gap from the recent-comments cache. Viewers see nothing more than a brief pause. A rolling deploy of 1,000 servers in batches of 5% takes about an hour, which is fine for this tier. See CI/CD and Deployment Strategies.

Load balancer choice. Two layers are common:

  • Layer 4 (TCP) load balancers at the edge, such as Maglev-style or other ECMP-based balancers, spread raw connections across many Layer 7 proxies. They are fast and stateless with respect to HTTP.
  • Layer 7 proxies (Envoy, NGINX, HAProxy) terminate TLS, read the video id from the path, and pick the realtime server by consistent hash. They must be configured for streaming: no response buffering, long idle timeouts on the stream route, and HTTP/2 to clients.

The proxies themselves now hold one client connection and one upstream connection per viewer, which doubles connection counts in that tier. Some designs let the realtime servers terminate TLS directly behind Layer 4 balancing with a consistent-hash routing step done by the client (it asks a lightweight "where should I connect for video V" endpoint first). See Forward Proxy vs Reverse Proxy vs API Gateway.

Rebalancing after scale-out. Long-lived connections do not rebalance on their own. When new servers join before a big event, only new connections go to them. If the event is already under way, the old servers stay hot. Options: pre-scale before scheduled events (sports, launches) using the event calendar; let servers shed a fraction of connections for videos that no longer hash to them; cap connection lifetime (for example 30 to 60 minutes, with jitter) so the fleet naturally rebalances over time.

Health and overload signals. Health checks for realtime servers should consider connection count, event-loop lag, outbound queue depth and delivery lag, not just "process is alive". A server whose event loop is lagging should stop accepting new connections before it starts dropping events.

Observability. The key service level indicator is end-to-end delivery lag: time from comment accepted to comment written to the viewer's socket, sampled per server, and ideally the time until rendered, reported by a sample of clients. Track p50, p99 and p99.9 per region. Also track connections per server, connection churn, reconnect rate, replay volume, pub/sub publish-to-receive latency, dropped events for slow consumers and the number of videos in each delivery mode. See Observability: Logs, Metrics and Traces.

12) How do we serve a global audience across regions?#

A global event has viewers on every continent. Speed-of-light round trips between continents are 70 to 200 ms, so a single-region design cannot meet a 200 ms end-to-end target for everyone.

Basic: one region. All viewers connect to one region. Viewers far away pay one long round trip on the connection (once) and on every push (the latency of each comment). Simple, but the far-away experience is poor and the region is a single point of failure.

Better: regional realtime tiers, global write path. Run realtime servers and pub/sub in each region, close to viewers. Comments are written to the video's home region (or the commenter's nearest region), stored, and then replicated to every region's pub/sub through a cross-region bridge: a small relay per region subscribes to local channels and republishes into remote regions. Each region fans out to its own viewers. A comment crosses an ocean once per region, not once per viewer.

Best: write locally, fan out regionally, store globally. Commenters post to their nearest region. The comment service there assigns the id, publishes to the local fan-out immediately (local viewers see it in about 100 ms), and appends it to a replicated log that delivers it to other regions within 100 to 300 ms. Storage uses a multi-region table (DynamoDB global tables or Cassandra with multi-datacenter replication), accepting eventual consistency between regions, which our requirements allow. Each region's recent-comments cache is fed from the same replicated stream, so reconnect replay works everywhere. See Multi-Region and Global Data.

Ordering across regions. Snowflake-style ids include a region or worker id, so they remain unique. Order across regions is approximate (clock skew plus replication delay), which is fine for comments. A European viewer may see a European comment a fraction of a second before an Asian comment that was posted slightly earlier. Nobody notices.

Mega-streams globally. CDN snapshots are naturally global: each region's aggregator merges its local comments with the replicated stream from other regions, and the CDN serves the snapshot from the nearest edge. Alternatively, one global aggregator for the video produces the snapshot, which simplifies merging at the cost of about 100 ms more latency for distant commenters, which does not matter in CDN mode.

Region failure. If a region fails, its viewers' connections drop and DNS or anycast steers reconnects to the next nearest region. That region's recent-comments cache already holds the replicated stream, so replay works. Plan each region with enough headroom to absorb a neighbour's viewers, or accept degraded mode (sampling more aggressively) during a regional failover. See Disaster Recovery and Backups.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Mega-stream with millions of viewersPush volume explodes, realtime servers saturate, latency climbs for everyoneAdaptive sampling, relay fan-out tree, switch to CDN snapshots above a threshold, hysteresis on the way back
Hot write partition for one videoDatabase throttles writes, posts fail or slow downWrite sharding videoId#bucket for hot videos, on-demand capacity, durable log buffer in front of the database
Join stampede at stream startMillions of history reads on one key, cache and database overloadRecent-comments cache, precomputed first page, single-flight rebuild, CDN-cached first page for hot videos
Realtime server crash100,000 viewers disconnected, reconnect stormJittered exponential backoff, Last-Event-ID replay from shared cache, headroom of 30 to 40% per server group
Pub/sub node failureComments for some channels not delivered for secondsReplicated or sharded pub/sub, servers resubscribe on failover, clients catch up from the cache; durability lives in the database
Naive broadcast pub/subEvery server processes every comment, internal traffic quadratic in growthPartition channels by hash of video id, co-locate viewers with consistent hashing, or use a dispatcher
Stale dispatcher map during viral growthNewly registered servers miss commentsWatches on the coordination store, frequent heartbeats with full video sets, shard dispatchers by video id
Slow consumers on bad networksPer-connection queues grow, memory pressure on the serverBounded per-connection queues, drop oldest events, close stuck connections and let clients catch up
Proxy buffering or idle timeouts on SSEStream appears dead, comments arrive in bursts or neverDisable buffering on the route, heartbeats every 15 to 30 s, raised idle timeouts, long-polling fallback
Browser connection limitsExtra tabs or streams block, page requests stallHTTP/2 or HTTP/3 for SSE, multiplex several videos per stream
Mode flapping at the CDN thresholdRepeated mass reconnects and inconsistent experienceSeparate upper and lower thresholds, minimum dwell time, jittered switch windows
Spam floods and abuseFeed unreadable, harmful content shownPer-user and per-video rate limits, slow mode, async classifiers with removal events, hold-for-review for high-risk streams

What Interviewers Expect#

Mid-level#

  • Gather the three functional requirements and the key non-functional ones: scale, low latency, availability over consistency.
  • Produce a working high-level design: a comment service, a database keyed by video, and a way to get new comments to viewers.
  • Recognise on your own that polling is too slow and too expensive, and move to a push model (SSE or WebSockets) with a reason.
  • Use cursor pagination for history and explain why offset pagination breaks in a fast-moving feed.
  • With some hints, arrive at pub/sub so that comments reach viewers on other servers, and scale it with guidance. The interviewer will probe basics ("what does your load balancer do here?") and may drive the later part of the discussion.

Senior#

  • Move quickly through the basic design to spend most of the time on scaling the broadcast.
  • Justify SSE over WebSockets from the read/write ratio, and know SSE's practical problems (proxy buffering, connection limits, idle timeouts, monitoring).
  • Separate the write service from the realtime tier, explain the coordination problem across servers, and design pub/sub partitioned by video with minimal hints.
  • See that partitioning without co-location does not help, and propose Layer 7 consistent-hash routing; compare Redis Pub/Sub and Kafka for this job.
  • Handle reconnects with Last-Event-ID, a shared recent-comments cache and bounded replay; mention jittered backoff.
  • Drive the scaling discussion proactively and state trade-offs clearly.

Staff+#

  • Treat the problem as a broadcasting system with a tiny write path, and use the popularity skew to explain why one design does not fit all streams.
  • Propose the three regimes: full-fidelity push for most videos, sampled push for big ones, and CDN snapshots for mega-streams, with a controller and hysteresis. Argue that the requirements themselves change at extreme scale.
  • Compare partitioned pub/sub and a dispatcher service in depth, including subscription churn, map freshness, hot-video sub-sharding with bounded-load hashing, and fan-out trees.
  • Quantify: connections per server and what limits them, internal message rates for naive versus co-located designs, egress, write hot partitions.
  • Raise the problems a team would hit in production: reconnect storms, draining connections for deploys, rebalancing after scale-out, slow consumers, the video timeline offset, moderation latency, multi-region fan-out.
  • Know specific technologies in practice (Redis sharded pub/sub, Envoy ring hash, DynamoDB partition limits, CDN request coalescing) and choose between them with experience-based reasoning. The interviewer should only need to focus the conversation, not steer it.
Deep Dive: The maths of live commentsShow

Fan-out is a product, so skew dominates. The delivery rate for one video is D = c × v, where c is comments per second and v is viewers. Both c and v grow with popularity: more viewers means more potential commenters, so c is roughly proportional to v (c ≈ α × v for some commenting rate α per viewer). Then D ≈ α × v², which is quadratic in viewers. A video with 10 times the viewers needs about 100 times the deliveries. With α = 1/3,000 per second (one comment per viewer every 50 minutes), a video with 10,000 viewers has c ≈ 3 per second and D ≈ 33,000 deliveries per second. One with 10 million viewers has c ≈ 3,300 per second and D ≈ 33 billion per second. This is the formal reason a mega-stream needs a different design: the quadratic term cannot be paid. Capping each viewer at r comments per second changes it to D = min(c, r) × v, which is linear in v again.

Internal traffic: naive versus co-located. Let S be the number of realtime servers and C the global comment rate. Naive broadcast delivers C × S internal messages per second: 50,000 × 1,000 = 50 million. With co-location, a comment on a video with v viewers goes to ⌈v / K⌉ servers, where K is connections per server. For the 99% of videos with v below K, that is one server. The internal rate is about C × E[⌈v/K⌉], weighted by comment share. If most comments come from small and medium streams, this is close to C, about 50,000 to 100,000 messages per second, a reduction of about 500 times. With hash-partitioned channels instead of per-video channels, add false sharing: a server subscribed to channel h receives comments for all videos in h. With N channels and M active videos, each channel carries about M / N videos. Choosing N comparable to the number of videos a server hosts times S keeps false sharing small; in practice N between 10,000 and 1,000,000 channels is typical, depending on what the broker handles well.

Reading speed and the sampling target. Adults read prose at roughly 200 to 300 words per minute, or about 4 to 5 words per second. Short comments are skimmed faster, but even at 20 words per second, 4-word comments arrive at a readable pace only up to about 5 per second. That is why a target display rate of 5 to 10 comments per second is a sensible cap. At 5,000 comments per second the sampling probability is 10 / 5,000 = 0.2%. The chance that a given ordinary comment is shown to a given viewer is therefore 0.2%, and to anyone is near 100% only if different viewers get different samples. That is a design choice: one shared sample (cheaper, cacheable, needed for CDN snapshots) versus per-viewer samples (more voices heard, more compute).

Queues and Little's law. Little's law says the average number of items in a system L equals arrival rate λ times average time in system W. For a realtime server writing 200,000 events per second with an average per-event latency of 2 ms inside the server, about 400 events are in flight at once, which is trivial. For a slow consumer whose link drains 2 events per second while 10 arrive per second, the queue grows by 8 per second without bound. A bound of 100 events is reached in about 12 seconds; then we drop the oldest. The law also sizes the reorder buffer: holding events for 150 ms at 10 events per second keeps about 1.5 events buffered per viewer.

Connection memory. If each connection costs 4 KB of kernel buffer (tuned), 16 KB of TLS state and 2 KB of application state, that is about 22 KB, so 100,000 connections need about 2.2 GB, and 1 million connections need 22 GB. Untuned default buffers can be 10 times larger, which is why the same hardware can hold 50,000 or 1 million connections depending on configuration.

Snapshot egress. CDN mode costs viewers × snapshot size × polls per second. With 10 million viewers, a 30 KB snapshot and 1 poll per second, egress is 300 GB/s. Two improvements: compress (JSON comments compress 3 to 5 times, so about 8 KB) and serve deltas (an immutable object per second containing only that second's sampled comments, about 10 comments or 1.5 KB compressed). With deltas, egress falls to about 15 GB/s, roughly 20 times less, and the edge cache hit rate stays near 100% because every viewer in a second fetches the same object. Origin load is roughly the number of edge locations times polls per second: a few hundred to a few thousand requests per second, independent of viewer count.

Tail latency and fan-out. If a comment's delivery to a viewer depends on one of 20 servers, and each server has a 1% chance of a 100 ms hiccup (a garbage collection pause, say) in any given second, then the probability that at least one of the 20 is hiccuping is 1 − 0.99^20 ≈ 18%. Some viewers of a big stream will always be seeing the slow tail. This is the effect Jeffrey Dean and Luiz André Barroso described in "The Tail at Scale" (Communications of the ACM, 2013). The fixes are the same: keep per-server pauses short (low-pause garbage collectors or non-GC runtimes), and measure delivery lag at p99 and p99.9, not just the mean.

Availability arithmetic. If the delivery path for a comment is client → load balancer → realtime server → pub/sub → comment service → database, each at 99.95%, the chained availability for a live delivery is about 99.95%^6 ≈ 99.7%. That sounds poor until you notice that the database is not needed for live delivery if we publish in parallel, and the client recovers from realtime-server and pub/sub failures by reconnecting and replaying. Recovery paths matter more than component availability.

Deep Dive: How real live-comment systems are builtShow

Public detail varies by company, so this section sticks to what has been described publicly and keeps claims general where specifics are not documented.

Facebook Live. Facebook launched Live for public figures in 2015 and to everyone in 2016. Its engineers have written publicly about the video side: live streams are cut into short segments and delivered through Facebook's edge caches, and when a popular broadcast starts, many viewers request the same segment at once. Edge request coalescing makes one request to the origin and serves everyone from the result, the same principle this design uses for comment snapshots. Popular Live videos can draw enormous audiences: a 2016 video of a woman laughing in a Chewbacca mask is often cited as one of the most-viewed Facebook Live videos, with well over 100 million views. The details of Facebook's comment fan-out are less documented, so treat any specific internal system name you hear with care.

LinkedIn Live. A LinkedIn engineer's QCon talk on real-time likes and comments for live videos described, in outline, frontend servers holding persistent HTTP connections using Server-Sent Events, built on the Akka actor framework, with an actor per connection. Frontends keep an in-memory subscription table of which connections watch which live video, and a dispatcher tier records which frontend nodes care about each video and sends each event only to those nodes. To support multiple data centres, events are sent to dispatchers in every data centre, each of which fans out locally. This is essentially the dispatcher design from deep dive 4, plus cross-region fan-out from deep dive 12. LinkedIn also wrote about holding hundreds of thousands of persistent connections per machine for instant messaging using the Play framework and Akka, with Server-Sent Events.

Twitch chat. Twitch chat is exposed through an IRC-compatible interface: third-party bots connect with ordinary IRC clients, and the web client speaks IRC over WebSockets. Channels map naturally onto IRC rooms. Twitch provides moderation controls including slow mode, follower-only and subscriber-only modes, and emote-only mode, which double as load controls for huge streams. Twitch's chat replay shows chat in sync with past broadcasts.

YouTube Live. YouTube offers two views of live chat: "Top chat", which filters out potential spam and some low-quality messages, and "Live chat", which shows all messages. That is the representative-subset idea exposed as a product toggle. YouTube also offers slow mode and, after a stream ends, live chat replay alongside the recording. Creators can pin messages, and paid "Super Chat" messages are highlighted and stay visible longer, which is an example of priority comments bypassing sampling.

Discord. Discord is chat rather than live comments, but its large community servers resemble live streams: one message, hundreds of thousands of online recipients. Its engineers wrote in 2017 about scaling Elixir to 5 million concurrent users, and introduced "Manifold", a library that batches message sends by destination node so that fanning out to many processes across many nodes costs one inter-node message per node rather than one per recipient. The same batching applies inside our realtime tier: serialise an event once per video per server, not once per connection.

Danmaku sites (Niconico, Bilibili). Japanese site Niconico popularised comments that fly across the video itself, tied to video time, and Chinese site Bilibili adopted the style. Because comments are anchored to playback time, they are stored with a video timestamp and replayed in sync for later viewers. Busy videos show a density limit: the player selects a subset when there are too many to display, which is sampling again, applied on the client.

Lessons common to all of them. Separate the write path from fan-out. Keep the hot path in memory and the durable record off to the side. Expose product controls (slow mode, filters) that also shed load. Accept that busy streams show a subset. Anchor comments to video time if you want replays to make sense.

Deep Dive: Inside a realtime messaging serverShow

The realtime server is where most of the fleet's CPU and memory go, so its internals deserve a closer look.

Core data structures.

  • videos: map<videoId, VideoGroup>, where a VideoGroup holds the set of local connections watching that video, the video's current delivery mode, its sampling state (for sampled mode) and a small ring buffer of the last few dozen events, useful for instant local replay when a viewer reconnects to the same server.
  • connections: map<connId, Connection>, where a Connection holds the socket, the video id (or ids, if multiplexed), the last event id written, a bounded outbound queue and per-connection counters.
  • subscriptions: map<channelId, refcount>: how many local videos need each pub/sub channel. Subscribe when the count goes from 0 to 1; unsubscribe after a grace period when it returns to 0.

Serialise once, write many. When a comment arrives from pub/sub, the server formats the SSE frame (id:, event:, data: lines) once, as an immutable byte buffer, and enqueues a reference to it on every local connection in the VideoGroup. With 100,000 viewers of one video on the server, that is one JSON encoding and 100,000 pointer copies, not 100,000 encodings. With TLS, each connection still encrypts its own copy, which is the dominant per-delivery cost; kernel TLS (kTLS) on Linux can move the encryption into the kernel and reduce copies.

Batch writes. If several comments arrive within a millisecond or two, write them to each socket in one system call (one writev with several frames). This trades a millisecond of latency for a large reduction in syscalls and TLS records. Under heavy load, a server can widen the batching window automatically (for example from 1 ms to 20 ms), which keeps throughput up without visible latency.

Per-viewer personalisation without per-viewer work. Most frames are identical for all viewers of a video. Personal frames (a friend's comment that was not in the global sample) are rare, so they are generated only for the connections that need them, using a per-server index from author to local viewers who follow that author. The index is built when connections join, from a social graph lookup, and can be approximate.

Threading model. A small number of event-loop threads (often one per core), each owning a subset of connections, avoids locks on the hot path. Pub/sub input is handled by one thread that hands each event to the loop threads that own the video's connections. In actor systems (Akka, Erlang), each connection or each video group is an actor; in Go, a goroutine per connection with a channel as its outbound queue is idiomatic, with care to keep per-goroutine memory small.

Back-pressure inside the server. If the event loops fall behind (rising event-loop lag), the server first widens batching, then increases sampling for sampled-mode videos, then stops accepting new connections, and only then starts dropping events for the slowest connections. This ordering keeps the experience degrading gracefully.

Memory hygiene. Hundreds of thousands of small objects per server can make garbage-collected runtimes pause. Pool buffers, prefer arrays over many small maps, avoid per-connection timers (use a single hashed timing wheel for heartbeats and timeouts), and keep the per-connection object small. A hashed timing wheel (Varghese and Lauck, "Hashed and Hierarchical Timing Wheels", SOSP 1987) turns millions of timers into constant-time operations.

Heartbeats as a scheduling problem. With 100,000 connections and a heartbeat every 20 seconds, the server sends 5,000 heartbeats per second. Spread them evenly with the timing wheel rather than sending all at once on a global tick. Skip the heartbeat for any connection that received a real event recently.

Statelessness where possible. The server's only durable responsibility is none: all state can be rebuilt from client reconnects and the shared cache. That makes the tier easy to scale and to replace, and is why it should never hold anything that is not also stored elsewhere.

Deep Dive: Variants interviewers ask aboutShow

Live reactions (likes, hearts, emoji bursts). Reactions are far more frequent than comments (often 10 to 100 times more), but each one carries almost no information. Never fan out individual reactions. Aggregate them: each write-tier instance counts reactions per video per type in memory and flushes counts every 100 to 500 ms to an aggregator, which sums them and broadcasts one small event per video per interval ("hearts +4,210 in the last 500 ms"). Clients animate a matching burst. For the persistent total, increment a sharded counter. This turns millions of writes per second into a few events per second per video, and is the same idea as the Pattern: Scaling Writes counter-sharding technique.

Concurrent viewer counts. Counting viewers exactly across 1,000 servers is unnecessary. Each server reports its local count per video every few seconds; an aggregator sums them. For unique viewers over a time window (rather than concurrent), use HyperLogLog sketches merged across servers: Flajolet, Fusy, Gandouet and Meunier, "HyperLogLog: the analysis of a near-optimal cardinality estimation algorithm" (2007), gives about 2% error in about 1.5 KB.

Replies and threads. If replies come into scope, a reply is a comment with a parentId. The live stream still carries all top-level comments, but replies are fanned out only to viewers who have the thread open, plus a lightweight "N replies" counter update to everyone. Storage adds an index on (liveVideoId, parentId, commentId).

Live Q&A and polls. A Q&A session lets viewers submit questions and upvote them. The live stream carries the top questions list, recomputed every second from vote counts, rather than every vote. Polls are reactions with a fixed set of options plus a final tally; see the Top-K case study for ranking under high write rates.

Live sports scores and tickers. Updates are rare and written by one source, but read by everyone. This is pure broadcast: CDN snapshots or SSE with tiny payloads, and the latest state matters more than history. Each update replaces the previous one, so catch-up means "send the latest state", not replay.

Live auctions and bidding. Order and correctness suddenly matter a lot: bids must be totally ordered and the current highest bid must be consistent. Use a single serialising owner per auction (a partition leader or a database row with optimistic concurrency) for writes, and broadcast the resulting state over SSE. Sampling is never acceptable. See Pattern: Dealing with Contention.

Live shopping. Comments plus product cards and inventory updates. Inventory counts are like scores (latest state wins), and "buy" actions go through the normal checkout path, not the comment path.

Gaming and esports chat. Very high comment rates with strong community norms. Emote-only and slow modes, heavy moderation automation, and per-viewer filters (for example hiding messages from new accounts) are common. Delivery is the same as here.

Comments overlaid on the video (danmaku). Comments are positioned at video times and rendered across the frame. Storage is keyed by (videoId, videoTimeBucket) so a player can fetch "comments for minutes 12 to 13" as it plays, which makes replays cacheable on a CDN in time-sliced chunks.

Private streams and small rooms. For a stream with 20 viewers, all of this machinery reduces to one server, one channel and full-fidelity delivery, which is exactly what partitioned pub/sub with co-location gives by default. The same design covers the long tail cheaply.

Deep Dive: Walking through the failure casesShow

Walking through failures one at a time is the best way to check that the design is really available-first.

  1. A comment service instance crashes mid-request. The client's POST times out. It retries with the same idempotency key to another instance. If the first instance had already stored the comment, the second finds the key and returns the stored comment; if not, it stores it now. Either way, exactly one comment exists.
  2. The database write succeeds, the publish fails. Viewers do not see the comment live. It is in history and in the recent-comments cache (if that append succeeded), so viewers who reconnect or scroll see it. The author sees it locally. A background "publish repair" can re-publish comments written but not acknowledged by pub/sub within a second, but for live comments most teams accept the rare miss.
  3. The database is throttling a hot partition. Posts would fail. Instead, accept the comment into a durable log (Kafka), publish to live fan-out immediately, and let a consumer write to the database when capacity allows. History lags by seconds; live viewers notice nothing.
  4. A pub/sub node fails. Channels on that node stop delivering until the cluster fails over (seconds). Realtime servers notice the subscription connection drop, resubscribe on the new owner, and fetch the gap from the recent-comments cache for each affected video, then push the missed comments to their viewers. Clients see a short pause and then a burst.
  5. A realtime server crashes. Its 100,000 viewers reconnect with jittered backoff, are routed to the next servers on the hash ring, send Last-Event-ID and get replay from the shared cache. The neighbours have headroom for this.
  6. The recent-comments cache is unavailable. Replay and the first history page fall back to the database (slower, and rate-limited to protect it). If that is also overloaded, reconnecting clients get a truncated marker and simply jump to live. Live delivery continues, because it does not depend on the cache.
  7. A Layer 7 proxy fails. Its connections drop; Layer 4 balancing steers reconnects to the remaining proxies. Proxies are stateless, so recovery is only reconnect cost.
  8. The stream-mode controller fails. Videos stay in their current mode. Thresholds are a safety and cost mechanism, not a correctness one, so a controller outage is tolerable for minutes. Realtime servers enforce a local fallback: if a video's local fan-out exceeds a hard limit, they sample locally regardless of the controller.
  9. The CDN origin for a snapshot is slow. Edges keep serving the last snapshot (stale-while-revalidate) and clients see comments pause. If the origin stays slow, clients receive a "switch back to push" signal only if there is capacity; otherwise they keep polling with a slower interval.
  10. A region fails. Viewers reconnect to the next region through DNS or anycast. The next region already has the replicated comment stream, so replay works. Mega-streams may be sampled more aggressively during the failover to fit the extra load.
  11. A celebrity starts a surprise stream. Within a minute, a million viewers join. The video starts in push mode on one server; bounded-load hashing spills viewers onto neighbouring servers as each fills, each subscribing to the channel. The controller sees the viewer count cross thresholds and moves the video to sampled mode, then CDN mode. The first history page is served from a precomputed blob. The worst moment is the first 30 seconds, which is why thresholds should react quickly on the way up and slowly on the way down.
  12. A spam bot network floods a stream. Per-user rate limits stop each account; per-video limits cap fan-out; the spam classifier flags patterns (identical text from new accounts) within seconds and hides them retroactively with removal events. The broadcaster can enable slow mode or follower-only mode, which cuts the flood at the source.

The common thread: the durable record is never in the live path's way, and every live-path failure is recovered by reconnect plus replay.

Deep Dive: Evolving the design, testing it and running itShow

Stage 1: a startup. One comment service and PostgreSQL with an index on (video_id, id). Viewers poll every few seconds, or better, a single server holds SSE connections and pushes comments it receives in-process. Handles thousands of concurrent viewers. Ship it.

Stage 2: a growing product. Split the comment service from the realtime servers. Add Redis Pub/Sub with one channel per video (fine at this scale) and the recent-comments cache. Round-robin load balancing is fine while the fleet is a handful of servers. Move comment storage to DynamoDB or Cassandra when write volume or operational burden demands it.

Stage 3: a large platform. Hundreds of realtime servers. Naive broadcast becomes too expensive, so partition channels by hash and add Layer 7 consistent-hash routing for co-location, or introduce a dispatcher. Add Last-Event-ID replay, bounded replay and jittered reconnects. Add sampling for big streams.

Stage 4: global scale. Regional realtime tiers, a replicated comment log across regions, multi-region storage, CDN snapshots for mega-streams with an automatic controller, write sharding for hot videos, and a mature trust-and-safety pipeline.

Each stage should be triggered by a measured limit (CPU spent discarding messages, p99 delivery lag, database throttling), not by anticipation. Interviewers like to hear that you would start simple and know exactly which signal would make you take the next step.

Load testing. You cannot test 100 million connections with a few laptops. Build a load generator that opens many SSE connections per process (event-loop clients can hold hundreds of thousands per machine, using multiple source IPs to avoid client-side port exhaustion), subscribes them to a realistic distribution of videos (a Zipf-like popularity curve), and measures delivery lag by embedding the send timestamp in each test comment. Test the scenarios that matter: steady state, a single mega-stream ramp, a realtime-server kill, a pub/sub failover, a rolling deploy and a regional failover. See Capacity Planning and Load Testing.

Game days for big events. For scheduled events (a final, an election night, a product launch), pre-scale the realtime tier and pub/sub, pre-mark the video as hot (start in sampled mode, with write sharding enabled), warm CDN configuration, freeze risky deploys and staff an on-call room with dashboards for delivery lag, connections and mode transitions.

Service level objectives. Examples: 99% of comments delivered to connected viewers of non-mega streams within 500 ms (p99 delivery lag), 99.9% of posts acknowledged within 1 second, and 99.95% availability of the posting API. For mega-streams, the SLO is snapshot freshness (p99 under 3 seconds), not per-comment delivery.

Cost levers. The biggest costs are realtime server fleet size (driven by connections and messages), egress (driven by deliveries times bytes) and CDN egress for mega-streams. Levers: compact event encoding (short field names, or a binary format for native clients), compression on the stream (with care for buffering), batching, sampling thresholds, and connection limits per client.

Security notes. Authenticate both POSTs and stream connections (a private or subscriber-only stream must not leak comments), validate the video id against the live video service, sanitise text before rendering (comments are a classic cross-site scripting vector), and sign CDN snapshot URLs for non-public streams. See Security Fundamentals for System Design.

Key Takeaways#

  • Live comments is a broadcast problem with a tiny write path: a few thousand writers, millions of readers per stream. Design the read path first. The broader approach is in Pattern: Pushing Realtime Updates.
  • Polling fails on both latency and cost. Use SSE for one-way delivery and plain HTTP POST for writes, because reads vastly outnumber writes. WebSockets work too, but suit balanced two-way traffic such as chat. See Polling, Long Polling, SSE, WebSockets and Webhooks.
  • Separate the write service from the realtime tier, and solve the coordination problem with pub/sub partitioned by video id plus viewer co-location through Layer 7 Consistent Hashing, or with a dispatcher that routes each comment to exactly the right servers. See Pub/Sub and Event Streaming.
  • Redis Pub/Sub (sharded) fits the last-hop fan-out because subscriptions change constantly and comments are already durable elsewhere. Kafka belongs behind the write path for moderation, analytics and snapshots. See Redis in Practice and Apache Kafka in Practice.
  • Fan-out cost grows roughly with the square of viewers, so mega-streams need different rules: adaptive, weighted sampling to a readable rate, then CDN snapshots with client-side smoothing, read-your-own-writes on the client and hysteresis between modes. See Content Delivery Networks (CDN).
  • Store comments in a partitioned store keyed by (liveVideoId, commentId) with time-ordered ids, use cursor pagination (never offsets), cache the first page, and write-shard hot videos. See Amazon DynamoDB in Practice and Unique ID Generation.
  • Ordering is approximate by design: Snowflake-style ids, a client reorder buffer and dedupe by id, a per-video sequence only where gap detection pays off, and video-time tags so comments match what the viewer is watching. See Time, Clocks and Ordering.
  • Disconnections are normal. Use SSE's Last-Event-ID, a shared recent-comments cache, bounded replay, jittered backoff and mobile-aware lifecycle handling. Every failure in the live path should recover through reconnect plus replay. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.
  • Operate it like the stateful tier it is: drain connections for deploys, rebalance after scale-out, bound per-connection queues, and measure end-to-end delivery lag at p99. See Observability: Logs, Metrics and Traces.