Above-the-Fold Deduplication for the Netflix Home Screen
Hard · System Design · Software Engineer · Technical Screen
Prompt
On the Netflix home screen, horizontal carousels (such as Continue Watching, Top 10, genre shelves, and similarity rows) are scored by independent ranking models, causing popular series to rank near the top of several rows at once. Design the initial-screen (above-the-fold) rendering pipeline so every visible slot on the first screen displays a distinct show—with zero duplicates within any single row or across rows.
Specify the data schema for candidate shelves and title assets, the personalization signals consumed during assembly, and hard product rules (including profile maturity caps, regional licensing windows, shelf theme membership, fixed-order charts, and editorial slot pins). Propose a selection and placement algorithm that enforces uniqueness while maximizing expected member engagement, and explain cross-row conflict resolution, candidate backfill when shelves run short, server- vs. client-side latency budgets, graceful fallbacks for missing upstream data, multi-tier caching, lazy loading on vertical and horizontal scroll, and offline/online impact measurement.
Scope & Expectations
- Model series-level deduplication (
show_idvs. season/trailervideo_id), score calibration across heterogeneous row models, and fail-closed safety filters applied prior to placement. - Formulate the cross-row assignment algorithm, priority ordering for fixed-order shelves and editorial pins, theme-aware backfill or spare-row substitution, and a realistic server
p99latency budget. - Detail multi-layer caching, deterministic fallbacks when ranking or metadata dependencies time out, and duplicate-free horizontal and vertical scroll pagination.
- Define offline replay verification and household-randomized A/B experiment metrics (qualified play rates, streaming retention, and safety/latency guardrails) to validate impact.
Step-by-step walkthrough
Clarify the viewport deduplication problem and requirements
The Netflix home page is a vertical stack of horizontal rows (
"Continue Watching","Top 10 Today","Because You Watched...", genre rows), each ranked independently by its own model. Because a hit series can score near the top of four different rows at once, rendering each row as-is fills the above-the-fold viewport (the initial screen visible before any vertical or horizontal scrolling) with duplicate tiles of the same show — wasting the highest-attention pixels on the page.Pin down two foundational definitions with the interviewer first:
- Deduplication zone (
Zcells): Every visible cell on the first screen, plus a 1-tile horizontal and 1-row vertical margin to cover partially visible "peek" tiles at the screen edges. The client sends its device class and visible grid dimensions; for example, TV/desktop web uses1Hero billboard +4 rows * 7 tiles = 29cells, while mobile portrait uses1 + 4 * 4 = 17cells. - Deduplication key (
show_id, notvideo_id): Season 1, Season 2, a teaser trailer, and a holiday special are differentvideo_idassets that all belong to one parentshow_id. Mappingvideo_id -> show_idensures two seasons or clips of the same series never appear together in the zone.
Functional requirements
- Every cell in the dedup zone displays a distinct
show_id(no duplicates within a row or across rows). - Enforce hard constraints without exception: profile maturity limits, country licensing windows, row theme rules (
"Comedies"only shows comedies), fixed-order rows (Continue Watchingby recency, numberedTop 10), and editorial pins. - Maximize expected user engagement by placing contested shows into the row where they are most likely to trigger a play.
- Backfill rows that run short after deduplication (or swap in a spare row) so the user never sees blank holes.
- Support smooth vertical and horizontal lazy loading on scroll without revealing jarring duplicates.
- Log decisions and impressions cleanly to measure impact offline and in A/B tests.
Non-functional requirements
- Latency: Server
p99under200 msfor the initial above-the-fold payload. - Determinism: Given identical inputs, assembly always produces the exact same layout (critical for caching, debugging, and offline replay).
- Fail-closed safety: Fail-closed means that if a show's maturity rating or a profile's maturity limit is missing or corrupt, the system drops the show (or applies the strictest Kids rating) rather than ever risking unsuitable content.
- Graceful degradation: If a ranking service times out, fall back to cached or country-popular candidates rather than failing the page load.
- Deduplication zone (
Back-of-the-envelope numbers
Traffic (assumed) 100M daily active profiles * 3 home page loads/day = 300M loads/day Average: 300,000,000 / 86,400 s ~ 3,500 req/s Evening prime-time peak (~3x): ~10,000 req/s Candidate volume per profile ~40 candidate rows * ~75 candidate shows/row = ~3,000 (show_id, score) entries/profile Dedup zone on TV/desktop: Z = 1 Hero + (4 rows * 7 tiles) = 29 cells CPU cost of dedup per request By the Pigeonhole Pruning Rule (Deep Dive 1), only the top Z = 29 shows per zone row can ever participate -> (1 + 4) * 29 = 145 (row, show) pairs! Sorting ~145 tuples in RAM takes < 0.1 ms (microseconds). Storage & payload Precomputed candidates: 100M profiles * 3,000 entries * 12 bytes ~ 3.6 TB raw -> Stored in a sharded key-value store + RAM cache tier (not recomputed from scratch per load) First-screen JSON payload: 29 tiles * ~300 bytes (IDs, title, artwork URL, badges) ~ 9 KB rawThree design lessons follow immediately: 1. The dedup algorithm itself takes
< 1 millisecond(~145pairs), so network fan-out to fetch candidates and metadata dominates our200 msbudget. 2. Row candidates must be precomputed offline/nearline; running heavy neural rankers over3,000items at10,000 req/s(30Mneural evaluations/s) on every page load is prohibitively expensive. 3. Total profile state (~3.6 TB) is large across all members, but tiny per request (~36 KBfor one profile read).API design
// 1. Initial above-the-fold request (profile_id & maturity tier come from the signed auth token, // NEVER from query parameters that a client could tamper with!) GET /v1/home?device_class=tv&grid=4x7&locale=en-US -> 200 { "page_id": "pg_9c4e_v18", "hero": { "show_id": 204, "video_id": 7712, "artwork_url": "...", "pinned": true }, "rows": [ { "row_id": "continue_watching", "title": "Continue Watching", "items": [ { "show_id": 58, "video_id": 4190, "progress": 0.65, "artwork_url": "..." } ], "has_more": true } // ... rows 2..4, 7 tiles each; all 29 show_ids across hero + 4 rows are unique! ], "next_rows_cursor": "cur_row_5", "degraded": [] // e.g. ["row_candidates_stale"] when using a fallback } // 2. Vertical scroll: fetch next batch of rows below the fold GET /v1/home/rows?page_id=pg_9c4e_v18&cursor=cur_row_5&count=4 // 3. Horizontal scroll: fetch tiles 7..26 inside an existing row GET /v1/home/rows/{row_id}/items?page_id=pg_9c4e_v18&offset=7&limit=20 // 4. Client viewport impression telemetry POST /v1/events/impressions { "page_id": "pg_9c4e_v18", "impressions": [{ "row_id": "...", "pos": 0, "show_id": 58, "ms": 1800 }] }page_idbinds subsequent vertical/horizontal scroll requests to the exactshown_show_idsalready rendered on screen, and joins impression/play logs back to the exact page layout for A/B attribution.gridlets the server size the dedup zone to the user's screen (rounding unfamiliar window sizes up to a small set of standard grid buckets like4x7or4x4so cache hit rates stay high).
Data model, personalization inputs, and score calibration
shows show_id PK (dedup key!), genres[], maturity_rating, release_date videos video_id PK, show_id FK (maps seasons, trailers, specials -> 1 show_id) availability (show_id, country) PK -> window_start, window_end row_definitions row_type PK, theme_filter, fixed_order BOOL, skippable BOOL, min_items INT row_candidates (profile_id, page_version) PK -> { row_id: [(video_id, show_id, cal_score)] } charts (country, chart_type) PK -> ordered [show_id] // e.g. Top 10 Today pins pin_id PK, row_type, position, show_id, countries[], start_at, end_at fallback_pools (country, maturity_tier, theme) PK -> ordered popular [show_id] profile_context profile_id PK -> maturity_limit, is_kids, locale, continue_watching[], my_list[] page_sessions page_id PK -> profile_id, grid_bucket, shown_show_ids SET, TTL = 30 minPersonalization inputs (fed into offline/nearline row rankers and lightweight online re-scoring): viewing history and completion ratios, active
Continue Watchingprogress,My Listadditions, thumbs ratings, recent search queries, impression fatigue (demoting titles shown repeatedly on prior home loads without a click), time of day, device class (tvvsmobile), country, and audio/subtitle preferences.Two modeling invariants make cross-row deduplication work properly: 1. Collapse
video_id -> show_idper row first: After filtering illegal items, if a row contains both Season 1 (0.61) and Season 2 (0.74) ofshow_id = 55, keep only the highest-scoring legal asset (0.74) so every row's candidate list has strictly distinctshow_ids before dedup begins. 2. Score calibration across models: Comparing a raw neural logit3.8from"Because You Watched"against a heuristic score0.45from"Trending"is meaningless. Every row model undergoes score calibration — mapping raw model outputs onto one shared probability scale,P(play | impression in row i), using isotonic regression (fitting a non-decreasing piecewise lookup curve on held-out historical impression logs).High-level architecture
Client (TV / Web / Mobile) | GET /v1/home?device_class=tv&grid=4x7 v +--------------+ check 5-min cache +------------------------------------------+ | Home API |-------------------------->| Page Cache: (profile, device, grid) | +--------------+ +------------------------------------------+ | cache miss v +-------------------------------------------------------------------------------------+ | Stateless Page Assembler (parallel fan-out with strict 60 ms dependency timeouts) | +-------------------------------------------------------------------------------------+ |---> [ Profile Context Store ] (maturity_limit, Continue Watching, My List) |---> [ Page Ranker Service ] (ordered zone rows + 2 spare rows) |---> [ Candidate KV Store ] (precomputed calibrated row_candidates) |---> [ Local 1-min RAM Caches ] (Top 10 charts, editorial pins, fallback pools, | show metadata, country availability) | | Pipeline inside Page Assembler (< 10 ms CPU): | 1. Hard-filter every candidate (maturity, country, theme) & collapse video->show | 2. Run zone dedup: Fixed rows -> Editorial pins -> Global greedy -> Backfill | 3. If a non-skippable chart collided or a row stayed short, swap in a spare row | 4. Hydrate localized titles & personalized artwork URLs for the 29 zone cells | 5. Write `shown_show_ids` to Session Cache (TTL 30 min) & return JSON v Decision & Impression Logs ---> Offline Replay & A/B Experiment PipelineRunning hard filters before deduplication is non-negotiable: an out-of-country or over-maturity show must never win a cell during deduplication and then get stripped out during rendering, leaving an empty hole on screen.
Deep dive 1: Selecting and placing shows to maximize relevance
Once fixed rows and pins claim their cells, we want to assign unique shows
tto the remaining flexible zone rowsi = 1..R(each needings_icells, with row visibility weightw_iestimated from how often users look at rowi) to maximize expected plays:Maximize: sum over chosen (i, t) of w_i * score(i, t) Subject to: 1) Every show_id `t` is chosen at most ONCE across the whole zone 2) Every row `i` receives at most `s_i` showsThis is a maximum-weight bipartite matching problem (pairing rows on one side with unique shows on the other side to maximize total weighted score). Let's compare three concrete algorithms on two rows with
1slot each and row weightsw_A = 1.0,w_B = 0.8:Case 1: Row A ("Trending", w=1.0): Show X (0.50), Show Y (0.45) Row B ("Because You Watched", w=0.8): Show X (0.95), Show Z (0.20) - Naive Row-by-Row (top down): Row A grabs X (1.0 * 0.50 = 0.50); Row B is stuck with Z (0.8 * 0.20 = 0.16) -> Total = 0.66 - Global Greedy (sort all (row, show) pairs by w_i * score descending): Pairs: (B, X)=0.76, (A, X)=0.50, (A, Y)=0.45, (B, Z)=0.16 1) (B, X) wins! Row B gets X (0.76). 2) (A, X) skipped (X already used). 3) (A, Y) wins! Row A gets Y (0.45). -> Total = 1.21! Case 2 (where Global Greedy is slightly suboptimal): Row A (w=1.0): Show X (0.90), Show Y (0.85) Row B (w=0.8): Show X (0.80), Show Z (0.10) - Global Greedy picks (A, X)=0.90 then (B, Z)=0.08 -> Total = 0.98 - Exact Min-Cost Flow picks (A, Y)=0.85 + (B, X)=0.64 -> Total = 1.49- Why Global Greedy has a strong worst-case floor: The two rules ("at most 1 cell per show" and "at most
s_icells per row") form the intersection of two partition matroids (simple group-capacity constraints), which mathematically guarantees Global Greedy achieves at least50%of the exact optimum in the worst adversarial case — and typically> 98%on real recommendation lists! - Exact Min-Cost Max-Flow (a standard graph algorithm that routes flow along lowest-cost augmenting paths) solves
~145edges to100%optimality in< 1 ms, and also lets you assign per-cell weightsw[i][j](so Row 1's far-right 7th tile does not outrank Row 2's top-left 1st tile!). Ship Global Greedy first because it is tiny, deterministic, and easy to explain to product/editorial teams ("Show X went to the row with the highest expected play score"), and run Min-Cost Flow on offline logs to check if the real play-score gain justifies switching.
The Top-
ZPigeonhole Pruning Rule (why we only inspect29candidates per row): Suppose the entire above-the-fold zone hasZ = 29cells total. Even if every single other cell on screen (<= 28cells) took a show from Rowi's top29distinct legal shows, at least29 - 28 = 1show inside Rowi's top29is guaranteed to remain unused! Therefore, no optimal solution ever needs to reach past rankZin any row (unless the row has fewer thanZcandidates total), shrinking40 * 75 = 3,000candidates down to~145pairs with zero loss of quality.- Why Global Greedy has a strong worst-case floor: The two rules ("at most 1 cell per show" and "at most
Deep dive 2: Conflict resolution, constraints, and backfill code
Conflicts between product rules are resolved by a strict 6-step claim hierarchy:
- Hard filters first: Strip any candidate failing profile maturity (fail closed!), country availability, or row theme, and collapse
video_id -> show_id. Editorial pins pass through the exact same maturity/country filter so a bad pin never leaks adult content onto a Kids profile. - Fixed-order rows claim first (in top-to-bottom display order):
- Skippable fixed rows (
Continue Watching,My List) keep their chronological/user order and silently skip ashow_idalready claimed by the Hero or an earlier fixed row. - Non-skippable fixed rows (numbered
"Top 10 Today", where skipping#2would render"#1, #3, #4") check if all visible slots are still free; if the Hero already claimed#2, move"Top 10 Today"intact to the first row below the fold and pull in a spare row above the fold!
- Skippable fixed rows (
- Editorial pins claim next at their exact
(row, position)coordinates; if a higher-priority fixed row already claimed thatshow_id, drop the pin and log a conflict warning for editors. - Flexible personalized rows share remaining cells via Global Greedy over each row's top
Zcandidates. - Theme-compatible backfill: Any flexible row still missing cells pulls unused shows from its
(country, maturity_tier, theme)popular fallback pool; if still short, replace the row with one of the2spare rows from the Page Ranker and re-run steps 2–5. - Intra-row left-to-right layout: Keep editorial pins locked at their target indices, and place picked shows left-to-right in descending score order (putting highest-probability titles in the highest-attention leftmost slots).
class Row: def __init__(self, row_id, candidates, fixed=False, pins=None, fallback=None): # candidates: [(show_id, calibrated_score)] sorted best-first, already hard-filtered # and collapsed so every show_id in `candidates` is distinct. self.row_id = row_id self.candidates = candidates self.fixed = fixed # True for skippable fixed-order rows (Continue Watching) self.pins = pins or {} # {slot_position: show_id}, already maturity-filtered self.fallback = fallback or [] # [show_id] popular in same country, tier, and theme def edge_sort_key(edge): # Sort descending by weighted_score; break ties deterministically by upper row, then show_id. weighted_score, row_idx, show_id, raw_score = edge return (-weighted_score, row_idx, show_id) def pick_sort_key(pick): # Within one flexible row, place higher calibrated scores further left. show_id, raw_score = pick return (-raw_score, show_id) def assemble_first_screen(rows, slots_per_row, row_weights): """Assign unique show_ids across `rows` (Hero is simply row 0 with 1 slot). Returns (cells_by_row, short_row_ids). """ zone_size = sum(slots_per_row) used_shows = set() # picks_by_row[i]: list of (show_id, raw_score) won by row i picks_by_row = [] # pinned_by_row[i]: {position: show_id} locked into specific columns of row i pinned_by_row = [] for _ in range(len(rows)): picks_by_row.append([]) pinned_by_row.append({}) # Phase 1: Fixed-order skippable rows claim first while preserving their exact order. for i, row in enumerate(rows): if row.fixed: for show_id, raw_score in row.candidates: if len(picks_by_row[i]) == slots_per_row[i]: break if show_id not in used_shows: used_shows.add(show_id) picks_by_row[i].append((show_id, raw_score)) # Phase 2: Editorial pins inside the viewport claim their exact slots next. for i, row in enumerate(rows): if row.fixed: continue for pos in sorted(row.pins): show_id = row.pins[pos] if pos < slots_per_row[i] and show_id not in used_shows: used_shows.add(show_id) pinned_by_row[i][pos] = show_id # Phase 3: Global greedy over the top `zone_size` candidates of each flexible row. candidate_edges = [] for i, row in enumerate(rows): if row.fixed: continue for show_id, raw_score in row.candidates[:zone_size]: weighted_score = row_weights[i] * raw_score candidate_edges.append((weighted_score, i, show_id, raw_score)) candidate_edges.sort(key=edge_sort_key) for weighted_score, i, show_id, raw_score in candidate_edges: open_slots = slots_per_row[i] - len(pinned_by_row[i]) - len(picks_by_row[i]) if open_slots > 0 and show_id not in used_shows: used_shows.add(show_id) picks_by_row[i].append((show_id, raw_score)) # Phase 4: Backfill any flexible row that ran short from its theme-matched fallback pool. short_row_ids = [] for i, row in enumerate(rows): if row.fixed: continue for show_id in row.fallback: if slots_per_row[i] - len(pinned_by_row[i]) - len(picks_by_row[i]) == 0: break if show_id not in used_shows: used_shows.add(show_id) # Score 0.0 ensures backfilled items sort to the right of real candidates. picks_by_row[i].append((show_id, 0.0)) if slots_per_row[i] - len(pinned_by_row[i]) - len(picks_by_row[i]) > 0: short_row_ids.append(row.row_id) # Phase 5: Place pins at their fixed indices and fill remaining slots best-first. cells_by_row = [] for i, row in enumerate(rows): if row.fixed: ordered_picks = picks_by_row[i] else: ordered_picks = sorted(picks_by_row[i], key=pick_sort_key) row_layout = [] pick_idx = 0 for pos in range(slots_per_row[i]): if pos in pinned_by_row[i]: row_layout.append(pinned_by_row[i][pos]) elif pick_idx < len(ordered_picks): row_layout.append(ordered_picks[pick_idx][0]) pick_idx += 1 cells_by_row.append(row_layout) return cells_by_row, short_row_idsTrace how
assemble_first_screenresolves every type of conflict on three rows (slots = [3, 3, 2],weights = [1.0, 0.9, 0.8]): - Row 0 (continue_watching,fixed=True):[("X", 1.0), ("P", 1.0), ("Q", 1.0)]-> Phase 1 claimsX, P, Qin order. - Row 1 (comedies,pins={0: "E"}): candidates[("X", 0.9), ("Y", 0.7), ("W", 0.6)], fallback["P", "F1", "F2"]-> Phase 2 locks"E"into slot0. - Row 2 (because_watched, flexible): candidates[("Y", 0.95)], fallback["X"]-> Phase 3 compares(Row 2, Y)(0.8 * 0.95 = 0.76) against(Row 1, Y)(0.9 * 0.70 = 0.63), so Row 2 wins"Y"while Row 1 takes"W"(0.54). - Backfill & layout (Phases 4–5): Row 1 needs1more show, skips already-used"P", and backfills"F1"->["E", "W", "F1"]. Row 2's only fallback"X"is already used, soshort_row_ids = ["because_watched"], signaling the Page Assembler to swap Row 2 with a spare row!- Hard filters first: Strip any candidate failing profile maturity (fail closed!), country availability, or row theme, and collapse
Deep dive 3: Server vs. client rendering, 200 ms latency budget, and caching
Where should deduplication run? Server-led hybrid. - Pure client-side dedup knows exact pixel bounds, but requires shipping thousands of raw candidates + scores over slow residential/cellular links and maintaining identical ranking/pin/fallback code across Smart TVs, iOS, Android, and browsers. - Instead, the client sends
device_classandgrid=4x7, the server runs the single authoritative dedup pipeline, and the client runs only a 10-line defensive UI guard that hides an accidental duplicate tile (if an expired session ever caused one on lazy scroll) and logs a bug metric.Server
p99latency budget (200 mstotal):Parallel fan-out (Profile Context + Page Ranker + Candidate KV Store) 60 ms Optional lightweight online re-scoring of top candidates (time/device) 50 ms Hard filters + video->show collapse + Global Greedy + Backfill + Layout < 5 ms Hydrate localized titles & personalized artwork URLs (RAM cache -> KV) 30 ms JSON serialization + gzip/brotli compression 10 ms Network & GC headroom 45 ms ------------------------------------------------------------------------------ Total server p99 budget 200 msThree-layer caching strategy: 1. Candidate KV store (hours + nearline minutes): Offline batch pipelines compute full candidate lists every few hours; a nearline stream processor updates
Continue Watchingand"Because You Watched..."within seconds of playback events. 2. Assembler in-process RAM cache (1 minTTL): Country availability maps,showsmaturity ratings, Top 10 charts, editorial pins, and fallback pools fit in a few hundred MB of local memory per server, avoiding network hops on every tile. 3. Assembled first-screen page cache (5 minTTL): Keyed strictly by(profile_id, device_class, grid_bucket)and invalidated immediately on playback, thumbs, orMy Listevents. Caching for 5 minutes keeps the home page stable when a user clicks into a show's detail modal and presses Back, while never sharing cache keys across profiles.Partial data fallbacks and scrolling (vertical and horizontal)
Every external read uses a strict
60 mstimeout and a deterministic fallback:Timed-out or missing dependency Fallback action Safety / UX impact Page Ranker (row ordering) Reuse profile's last cached row order, else country default row template Slightly less personalized One row's candidates missing Fill from theme fallback pool, or swap in a spare row Zero holes, valid theme Entire Candidate KV Store down Serve stale cached page for profile, else pre-built (country, maturity_tier, grid)popular pageInstant 200, non-personalContinue Watchingstore slowServe short-TTL cached list, else omit row ( degraded: ["cw_omitted"])Avoids stale resume point Profile maturity tier missing Default to strictest Kids tier ( fail closed)Zero maturity leaks Show's rating/metadata missing Drop that show_idduring Step 1 filtering (fail closed)Zero maturity leaks Scrolling below the fold and horizontally inside a row: - Vertical scroll (
GET /v1/home/rows): Loadsshown_show_idsfrompage_sessions[page_id]and runs the same dedup logic on the next 4 rows withused_showspre-populated. Below the fold, cross-page dedup is relaxed to a soft constraint: if strict dedup would leave a genre row belowmin_items, allow repeats of shows from far up the page rather than rendering a half-empty row (while still enforcing zero duplicates within the same row). - Horizontal scroll (GET /v1/home/rows/{row_id}/items): Filters outshown_show_idsfrom the initial zone so scrolling Row 2 to the right never slides in a show currently visible right below it in Row 3! - Session expiry (> 30 minidle tab): Encode(page_version, pins_snapshot_id, grid_bucket)insidepage_idand retain the previouspage_versionin the Candidate KV Store for ~35 minutes so the server can deterministically reconstruct the initialshown_show_idson a cache miss (falling back to the client's defensive UI guard if that version aged out).Measuring impact, scaling, and trade-offs
1. Offline replay validation (before touching live traffic) Replay logged production requests through the new assembler and verify:
0zone duplicates, total weighted calibrated play score (comparing Row-by-Row vs. Global Greedy vs. Exact Min-Cost Flow), backfill & spare-row swap rates, genre entropy/diversity across the 29 cells, and< 5 msassembly CPU.2. Online A/B testing - Randomize by household account, not individual profile: Family members share living-room TVs and talk to each other; account-level bucketing prevents spillover between control and treatment. - Primary metrics: Home-page qualified play rate per visit (fraction of home loads resulting in
>= 2 minutesof playback) and above-the-fold plays per visit. Compare per-visit rates rather than per-tile click-through rates, because deduplication shifts shows across row positions (position bias). - North-Star & secondary metrics: Long-term member streaming hours and retention (measured over>= 2–4 weeksor a long-term holdout so novelty effects settle), time-to-first-play, and vertical/horizontal scroll depth. - Guardrail metrics: Serverp99latency,degradedfallback rate,Continue Watchingresume rate, editorial pin play rate, and0client-reported duplicate escapes.Summary of trade-offs: Global Greedy trades a tiny theoretical optimality gap vs. Min-Cost Flow for simplicity and editorial explainability; calibrated probabilities + row weights ensure that when strict dedup takes a show from three rows, the single winning row is where the user is most likely to press Play; the server-led grid-bucket hybrid unifies logic across TV/web/mobile while respecting device screen sizes; and fail-closed filtering guarantees child-profile safety even during partial outages.
Intuition & how it works
Think of assembling Netflix's initial home screen like arranging the front display window of a bookstore where four department managers ("Trending", "Sci-Fi", "Critically Acclaimed", and "Because You Watched Dark") all nominate the exact same #1 bestseller for their shelf. Putting four copies of the same book in the front window wastes three prime display spots where a passerby could have discovered another title they love! To fill the above-the-fold viewport (the first screen of tiles visible before any scrolling) with zero duplicates while keeping recommendations super relevant, we first map every season, trailer, and clip (video_id) to its parent series (dedup key show_id), apply fail-closed filtering (immediately dropping any show with missing or over-limit maturity ratings or expired country rights before placement begins), standardize different row models with score calibration (converting raw scores from separate ML models onto one shared probability scale: the chance of a play given an impression), and solve a bipartite matching problem (pairing rows with unique shows so each contested show lands in the row where it creates the highest expected play value, while runner-up shows fill the other rows).
Why do the naive approaches fail? Deduplicating by video_id instead of show_id lets a Season 1 tile and a Season 2 trailer of the exact same series appear side by side. Deduplicating greedily row-by-row from top to bottom lets Row 1 ("Trending") grab a show it prefers by 0.02 over its runner-up, robbing Row 2 ("Because You Watched Dark") of the only show that strongly fits its theme. And running maturity or licensing filters after deduplication lets an ineligible show claim a viewport slot and then get stripped out at render time, leaving a broken blank gap on screen.
Let's trace a tiny concrete viewport with 5 cells total — Hero (1 slot, pinned), Row A (2 slots, weight 1.0), and Row B (2 slots, weight 0.8) — after collapsing video_id -> show_id and filtering maturity:
Inputs:
Hero (pinned): Show M
Row A (w=1.0): candidates [(M, 0.92), (S1, 0.50), (S2, 0.48), (S4, 0.40)], fallback [FB1]
Row B (w=0.8): candidates [(S1, 0.95), (S3, 0.60)], fallback [S2, FB2]
Step 1 - Fixed / Pinned claims:
Hero claims Show M -> used = {M}. (Row A's (M, 0.92) will now be skipped automatically!)
Step 2 - Global Greedy sorts remaining (row, show) pairs by (row_weight * score) descending:
1) (Row B, S1): 0.8 * 0.95 = 0.76 -> S1 unused, Row B needs 2 -> Row B gets S1! used = {M, S1}
2) (Row A, S1): 1.0 * 0.50 = 0.50 -> S1 already in `used` -> skipped!
3) (Row A, S2): 1.0 * 0.48 = 0.48 -> S2 unused, Row A needs 2 -> Row A gets S2! used = {M, S1, S2}
4) (Row B, S3): 0.8 * 0.60 = 0.48 -> S3 unused, Row B needs 1 -> Row B gets S3! used = {M, S1, S2, S3}
5) (Row A, S4): 1.0 * 0.40 = 0.40 -> S4 unused, Row A needs 1 -> Row A gets S4! used = {M, S1, S2, S3, S4}
Step 3 - Left-to-right layout (all 5 viewport cells unique, total weighted score = 1.72):
Hero: [M] | Row A: [S2, S4] | Row B: [S1, S3]
(Notice: naive top-down would have given S1 to Row A and forced Row B to backfill FB2!)
Key trade-offs
- Row-by-row top-down vs. Global Greedy vs. Exact Min-Cost Flow. Top-down greedy is trivial to code but lets upper rows hoard contested shows for tiny marginal gains. Global Greedy by
w_i * score(i, t)fixes cross-row hoarding, runs in microseconds on~145pairs (only the topZshows per row can ever matter by the pigeonhole principle), is deterministic and easy to explain to editors, and is guaranteed at least50%of optimal via matroid intersection (combining the one-cell-per-show rule ands_i-cells-per-row rule). Min-Cost Max-Flow (an exact graph-flow solver) achieves100%optimality and supports per-cell(row, column)visibility weights in< 1 ms, at the cost of trickier debugging and explainability; measure the offline gap on real logs before choosing flow over Global Greedy. - Strict uniqueness vs. per-row relevance. Forcing zero duplicates inevitably takes a popular show away from 2–3 rows. Using calibrated
P(play | impression)scores weighted by row visibility ensures the contested show lands where a play is most likely, while theme-matched fallback pools and2spare rows from the Page Ranker prevent weak or empty rows. - Server-side vs. client-side deduplication. Pure client-side dedup knows the exact pixel viewport, but bloats mobile payloads with thousands of candidate scores and duplicates complex constraint code across TV, iOS, Android, and web. Having the client send its
gridbucket (4x7or4x4) so the server runs one unified algorithm — backed by a tiny client-side last-mile duplicate guard — captures the best of both worlds. - Fixed-order charts & editorial pins vs. optimizer freedom. Numbered charts (
"Top 10 Today") andContinue Watchingcarry semantic order, so they claim before Global Greedy runs. If a non-skippable"Top 10"row collides with the Hero billboard, demoting"Top 10"just below the fold preserves honest"#1, #2, #3"numbering at the cost of pushing that chart down one screen. - 5-minute page cache stability vs. instant freshness. Caching assembled pages per
(profile_id, device_class, grid_bucket)for 5 minutes stops the home grid from disorientingly reshuffling when a user clicks Back from a trailer, while event-driven cache invalidation updates the page immediately as soon as the user actually watches a show or editsMy List. - Server-side
page_sessionsvs. stateless signed cursors. Storingshown_show_idsin a 30-minute server session cache keeps scroll URLs tiny; embedding(page_version, snapshot_id)insidepage_idlets an expired session deterministically rebuild the shown set without bloating client requests.
Common mistakes
- Deduplicating on
video_idinstead of parentshow_id, allowing Season 1, Season 3, and a teaser trailer of the same show to appear together on the first screen. - Collapsing
video_id -> show_idafter slicing the topZcandidates, so a row with 30 episode/clip assets of one series shrinks to a single candidate instead of 29 distinct series. - Comparing uncalibrated raw scores across heterogeneous row models, letting an uncalibrated model outputting
0.0..10.0win every contested show against a calibrated model outputting0.0..0.3. - Running maturity, licensing, or theme filters after deduplication, allowing an adult-rated or unavailable title to block valid candidates and leave blank holes once stripped out (or worse, letting an editorial pin bypass Kids maturity filters).
- Silently skipping a duplicate inside a numbered
"Top 10"row, which either renders broken numbering ("#1, #2, #4") or falsely labels the#4show in the country as"#3". - Ignoring horizontal scroll inside above-the-fold rows, so swiping Row 1 to tile
#8slides in a show currently sitting right underneath in Row 2, tile#2. - Sharing page-cache keys across profiles or accounts, leaking one family member's private watch history to another user.
- Evaluating the A/B test by per-tile CTR or randomizing by profile instead of household account, confounding position shifts with user satisfaction and letting shared living-room TVs contaminate control and treatment groups.
Follow-up questions
- How would you suppress near-duplicates—such as sequels or spin-offs within the same franchise—without blocking high-intent titles when alternatives are weak? Add a softer second-level grouping key
franchise_idalongside the hardshow_iduniqueness rule. Keep hard deduplication onshow_id(<= 1per zone), and apply a multiplicative diversity discount (for example0.5x) to any candidate whosefranchise_idhas already been placed in the zone. Implement Global Greedy with a max-heap (priority queue) (a tree structure that pops the highest-weighted candidate inO(log N)time) instead of a static sorted list: whenever the popped candidate'sfranchise_idis already inused_franchises, multiply its weight by0.5and push it back into the heap once so genuine high-intent sequels can still appear when alternatives are weak, while close ties favor fresh franchises. - If product asks to extend deduplication across all 40 rows of the home screen rather than only the initial viewport, how does your strategy change? Keep strict zero-duplicate deduplication for the above-the-fold zone, and switch below-the-fold lazy batches (
GET /v1/home/rows) to best-effort deduplication with amin_itemsfloor. Initializeused_showsfrompage_sessions[page_id].shown_show_ids, run Global Greedy per 4-row scroll batch, and only allow repeating an earlier show from 20 rows up if a narrow theme row (like"Award-Winning Documentaries") would otherwise drop belowmin_items(while still enforcing strict uniqueness within each row and within each visible 4-row viewport window). Request6–8spare rows from the Page Ranker instead of2since deeper rows exhaust candidates much faster, and monitor lower-page play rates closely in A/B tests. - How do you make raw scores from independently trained row rankers comparable so cross-row conflict resolution stays fair? Train a lightweight post-processing calibration layer per row type that maps raw model scores to empirical
P(qualified_play | impression in row_type, position=0)using isotonic regression (a non-decreasing step-function curve fit) or Platt scaling (fitting a logistic sigmoid curve) on recent randomized or position-debiased impression logs. Validate calibration weekly with reliability curves (checking that tiles predicted at0.15actually convert at~15%in every row type) and automatically refit calibration whenever an upstream ranking model retrains, then multiply by row/cell attention weightw_iduring assignment.
Follow-up questions
- How would you suppress near-duplicates—such as sequels or spin-offs within the same franchise—without blocking high-intent titles when alternatives are weak?
- If product asks to extend deduplication across all 40 rows of the home screen rather than only the initial viewport, how does your strategy change?
- How do you make raw scores from independently trained row rankers comparable so cross-row conflict resolution stays fair?
Similar questions
- Architecting a Scalable React Video Playlist UI
- Crash-Safe Local File System
- Streaming Ad Frequency Limiter
- Incremental Directory Backup System
- Multi-Tenant GPU Cluster Scheduler for ML Workloads
- Design a Cluster Scheduler for ML Training, Batch Inference, and Evaluation
More Netflix interview questions
- Multi-Tenant GPU Cluster Scheduler for ML Workloads Medium
- Advertising Platform Data Schema Medium
- Rotating Media Queue With Dynamic Ratings and Thread Safety Medium Pro
- Count Active Closed Intervals at Query Points Medium Pro
- Netflix Recruiter Screen: Culture and Career Fit Medium Pro
- Probability, Regression Confounding, CLT, and Experiment Sizing Medium Pro
- Earliest Task Completion Schedule Hard Pro
- Estimating ITT, TOT, and Complier LATE Medium Pro
- Fastest Broadcast Arrival Times Across Nodes Easy Pro
- Subtree Value Totals in a Rooted Tree Hard Pro