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_id vs. season/trailer video_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 p99 latency 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

  1. 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 (Z cells): 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 uses 1 Hero billboard + 4 rows * 7 tiles = 29 cells, while mobile portrait uses 1 + 4 * 4 = 17 cells.
    • Deduplication key (show_id, not video_id): Season 1, Season 2, a teaser trailer, and a holiday special are different video_id assets that all belong to one parent show_id. Mapping video_id -> show_id ensures two seasons or clips of the same series never appear together in the zone.

    Functional requirements

    1. Every cell in the dedup zone displays a distinct show_id (no duplicates within a row or across rows).
    2. Enforce hard constraints without exception: profile maturity limits, country licensing windows, row theme rules ("Comedies" only shows comedies), fixed-order rows (Continue Watching by recency, numbered Top 10), and editorial pins.
    3. Maximize expected user engagement by placing contested shows into the row where they are most likely to trigger a play.
    4. Backfill rows that run short after deduplication (or swap in a spare row) so the user never sees blank holes.
    5. Support smooth vertical and horizontal lazy loading on scroll without revealing jarring duplicates.
    6. Log decisions and impressions cleanly to measure impact offline and in A/B tests.

    Non-functional requirements

    • Latency: Server p99 under 200 ms for 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.
  2. 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 raw
    

    Three design lessons follow immediately: 1. The dedup algorithm itself takes < 1 millisecond (~145 pairs), so network fan-out to fetch candidates and metadata dominates our 200 ms budget. 2. Row candidates must be precomputed offline/nearline; running heavy neural rankers over 3,000 items at 10,000 req/s (30M neural 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 KB for one profile read).

  3. 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_id binds subsequent vertical/horizontal scroll requests to the exact shown_show_ids already rendered on screen, and joins impression/play logs back to the exact page layout for A/B attribution.
    • grid lets the server size the dedup zone to the user's screen (rounding unfamiliar window sizes up to a small set of standard grid buckets like 4x7 or 4x4 so cache hit rates stay high).
  4. 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 min
    

    Personalization inputs (fed into offline/nearline row rankers and lightweight online re-scoring): viewing history and completion ratios, active Continue Watching progress, My List additions, thumbs ratings, recent search queries, impression fatigue (demoting titles shown repeatedly on prior home loads without a click), time of day, device class (tv vs mobile), country, and audio/subtitle preferences.

    Two modeling invariants make cross-row deduplication work properly: 1. Collapse video_id -> show_id per row first: After filtering illegal items, if a row contains both Season 1 (0.61) and Season 2 (0.74) of show_id = 55, keep only the highest-scoring legal asset (0.74) so every row's candidate list has strictly distinct show_ids before dedup begins. 2. Score calibration across models: Comparing a raw neural logit 3.8 from "Because You Watched" against a heuristic score 0.45 from "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).

  5. 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 Pipeline
    

    Running 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.

  6. Deep dive 1: Selecting and placing shows to maximize relevance

    Once fixed rows and pins claim their cells, we want to assign unique shows t to the remaining flexible zone rows i = 1..R (each needing s_i cells, with row visibility weight w_i estimated from how often users look at row i) 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` shows
    

    This 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 1 slot each and row weights w_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_i cells per row") form the intersection of two partition matroids (simple group-capacity constraints), which mathematically guarantees Global Greedy achieves at least 50% 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 ~145 edges to 100% optimality in < 1 ms, and also lets you assign per-cell weights w[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-Z Pigeonhole Pruning Rule (why we only inspect 29 candidates per row): Suppose the entire above-the-fold zone has Z = 29 cells total. Even if every single other cell on screen (<= 28 cells) took a show from Row i's top 29 distinct legal shows, at least 29 - 28 = 1 show inside Row i's top 29 is guaranteed to remain unused! Therefore, no optimal solution ever needs to reach past rank Z in any row (unless the row has fewer than Z candidates total), shrinking 40 * 75 = 3,000 candidates down to ~145 pairs with zero loss of quality.

  7. Deep dive 2: Conflict resolution, constraints, and backfill code

    Conflicts between product rules are resolved by a strict 6-step claim hierarchy:

    1. 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.
    2. 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 a show_id already claimed by the Hero or an earlier fixed row.
      • Non-skippable fixed rows (numbered "Top 10 Today", where skipping #2 would 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!
    3. Editorial pins claim next at their exact (row, position) coordinates; if a higher-priority fixed row already claimed that show_id, drop the pin and log a conflict warning for editors.
    4. Flexible personalized rows share remaining cells via Global Greedy over each row's top Z candidates.
    5. 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 the 2 spare rows from the Page Ranker and re-run steps 2–5.
    6. 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_ids
    

    Trace how assemble_first_screen resolves 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 claims X, P, Q in 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 slot 0. - 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 needs 1 more show, skips already-used "P", and backfills "F1" -> ["E", "W", "F1"]. Row 2's only fallback "X" is already used, so short_row_ids = ["because_watched"], signaling the Page Assembler to swap Row 2 with a spare row!

  8. 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_class and grid=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 p99 latency budget (200 ms total):

    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 ms
    

    Three-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 Watching and "Because You Watched..." within seconds of playback events. 2. Assembler in-process RAM cache (1 min TTL): Country availability maps, shows maturity 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 min TTL): Keyed strictly by (profile_id, device_class, grid_bucket) and invalidated immediately on playback, thumbs, or My List events. 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.

  9. Partial data fallbacks and scrolling (vertical and horizontal)

    Every external read uses a strict 60 ms timeout 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 page Instant 200, non-personal
    Continue Watching store slow Serve 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_id during Step 1 filtering (fail closed) Zero maturity leaks

    Scrolling below the fold and horizontally inside a row: - Vertical scroll (GET /v1/home/rows): Loads shown_show_ids from page_sessions[page_id] and runs the same dedup logic on the next 4 rows with used_shows pre-populated. Below the fold, cross-page dedup is relaxed to a soft constraint: if strict dedup would leave a genre row below min_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 out shown_show_ids from 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 min idle tab): Encode (page_version, pins_snapshot_id, grid_bucket) inside page_id and retain the previous page_version in the Candidate KV Store for ~35 minutes so the server can deterministically reconstruct the initial shown_show_ids on a cache miss (falling back to the client's defensive UI guard if that version aged out).

  10. Measuring impact, scaling, and trade-offs

    1. Offline replay validation (before touching live traffic) Replay logged production requests through the new assembler and verify: 0 zone 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 ms assembly 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 minutes of 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 weeks or a long-term holdout so novelty effects settle), time-to-first-play, and vertical/horizontal scroll depth. - Guardrail metrics: Server p99 latency, degraded fallback rate, Continue Watching resume rate, editorial pin play rate, and 0 client-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 ~145 pairs (only the top Z shows per row can ever matter by the pigeonhole principle), is deterministic and easy to explain to editors, and is guaranteed at least 50% of optimal via matroid intersection (combining the one-cell-per-show rule and s_i-cells-per-row rule). Min-Cost Max-Flow (an exact graph-flow solver) achieves 100% 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 and 2 spare 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 grid bucket (4x7 or 4x4) 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") and Continue Watching carry 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 edits My List.
  • Server-side page_sessions vs. stateless signed cursors. Storing shown_show_ids in a 30-minute server session cache keeps scroll URLs tiny; embedding (page_version, snapshot_id) inside page_id lets an expired session deterministically rebuild the shown set without bloating client requests.

Common mistakes

  • Deduplicating on video_id instead of parent show_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_id after slicing the top Z candidates, 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.0 win every contested show against a calibrated model outputting 0.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 #4 show in the country as "#3".
  • Ignoring horizontal scroll inside above-the-fold rows, so swiping Row 1 to tile #8 slides 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_id alongside the hard show_id uniqueness rule. Keep hard deduplication on show_id (<= 1 per zone), and apply a multiplicative diversity discount (for example 0.5x) to any candidate whose franchise_id has already been placed in the zone. Implement Global Greedy with a max-heap (priority queue) (a tree structure that pops the highest-weighted candidate in O(log N) time) instead of a static sorted list: whenever the popped candidate's franchise_id is already in used_franchises, multiply its weight by 0.5 and 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 a min_items floor. Initialize used_shows from page_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 below min_items (while still enforcing strict uniqueness within each row and within each visible 4-row viewport window). Request 6–8 spare rows from the Page Ranker instead of 2 since 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 at 0.15 actually convert at ~15% in every row type) and automatically refit calibration whenever an upstream ranking model retrains, then multiply by row/cell attention weight w_i during assignment.

Follow-up questions

Similar questions

More Netflix interview questions

All 97 Netflix questions →