AI System DesignRecommendation and Ranking SystemsVideo Recommendations and Responsible Engagement
How to Design YouTube’s Responsible Video Recommendation System
Question 10 of 46 · Updated
On this page
- 1. Clarify the product, surface and objective
- 2. Functional and non-functional requirements
- 3. Estimate capacity and identify bottlenecks
- 4. End-to-end architecture
- 5. Video catalog and interaction data
- 6. Stage one: candidate generation
- Two-tower retrieval model
- 7. Session-aware recommendations
- 8. Stage two: deep ranking and multi-task learning
- 9. Watch-time prediction: use the right denominator
- 10. Multi-objective ranking and responsible engagement
- 11. Slate construction, creator diversity and safety
- 12. Exploration, exploitation and feedback loops
- 13. Tested Python example: bounded utility and constrained reranking
- 14. Real-time serving and freshness
- 15. Scalability and storage design
- 16. Cold start
- 17. Evaluation and controlled experiments
- 18. Reliability, privacy and production failure handling
- 19. Interview trade-offs and concise answer
- References and research transparency
I would use a two-stage recommendation pipeline: a high-recall candidate generator retrieves a manageable set of eligible videos, and a contextual multi-task ranker estimates viewer satisfaction, expected watch time and negative feedback. A separate policy and diversity layer constructs the final slate, respects explicit viewer controls and revalidates content eligibility. I would optimize useful, voluntary engagement and sustained satisfaction, not unlimited consumption.
Original interview question: How would you design a YouTube video recommendation system to maximize user engagement?
Historical YouTube research, including the 2016 candidate-generation and ranking paper by Covington and colleagues and the 2019 multitask ranking paper by Zhao and colleagues, offers relevant technical foundations. The architecture below is a proposed modern interview design informed by established methods, not an assertion about YouTube's current proprietary ranking weights, serving infrastructure, policy implementation or business metrics. All numerical examples and workload assumptions are synthetic.
1. Clarify the product, surface and objective#
A video platform supports multiple recommendation surfaces:
| Surface | Primary context | Typical user goal |
|---|---|---|
| Home feed | Current session, authorized history, explicit interests | Find something worthwhile to watch |
| Watch-next panel | Current video and recent session context | Continue or change a viewing task |
| Subscription discovery | Explicit channel subscriptions | Discover relevant recent uploads |
| Short-form feed | Rapid interactions and format preference | Find relevant short videos |
| Search | Explicit query | Retrieve videos that answer a stated need |
Scope the initial system to Home and watch-next recommendations. Search is a separate retrieval objective; short-form surfaces have different exposure and playback semantics and should be evaluated separately. Reuse compatible infrastructure without assuming a common metric or ranking model is optimal for every surface.
A recommendation is an ordered impression of a video, not a completed view. The system can control which eligible videos are presented and their order, but the user chooses whether and when to watch. Respect history settings, blocked creators, explicit negative feedback, age-appropriate settings and stopping controls. Do not use signals to infer personal vulnerability or exploit compulsive viewing.
Distinguish immediate engagement (intentional starts, meaningful viewing, relevant saves), viewer satisfaction (explicit feedback and appropriately sampled surveys), and long-term value (whether recommendations remain useful over time). These outcomes can disagree. A long video that disappoints a viewer may generate more minutes than a short video that answers their question perfectly.
This differs from Discover Weekly: the latter creates a periodic music playlist with a fixed discovery horizon, while video recommendation updates within a session and must account for duration, watch context, and freshly uploaded or removed content. The restaurant recommender instead has geographic, opening-hours and physical travel constraints. Video availability is primarily policy, access and rights-related; it does not require a radius around the viewer.
2. Functional and non-functional requirements#
| Requirement | Proposed design |
|---|---|
| Candidate retrieval | Retrieve hundreds of relevant videos from a large eligible catalog |
| Session adaptation | Update context after meaningful interactions without overriding explicit controls |
| Ranking | Predict multiple viewer-centered outcomes on consistent label definitions |
| Eligibility | Enforce access, rights, visibility, safety and audience constraints independently of ranking |
| Diversity | Limit excessive repetition and preserve useful creator/topic discovery |
| Freshness | Index new eligible uploads and propagate restrictions or deletion promptly |
| Latency | Illustrative p95 service target of 200 ms, measured end to end |
| Degradation | Serve validated nonpersonalized candidates or a short/empty slate when required |
| Auditability | Log model, retrieval, policy, experiment and impression versions |
| Privacy | Purpose-limited history, opt-outs, deletion propagation and restricted access |
The numeric latency target is a design assumption, not a claim about YouTube. Establish separate budgets for Home and watch-next, and measure candidate retrieval recall, ranking quality, and factual eligibility as independent system contracts.
3. Estimate capacity and identify bottlenecks#
Assume a fictional platform has 100 million active daily viewers, each generating ten recommendation requests per day, and 100 million currently indexed videos.
- One billion requests per day averages about 11,574 requests per second. An illustrative fivefold peak is approximately 57,870 requests per second.
- At 500 candidates entering ranking per request, the average candidate-scoring load is approximately 5.79 million scores per second. This is a logical scoring count, not a claim that each score needs a separate RPC.
- A 128-dimensional float32 video vector consumes 512 bytes. One hundred million such vectors consume 51.2 GB of raw embedding payload, before index structures, IDs, metadata, replicas and training snapshots.
- At 1 KB of compact request-level metadata, request logs alone amount to roughly 1 TB per day; actual impression, playback and feedback logs add substantial volume.
These workload sizes justify approximate retrieval, vectorized scoring, regional replication and carefully scoped logging. They do not determine the number of GPUs or servers without benchmarking feature retrieval, model throughput, batch size, tail latency and failure headroom.
Avoid a design that evaluates a large cross-encoder against every video in the catalog. Retrieve with cheap vector or index operations, then spend richer compute only on shortlisted candidates. Separate video media delivery from recommendation serving: the CDN and transcoding pipeline do not need to execute recommendation inference to deliver a selected video.
4. End-to-end architecture#
Two learned stages are retrieval and ranking. The final reranker is an additional policy/slate stage, not a replacement for either. Preliminary eligibility reduces wasted computation; authoritative final checks prevent the score from overriding current rights or safety restrictions.
The ingestion and training paths operate asynchronously. Online models consume version-compatible snapshots. The recommendation API has no authority to bypass a restriction or directly modify content availability.
5. Video catalog and interaction data#
A canonical video record includes video ID, creator/channel ID, upload and publication timestamps, duration, format, language and authorized content metadata. It also references visibility state, regional rights, audience eligibility, review status, restriction versions and deletion tombstones.
Candidate generation can use title, description, transcript, topic representations and audiovisual embeddings when those inputs are permitted and validated. Keep content quality and policy judgments separate from generic semantic similarity.
Log the events needed to distinguish exposure from response:
| Event | Key fields |
|---|---|
| Recommendation request | Request ID, surface, context version, experiment assignment |
| Served impression | Impression ID, video ID, position, candidate source, policy/model version |
| Playback start | Impression reference, intentional or automatic playback context |
| Watch progress | Deduplicated playback intervals, active viewing semantics |
| Viewer feedback | Like, dislike, not-interested, creator block, survey response where available |
| Content change | Video ID, state version, rights or eligibility update |
| Viewer control update | Authorized preference or history-setting version |
A video ID included in an API response may not actually be visible to the user. Instrument visibility and presentation consistently. Avoid labeling all returned-but-unseen cards as rejections. A click or autoplay start is not equivalent to satisfaction.
Join delayed events through stable impression and playback IDs; deduplicate retries, handle out-of-order events and specify when labels mature. For playback duration, distinguish pauses, background playback, buffering, seeks and replays according to the chosen measurement contract. Avoid counting duplicated client progress events as additional watch time.
Point-in-time features must reflect information available at the recommendation timestamp. Future likes, later watch behavior, moderation outcomes or updated creator statistics cannot enter an earlier training vector. Use chronological train/validation/calibration/test partitions and keep related sessions together where appropriate. Respect deletion and history settings in both training and serving.
6. Stage one: candidate generation#
Retrieve a diverse high-recall pool from multiple sources rather than depend on a single global popularity ranking.
| Source | Purpose | Limitation |
|---|---|---|
| Explicit subscriptions | Recent relevant uploads from selected channels | Not sufficient for new-interest discovery |
| Collaborative retrieval | Related videos based on authorized interaction patterns | Exposure and popularity bias |
| Content-based retrieval | Semantic matches from title, transcript or media embeddings | Metadata quality and representation errors |
| Session-conditioned retrieval | Videos relevant to recent viewing context or current video | Can overreact to accidental interactions |
| Fresh eligible content | Cold-start coverage for newly published videos | Limited engagement labels |
| Localized or topical baseline | Nonpersonalized relevance by authorized language/region | Less individualized |
Deduplicate by canonical video ID and record source indicators. Adjust source allocation according to surface and context. A watch-next request should prioritize relevance to the current video or task, while a Home feed may combine longer-term interests with recent intent. Avoid repeated near-identical candidates overwhelming the pool.
Two-tower retrieval model#
A query tower encodes authorized viewer/session context into q; an item tower encodes each video into v. With normalized embeddings, a dot product equals cosine similarity. Train on appropriate observed interactions with sampled negatives and a documented sampling policy.
similarity(query, video) = dot(q, v)Positive pairs might correspond to meaningful, authorized viewing or explicitly positive feedback. Exposed negatives, sampled negatives and unobserved items have different semantics. Sampled items are useful for retrieval training but are not proof of dislike. Consider popularity-aware sampling and weighting where justified, and validate retrieval on a representative evaluation set.
Precompute video embeddings offline and incrementally embed new eligible uploads. Serve query embeddings online. Use an approximate nearest neighbor index such as an HNSW or IVF-style design, chosen according to measured memory, update rate and recall requirements. Compare approximate search against exact search on tractable shards; tune the candidate budget to achieve adequate recall at a latency cost the service can afford.
Maintain compatible query/item encoders and index versions. If the embedding space changes, rebuild or migrate indexes under a versioned rollout. A new encoder queried against old incompatible vectors may silently degrade relevance.
Enforce access and audience constraints in retrieval where possible, and always recheck final eligibility. Overfetching then filtering may be necessary for some indexes, but retrieving a small global top-K and applying restrictive filters afterward can yield poor eligible recall. Use compatible partitions or filtered-search support where appropriate.
7. Session-aware recommendations#
Represent short-term intent separately from longer-term preferences. A viewer who usually watches cooking videos may be troubleshooting a laptop today. A model driven only by lifetime history may miss that task.
A simple baseline summarizes recent eligible interactions using recency weights, the currently watched video and explicit surface intent. A sequence model such as a GRU or self-attention encoder can capture ordered context, topic transitions and recency. Compare it with a simpler pooling baseline before adding operational complexity.
Keep the session state small and purpose-limited: recent permitted events, current context, explicit preferences and freshness metadata. A skip or accidental click should not permanently rewrite a viewer's interests. Give explicit negative feedback and user controls precedence over inferred affinity.
Update session state after validated events. Use monotonic versions or event-time ordering to reject stale updates, and expire short-term state according to the agreed privacy and product contract. Handle multiple devices, anonymous sessions and disabled history without reconstructing hidden user identities. If history is unavailable or opted out, use current request context and approved nonpersonalized sources.
Recompute the next slate on meaningful events and user requests rather than treating every playback heartbeat as a reason to rank the whole catalog. Respect pagination and avoid unstable result changes that make the interface confusing.
8. Stage two: deep ranking and multi-task learning#
The ranker scores hundreds of retrieved candidates with richer features:
- Current surface and video context, authorized recent interaction sequence, language and declared preferences.
- Candidate duration, topic representation, freshness, creator information and relevant content attributes.
- Candidate-source indicators, retrieval similarity, recent exposure and negative feedback.
- Contextual match features and data-quality/missingness indicators.
A gradient-boosted or logistic baseline is useful for measuring incremental benefit. A deeper model can combine categorical embeddings, dense features and session representations in shared layers. Task-specific heads estimate different outcomes. A multi-gate mixture-of-experts architecture allows tasks to share useful representations while maintaining task-specific weighting of expert networks; the additional complexity must earn its serving and maintenance cost.
Use binary cross-entropy for binary outcomes and a suitable robust regression or distributional loss for conditional watch time. Survey satisfaction labels may be sparse and selectively observed; use task masks rather than treating missing survey responses as negative ratings. Weight or sample examples with documented assumptions and evaluate representativeness. Multi-task loss weights affect training dynamics and are not the same as the business weights used in online ranking.
For example, a joint training objective can be written as:
L = a * start_loss
+ b * conditional_watch_loss
+ c * observed_satisfaction_loss
+ d * negative_feedback_lossHere each task is evaluated only on its valid label population with a documented normalization strategy. The watch-time head is trained on the relevant playback population; the satisfaction head must account for survey selection, response and missingness. Hyperparameters a, b, c and d are chosen on validation data. Monitor task conflicts, gradient domination and per-task calibration. A single deep score without interpretable task outputs makes it harder to diagnose why rankings changed.
9. Watch-time prediction: use the right denominator#
Distinguish conditional watch time from watch time per impression. Define S as an intentional playback start after an eligible impression and W as measured watch duration, with W = 0 if no start occurs under the defined contract.
expected watch seconds per impression
= P(S = 1 | context, video)
* E[W | S = 1, context, video]This follows from conditioning on the start event. Do not multiply by start probability again if the duration head already predicts unconditional watch time per impression. Use consistent exposure windows and ensure the label convention includes or excludes autoplay as intended.
For a synthetic candidate A with start probability 0.5 and conditional watch time 200 seconds, expected watch time is 100 seconds. Candidate C with start probability 0.8 and conditional duration 600 seconds has 480 expected seconds. A system optimizing minutes alone would prefer C on this measure, even when A is more useful and likely to satisfy the viewer.
Duration introduces bias: long videos can generate more minutes without greater satisfaction, and completion rates can favor very short videos. Analyze quality by duration and format. Consider duration-normalized measures, meaningful completion, explicit usefulness and bounded engagement contributions; none is a universally reliable satisfaction label.
If some viewing remains ongoing when training data is generated, wait for the chosen label window or handle censoring explicitly. Distinguish streaming or live content from finite prerecorded video. Compare predicted and observed expected duration by cohort and validate both the start-probability and conditional-duration components.
10. Multi-objective ranking and responsible engagement#
A possible educational utility combines viewer satisfaction with a bounded engagement contribution and negative feedback:
utility =
0.6 * predicted_satisfaction
+ 0.2 * min(expected_watch_seconds / 300, 1)
- 0.2 * predicted_negative_feedbackAll coefficients and the 300-second normalizer are fabricated to demonstrate scale alignment and bounded influence, not operational parameters. Satisfaction and negative-feedback probabilities in this example are assumed to be per-impression outcomes under a consistent horizon. They must be estimated and calibrated against appropriately defined labels. The utility is a dimensionless ranking score, not a probability.
A worked example:
| Video | P(start) | Conditional watch seconds | P(satisfaction) | P(negative feedback) | Utility |
|---|---|---|---|---|---|
| A | 0.50 | 200 | 0.90 | 0.05 | 0.5967 |
| B | 0.80 | 300 | 0.70 | 0.10 | 0.5600 |
| C | 0.80 | 600 | 0.50 | 0.20 | 0.4600 |
A ranks first because the stated utility favors its satisfaction estimate despite C's longer expected watch time. The formula does not prove that these weights produce beneficial outcomes. In real deployment, assess Pareto trade-offs, calibrate the tasks, solicit appropriate viewer feedback and agree on safety and product constraints.
Safety is not a soft negative term that a sufficiently high engagement score can cancel. Audience restrictions, rights, explicit user blocks and other mandatory conditions must be enforced independently. The system must not aim to keep viewers watching against their wishes, exploit emotional distress, or treat a user's decision to stop as a failure to be overcome. Respect intentional task completion, break and autoplay controls, and age-appropriate experiences.
11. Slate construction, creator diversity and safety#
The top-K independent scores may produce an unsatisfactory slate if they all represent the same creator or near-duplicate topic. Construct a list with explicit constraints and measurable diversity.
Apply hard eligibility, deduplication, then an appropriate creator/topic diversity strategy. Maximum marginal relevance is one possible greedy reranker: select a candidate using a combination of its relevance and the maximum similarity to already selected items. Ensure the similarity and relevance terms have compatible scales. Other approaches include constrained top-K, exposure-aware optimization and topic coverage objectives.
Use constraints according to surface intent. A creator-specific or subscription-focused experience may appropriately show several videos from the same channel; an open-ended Home feed benefits from varied options. Do not force unrelated content into a list merely to satisfy a diversity quota. If there are too few eligible candidates, return fewer rather than bypass mandatory restrictions.
Separate moderation from recommendation. Content eligibility can include approved audience classification, regional licensing, private/unlisted access, removal, user blocks and other applicable product policies. Treat missing eligibility information according to an approved conservative policy; never infer that a missing restriction means content is permitted.
Safety evaluation must consider the recommendation sequence, not only individual items. Repeated exposure to inappropriate or unwanted content may create cumulative harm even when isolated items satisfy a narrow item-level criterion. Provide accessible controls for feedback, history and recommendation resets; propagate them promptly. Where minors are involved, apply appropriate protective policies and evaluate the experience separately with authorized oversight.
12. Exploration, exploitation and feedback loops#
Exploitation recommends currently well-supported relevant content. Exploration gives eligible new or uncertain candidates a controlled opportunity to be evaluated. Without exploration, a model may continue selecting popular creators because historical exposure provided them with the most evidence.
The loop is not inherently harmful, but it can amplify selection effects. Unshown videos have no observed response in that context. A new uploader with few views may have insufficient evidence, not poor relevance. Track coverage and exposure distribution and measure the effect of ranking changes on a representative set of users and creators.
A contextual bandit can choose among approved eligible exploration candidates using uncertainty-aware selection. Log action probabilities and policy versions for statistical analysis. Do not explore content whose eligibility or safety is unverified. Exploration is optional and bounded by viewer intent, user controls and agreed guardrails, not a license to maximize attention.
For a simplified one-step evaluation, inverse propensity scoring estimates the reward of a target policy using the ratio of target to logging-policy action probabilities. It requires overlap, correct logged propensities, consistent rewards and suitable assumptions. Slate probabilities and session interference complicate this substantially. A policy that never showed a particular video cannot provide empirical evidence of that viewer's response to it. Clipping weights reduces variance at the cost of bias. Use controlled online evaluation where permitted rather than claiming that replay alone proves engagement uplift.
Avoid training on clicks alone: misleading previews may receive many clicks and few satisfied viewers. Include feedback quality, exposure position and appropriate satisfaction measures, and monitor changes in how the UI itself affects labels.
13. Tested Python example: bounded utility and constrained reranking#
The following standard-library example operates on synthetic, canonical video records with already-resolved eligibility. It calculates expected-watch-based utility and greedily selects a slate with a configurable creator cap. It demonstrates the decision layer, not trained retrieval, learned probabilities or a production content-safety service.
PYTHONfrom dataclasses import dataclass from math import isfinite @dataclass(frozen=True) class Video: id: str creator: str eligible: bool start: float watch_seconds: float satisfaction: float negative_feedback: float def utility(v): probs = (v.start, v.satisfaction, v.negative_feedback) if not all(isfinite(p) and 0 <= p <= 1 for p in probs): raise ValueError('invalid probability') if not isfinite(v.watch_seconds) or v.watch_seconds < 0: raise ValueError('invalid duration') return (0.6 * v.satisfaction + 0.2 * min(v.start * v.watch_seconds / 300, 1) - 0.2 * v.negative_feedback) def select(videos, k, creator_cap=1): if type(k) is not int or k < 0 or type(creator_cap) is not int or creator_cap < 1: raise ValueError('invalid limits') eligible = {} for v in videos: if not v.eligible: continue score = utility(v) if v.id in eligible and eligible[v.id][1] != v: raise ValueError('inconsistent canonical record') eligible[v.id] = (score, v) result, counts = [], {} for _, v in sorted(eligible.values(), key=lambda x: (-x[0], x[1].id)): if len(result) >= k: break if counts.get(v.creator, 0) >= creator_cap: continue result.append(v.id) counts[v.creator] = counts.get(v.creator, 0) + 1 return result a = Video('a', 'c1', True, .5, 200, .9, .05) b = Video('b', 'c1', True, .8, 300, .7, .1) c = Video('c', 'c2', True, .8, 600, .5, .2) d = Video('d', 'c3', False, 1., 1000, 1., 0.) assert abs(utility(a) - (.54 + .2/3 - .01)) < 1e-12 assert utility(a) > utility(c) assert select([a,b,c,d,a], 3) == ['a','c'] assert select([a,b,c,d], 3, 2) == ['a','b','c'] assert select([d], 2) == [] assert select([a], 0) == [] assert select([], 3) == [] assert select([Video('z','c2',True,.5,200,.9,.05),a], 2) == ['a','z'] for fn in [lambda: utility(Video('x','c',True,1.1,1,.5,0)), lambda: utility(Video('x','c',True,.5,float('nan'),.5,0)), lambda: select([a],1,0), lambda: select([a,Video('a','c1',True,.5,200,.1,.05)],2)]: try: fn() except ValueError: pass else: raise AssertionError('invalid input accepted') print('12 checks passed')
Observed local execution:
12 checks passedThe checks cover utility arithmetic, satisfaction-over-watch-time ordering, ineligible content, duplicate IDs, creator limits, empty input, zero list size, deterministic ties, invalid probabilities/durations and inconsistent eligible records. The greedy cap is a simple illustration and does not solve arbitrary slate optimization problems.
For N candidates, deduplication and scoring are O(N) expected time with hash maps, sorting is O(N log N), and additional storage is O(N). The function assumes that eligibility and canonical identity have been authoritatively resolved; contradictory eligibility or creator records must be rejected or reconciled upstream, with final policy revalidation before serving. In production, enforce all applicable constraints even if a candidate is ranked first.
These tests establish implementation behavior on the supplied synthetic cases. They do not establish actual model quality, user satisfaction, creator fairness or production safety.
14. Real-time serving and freshness#
An illustrative request includes surface ID, authorized session reference, optional current video ID, locale, request ID, page size and cursor. The response includes ordered video IDs, relevant metadata, compatible snapshot or pagination version and safe explanations where available. Do not expose private model features or unrelated viewer history.
Use parallel retrieval with a shared deadline, batched feature hydration and vectorized inference. Candidate generators should have bounded time and result budgets. For example, a 200 ms planning budget could reserve 20 ms for request context, 60 ms for retrieval, 35 ms for features, 50 ms for ranking and 35 ms for final policy and serialization. These are budgets, not measured per-stage latencies; test the real end-to-end p95/p99 under load.
Cache shared video embeddings, nonpersonalized candidate pools and static metadata. Personalized caches require viewer-scoped authorization, expiry, and invalidation on blocks or history changes. Do not reuse another viewer's personalized slate. Use a compatible request snapshot for pagination and recheck content restrictions on subsequent pages.
New uploads enter candidate indexes only after applicable eligibility checks. A newly removed or restricted video should not be recommended merely because a stale index contains it. Propagate versioned tombstones, prevent older upserts from resurrecting records and maintain an authoritative final check. The playback authorization service must independently enforce access and rights.
15. Scalability and storage design#
| Store | Role |
|---|---|
| Canonical video and policy catalog | Authoritative IDs, visibility, rights and eligibility versions |
| Embedding/index service | ANN retrieval and version-compatible video vectors |
| Subscription and explicit preference service | Authorized user controls and selected interests |
| Online feature store | Batched low-latency context and item features |
| Session state store | Short-lived ordered context under privacy settings |
| Event log and historical data lake | Impression, feedback and catalog lineage |
| Model registry | Retrieval, ranking, calibration and preprocessing artifacts |
| Experiment and evaluation store | Assignment, metrics, release and audit records |
Shard or partition large indexes and replicate frequently accessed regions. Balance ANN recall, search fan-out, memory, rebuild frequency and query tail latency. Popular videos and creators can create hot feature keys; cache public compatible features and avoid duplicate reads.
Use separate lightweight and expensive ranking stages if benchmarking shows a benefit: a cheap pre-ranker can reduce 1,000 candidates to a smaller set for a deeper model. Keep the conceptual two-stage retrieval/ranking distinction; a pre-ranker is an implementation optimization within ranking.
Use dynamic batching only where its queue delay fits the deadline. Compare CPU and accelerator throughput at realistic model and feature sizes. Training, embedding rebuilds and replay workloads should not exhaust live recommendation capacity. Measure cost per request, per eligible useful impression and per model release rather than raw hardware utilization alone.
New-item embeddings, traffic-driven session updates and model releases occur on different cadences. Fast feature updates do not require automatically deploying unreviewed model weights. Pin compatible artifact bundles, build new indexes in parallel and shadow retrieval before switching.
16. Cold start#
New viewer: use explicitly selected interests, language, current video context and approved nonpersonalized recommendations. Offer optional personalization controls rather than requiring invasive history. Avoid assuming everyone shares the same interests based on demographic traits.
New video: use permitted content representations, creator-provided metadata and appropriately governed priors. Evaluate content eligibility before allowing discovery. Use limited exploration where appropriate to collect feedback, avoiding automatic preference for already popular creators.
New creator or niche topic: monitor exposure and retrieval coverage, verify metadata quality and avoid suppressing a creator solely for lack of historical interactions. Diversity and exploration must remain relevant to the viewer rather than guarantee arbitrary exposure irrespective of quality.
17. Evaluation and controlled experiments#
Measure each stage and the complete experience.
| Layer | Metrics and interpretation |
|---|---|
| Retrieval | Recall@K, eligible recall, coverage of fresh and long-tail videos |
| Ranking | NDCG@K, task-specific log loss, calibration, watch-time error |
| Slate | Duplicate rate, creator/topic redundancy, relevance and eligibility violations |
| Viewer value | Satisfaction survey estimates, meaningful voluntary engagement, explicit negative feedback |
| Responsible experience | User-control effectiveness, inappropriate exposure incidents, unwanted repetitive sequences |
| Creator ecosystem | Exposure concentration, new-creator coverage, performance by relevant governed cohorts |
| Serving | p50/p95/p99 latency, timeout rates, fallback, index and feature age |
Offline retrieval evaluation must use the candidate universe and eligible video snapshot as of each prediction. Recall@K is the fraction of known relevant eligible items retrieved among the top K; judged or observed relevance is often incomplete. For ranking, NDCG discounts gain at lower positions. Use appropriate relevance labels rather than assuming watch duration is the only gain.
A synthetic example: if three relevant videos are present among five retrieved results and the evaluated eligible universe has four known relevant videos, precision@5 is 0.6 and recall is 0.75. These are arithmetic illustrations, not measured platform metrics.
Calibrate predicted starts and feedback by surface and cohort. Evaluate duration predictions conditionally and per impression. Measure satisfaction survey response bias: respondents may differ from nonrespondents. Use representative sampling, justified weighting and uncertainty estimates, not an assumption that silence is satisfaction.
Shadow candidate models first. Compare with an approved baseline on identical historical or live context without changing what viewers see. Shadowing can measure latency, compatibility, feasibility and quality on observed outcomes, but cannot establish counterfactual responses for different unseen slates.
For controlled experiments, assign suitable units before exposure, specify primary viewer-value outcomes, guardrails, duration and analysis plan. Account for repeated sessions and possible creator-side interference. Evaluate intent-to-treat and include users who stopped viewing or gave negative feedback. Use longer-horizon evaluation for novelty effects, while respecting privacy and retention rules. Never run a variant that intentionally violates safety or explicit user controls.
An experiment with higher watch time but worse satisfaction, stronger unwanted repetition, or more safety violations should not automatically win. Require independent policy and responsible-experience approval rather than collapsing every concern into one scalar.
18. Reliability, privacy and production failure handling#
| Failure | Approved response |
|---|---|
| Session features unavailable | Use current video context or nonpersonalized mode |
| Candidate source timeout | Continue with remaining compatible eligible sources |
| Ranker timeout or invalid scores | Use validated relevance baseline |
| Embedding/index incompatibility | Reject affected source and restore compatible bundle |
| Eligibility service unavailable | Use only independently verified eligible items under approved policy, or withhold results |
| Removed video in cached slate | Revalidate, remove and reconcile stale projections |
| Consent or block changes | Invalidate affected features and personalized caches |
| Event lag | Degrade freshness appropriately and delay unreliable evaluation |
| Quality or safety regression | Stop rollout, restore approved compatible policy/model and investigate |
Use circuit breakers, deadline propagation, bounded retries, backpressure, isolated resource pools and monitored degradation. A fallback may simplify relevance scoring, never bypass safety or access control. If no safe candidates remain, return fewer or no recommendations.
Protect viewer history and creator data through purpose limitation, authorization, encryption, retention limits and audit logs. Honor opt-outs, deletion and user-defined blocks across caches, indexes, derived features and future training snapshots. Do not infer sensitive interests or personal vulnerability to increase engagement. Handle already trained artifacts under documented governance rather than falsely promising immediate removal of all learned influence.
Log model versions and outcome data necessary for debugging, not unrestricted personal viewing traces. Restrict sensitive event access, validate business metadata, and treat captions, transcripts and user text as untrusted input. If a generative explanation component is used, it must not invent endorsements, policy facts or sensitive profile details.
Monitor exposure and complaint trends, feature freshness, index drift, calibration and safety incidents. A model quality issue can originate in a catalog change, label defect, feature outage, UI experiment or embedding mismatch rather than the model itself. Keep independent rollback control for retrieval, ranker, index and policy; never roll back a current safety restriction merely to restore an older model's behavior.
19. Interview trade-offs and concise answer#
Why two stages? Retrieval provides high recall at catalog scale, while ranking uses expensive context and multiple task outputs on a bounded shortlist.
Why not optimize CTR or watch time alone? Both are imperfect proxies. They can reward misleading previews, long duration or unwanted viewing. Include satisfaction, voluntary engagement and negative feedback with independent safety and viewer-control constraints.
How do you handle new videos? Use content embeddings and eligible exploration rather than relying solely on historical engagement.
How do you avoid a popularity feedback loop? Log exposure and selection, preserve useful source diversity, evaluate long-tail coverage, and use approved exploration with known selection probabilities where appropriate.
What if the ranking model fails? Fall back to an independently validated local-in-context relevance policy, with current content restrictions and viewer controls still enforced.
Interview-ready summary: I would build a large-scale candidate retrieval service using subscriptions, collaborative/content embeddings, and recent-session context. A multi-task deep ranker would estimate intentional starts, conditional watch time, satisfaction and negative feedback. The final slate would balance useful engagement with creator diversity, explicit viewer controls and hard eligibility. Streamed events support point-in-time learning, while regional indexes, batch inference, compatible versioning and validated fallbacks keep serving fast and reliable. I would evaluate offline recall, NDCG and calibration and use controlled online experiments for viewer satisfaction and responsible long-term outcomes. The crucial design principle is optimizing worthwhile engagement, not maximizing time spent regardless of viewer intent or harm.
References and research transparency#
The authorized offline research exception was applied. The references below identify established papers and technical resources; current link availability, contents and Supabase changelog could not be live-verified. Historical YouTube research is not evidence of its present-day proprietary implementation. All four Mermaid diagrams are written in standard triple-backtick Mermaid fences and structurally reviewed. The local runtime has no Mermaid parser installed, so parser execution and live website rendering were not verified. The Python example was actually executed locally with all 12 checks passing. No real viewer data or empirical engagement gains are claimed.
- Covington, Adams and Sargin (2016) — Deep Neural Networks for YouTube Recommendations
- Zhao et al. (2019) — Recommending What Video to Watch Next: A Multitask Ranking System
- Ma et al. (2018) — Modeling Task Relationships in Multi-task Learning with Multi-gate Mixture-of-Experts
- Kang and McAuley (2018) — Self-Attentive Sequential Recommendation
- Johnson, Douze and Jégou — Billion-scale Similarity Search with GPUs
- Swaminathan and Joachims — Counterfactual Risk Minimization: Learning from Logged Bandit Feedback
- Carbonell and Goldstein — The Use of MMR, Diversity-Based Reranking
- Guo et al. — On Calibration of Modern Neural Networks
- Kohavi, Tang and Xu — Trustworthy Online Controlled Experiments
- Google — Rules of Machine Learning: Best Practices for ML Engineering
- NIST — AI Risk Management Framework 1.0
- NIST — Privacy Framework
References
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.Guo et al. — On Calibration of Modern Neural Networksproceedings.mlr.press
- 9.
- 10.Google — Rules of Machine Learning: Best Practices for ML Engineeringdevelopers.google.com
- 11.
- 12.NIST — Privacy Frameworknist.gov
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython