Ranking Currently-Live Channels Under a 100 ms Budget
Machine LearningModel answerLast updated
Design an end-to-end ML system that ranks live channels for viewers, covering labels, features, models, bias correction, evaluation, and low-latency serving as streams start and end.
You are asked to design a recommender that fills a "Live now" row on a video platform's home page. Each request returns about 20 channels that are broadcasting at that moment. The set of eligible items changes every minute as broadcasts begin and end, and a channel that has gone offline has no value.
Walk through the following parts in your answer.
- Objective and labels. Choose a primary objective, for example the probability that a viewer who sees a channel stays for at least 10 minutes. Explain how you would build training labels from a
view_eventslog, including outcomes that arrive late and cases where the broadcast ends before the 10-minute mark is possible. - Features. Describe user, creator, stream, and context features. Cover cold start for new creators and new users, and explain how short-term session behavior and long-term embeddings are combined.
- Model and loss. Pick a model family (for instance a two-tower retrieval stage followed by a re-ranker with calibrated probabilities). State the loss, the negative sampling plan (in-batch plus hard negatives), and how you handle strong class imbalance.
- Feedback loops and bias. Explain how you would reduce position bias and popularity bias, using counterfactual estimators (IPS or doubly robust) and/or randomized exploration. Describe the exploration policy (Thompson Sampling, UCB, etc.) and the safety limits around it.
- Evaluation. Name offline metrics (AUC, PR-AUC, calibration, NDCG@k) and online metrics (watch time per viewer, session length, bounce rate). Explain how replay evaluation and interleaving help offline results predict online results.
- Serving. Give an end-to-end latency budget under 100 ms at p95 covering retrieval, feature fetch, and ranking. Explain how you keep features fresh when a streamer goes live and how embeddings are updated in near-real time.
State your scale assumptions up front and call out the main trade-offs.
Hints
Hint 1
Factor the objective into P(click) times P(watch 10+ min | click), and decide explicitly whether a broadcast that ends early counts as a negative or as a censored example.
Hint 2
Separate what changes slowly (long-term user and creator embeddings, refreshed daily) from what must be live (viewer count velocity, category, session embedding), and place each in a store matching its freshness need.
Hint 3
Log the position and the probability with which each item was shown. Without logged propensities you cannot do IPS or doubly robust estimation, and exploration will not be evaluable.
Hint 4
Write the latency budget as a table of stages that sum to well under 100 ms, with the candidate set kept small enough (hundreds, not thousands) for the ranker to fit its slice.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
Surface: home "Live now" row, 20 results per request. Scale: roughly 3M concurrent viewers, 100k live channels, 50k peak QPS. Target: under 100 ms p95. The catalog churns every minute, so freshness is a first-class requirement.
1. Objective and labels
Objective. Maximize qualified watches per impression:
P(qualified | impression) = P(click | impression) x P(watch >= 10 min | click)
Use two heads in one multi-task model. Clicks are dense and give a strong training signal. The 10-minute head stops thumbnail bait from winning. Total watch time is a secondary monitored metric, not the target, because it is heavy-tailed and dominated by a few very long sessions.
Labels. Join impressions (request_id, position, stream_id) to play-start and heartbeat events.
- click = 1 if playback starts within about 30 s of the impression.
- watch10 = 1 if accumulated heartbeats reach 10 minutes.
Delayed outcomes. The watch10 label cannot be final for at least 10 minutes. For batch training, wait a join window of about 15 minutes before emitting a label. For streaming training, emit a provisional negative and later a correction, and use a delayed-feedback loss or fake-negative weighting so early negatives do not drag predictions down.
Censoring. If the broadcast ends at minute 6, the viewer could not have reached 10 minutes. That is right-censored, not negative. Options, in increasing quality: drop censored rows (simple, but biased against short-lived streams); label positive if the viewer stayed until the stream ended after a minimum such as 3 minutes; or fit a survival/hazard model of watch duration where stream end is a censoring event. Also flag involuntary traffic such as raids and hosts, which is not organic choice, and exclude or down-weight it.
2. Features
- User: long-term embedding (followed channels, categories watched), language, region, device, account age.
- Creator: creator embedding, historical click and 10-minute rates, follower count, usual schedule, content rating.
- Stream (real time): current category, title text embedding, viewer count and its 5-minute velocity, uptime, chat rate, language.
- Context: time of day, weekday, surface, network quality. Position is used only for bias handling (section 4).
- Cross: user-category affinity, follows-creator flag, watched-creator-in-last-7-days.
Short vs long term. The long-term embedding is retrained daily on about 90 days of history. A session embedding is computed online by a small GRU or attention pooling over the last N watched or skipped streams with recency decay, stored in a low-latency key-value store and updated per event. The user tower consumes both, so it can learn that tonight's session differs from the usual pattern.
Cold start. New creators: content-based embedding from category, title, language and tags projected into the ID-embedding space, category-level priors for rates, and guaranteed exploration slots. New users: onboarding picks, geo, language, device; fall back to locale and category popularity; the session embedding takes over after one or two watches.
3. Model and loss
Retrieval (two-tower). User/context tower and stream tower each output a 128-d vector; score by dot product. Train with sampled softmax using in-batch negatives plus log-Q correction, since in-batch sampling over-represents popular items. Add hard negatives: impressed-but-skipped streams and high-viewer streams from the same category. Query an ANN index containing only live streams for about 500 candidates, and merge with rule-based sources (followed channels that are live, trending in the user's categories, an exploration pool).
Ranker. A multi-task network (DCN-v2 or MMoE) with click and watch10 heads trained with binary cross-entropy. Final score = p_click x p_watch10 plus small business terms. Calibrate with isotonic or Platt scaling per surface on recent holdout, because the heads are multiplied and exploration bonuses are added to probabilities.
Imbalance. Click rate is about 2-5% and unconditional watch10 under 1%. Downsample negatives (for example keep 10%) and correct with p = p' / (p' + (1 - p') / w), where w is the keep rate. Train the watch10 head only on clicked examples, where positives are about 30%. Use focal loss only if calibration survives.
4. Feedback loops and bias
Position bias. Log position on every impression. Train with position as a feature and fix it (e.g., slot 1) at serving, or use a shallow position tower whose logit is dropped at inference. Estimate examination propensities from a small randomized swap experiment (adjacent swaps on about 1% of traffic).
Popularity bias. Log-Q correction in retrieval, plus IPS weights 1/pi(a|x) clipped near 10 to control variance. Use doubly robust estimators (reward model plus IPS residual correction) for both reweighting and offline policy evaluation. This needs logged propensities, so the serving policy must be stochastic or log its scores.
Exploration. Reserve 1-2 of 20 slots. Run Thompson Sampling with a Beta posterior on each eligible stream's 10-minute rate, seeded from category priors and updated in near real time. UCB is a deterministic alternative that is easier to debug but gives less natural propensities.
Safety. Explore only among streams passing trust-and-safety, content-rating, language and age filters; never use slot 1; cap per-stream exposure per minute; auto-disable exploration on a surface if guardrail metrics degrade.
5. Evaluation
Offline: AUC and PR-AUC per head (PR-AUC matters given imbalance), calibration (reliability curves, ECE), NDCG@k on watch10 with position-debiased weights, and DR/IPS estimates of policy value. Slice by new vs. returning users and small vs. large creators.
Online: watch time per viewer, session length, bounce rate (leaving within 30-60 s), plus guardrails (creator diversity, new-creator exposure, latency).
Offline-to-online link. Replay evaluation on randomized-exploration logs gives an unbiased estimate; on purely deterministic logs it is biased, so keep the exploration slice. Use interleaving (team-draft) for fast, high-sensitivity comparison before full A/B tests. Track the correlation between offline gains and A/B outcomes across past launches to learn which metrics to trust.
6. Serving and freshness
Latency budget (p95, ms):
| Stage | Budget |
|---|---|
| Gateway, request parsing | 5 |
| User/session feature fetch | 10 |
| ANN retrieval + rule sources (parallel) | 20 |
| Stream feature fetch for ~500 candidates (batched) | 15 |
| Ranker inference (batched, GPU or optimized CPU) | 25 |
| Re-rank, exploration, filters | 8 |
| Response + slack | 10 |
| Total | about 93 |
Prefilter to a few hundred candidates before the ranker. Cache long-term embeddings and static creator features locally.
Freshness. A stream-start event goes through a streaming pipeline that registers the channel in the live index within seconds, using a content-based embedding for new creators. Stream-end events remove it immediately, and a serving-time liveness check guards against stale entries. Real-time counters (viewer velocity, chat rate) are windowed aggregates in a key-value store updated every few seconds. Stream embeddings are recomputed when category or title changes; the user tower is not re-run on a schedule, as the session embedding updates per event. Long-term towers are retrained daily with a lightweight incremental refresh in between.
Common mistakes
- Treating early-ended streams as negatives.
- Training on position-biased clicks with no correction and no logged propensities.
- Multiplying uncalibrated heads.
- Optimizing raw watch time, which rewards marathon viewers.
- Designing the index for a static catalog.
- Letting exploration bypass safety filters.