Design a Homepage Recommendation System
Understanding the Problem
🏠 What is a homepage recommender? It's the system that fills the first screen of an app with personalized rows: "Continue watching" and "Because you watched Dark" on Netflix, "Inspired by your browsing" on an e-commerce site, "Order again" and "Fastest near you" in a food delivery app, "Made for you" mixes on Spotify. The page is a grid. Each row is a theme, each row holds ranked items, and the order of the rows is personalized too.
You'll get this question in several costumes, and it's one problem underneath:
- E-commerce home page: a catalog of tens or hundreds of millions of products, sparse purchase signals, a strong "buy again" pattern.
- Food delivery home feed: stores and restaurants instead of products. Only a few thousand stores are deliverable to any one address, and whether a store is open, how far away it is and how long delivery takes change by the minute.
- Netflix or Prime Video: tens of thousands of titles, slow-changing taste, and an objective (keep the subscription) that is measured over months.
- Spotify home: around a hundred million tracks, but the home page mostly shows playlists, albums and artists, and the strongest signal is whether people skip.
All four share the same structure: generate candidate rows, rank the items in each row, then decide which rows go on the page and in what order. We'll design the general system and cover what changes for each variant in the deep dives. The serving infrastructure (precomputed rows, caching, fallbacks) is covered in Design a Recommendation System; here we focus on the models.
Functional Requirements
Core Requirements
- The system should return a personalized home page: an ordered list of rows, each with an ordered list of items.
- The page should mix row types: resume or reorder rows, rows anchored on something the user did ("Because you bought a tent"), general personalized picks, and popular or new items.
- Every item shown must be available: in stock, licensed in the user's country, or open and deliverable to their address.
- New users and new items should get reasonable treatment.
Below the line (out of scope)
- Search results and the search ranker.
- Sponsored placements on the page (an ads auction; see Ads Ranking).
- Personalized artwork and thumbnails (we'll mention it briefly).
Non-Functional Requirements
Core Requirements
- 100 million daily active users, each loading the home page around 3 times a day: 300 million page loads a day, about 3,500 QPS on average, with peaks around 20,000 QPS (dinner time for delivery, evenings for streaming).
- The page should render with recommendations in under 300 ms at p99 on the server.
- Freshness varies by variant: a delivery feed must reflect the current time, location and store status; an e-commerce page should react to this session's browsing within minutes; a streaming page can be mostly computed overnight.
- The page must never be empty. If a model fails, serve less personal rows.
- Fairness across suppliers: small sellers, restaurants and artists should get some exposure, not just the top 1%.
Below the line (out of scope)
- Cross-region consistency of user history.
A typical page has around 15 rows of 20 items each, so we show up to 300 items per page load. At peak that's 20,000 × 300 = 6 million item slots per second to fill.
The math that matters most is how big the candidate set is per user, because it decides whether we need retrieval at all:
| Variant | Items per user | Can we score them all? |
|---|---|---|
| Food delivery | ~2,000 deliverable stores | Yes, with a good model |
| Streaming video | ~10,000–50,000 titles in the region | Yes, offline; not online with a heavy model |
| E-commerce | ~100M+ products | No, need retrieval |
| Music | ~100M tracks, millions of playlists | No, need retrieval |
At about 10 µs per item for a mid-size model, scoring 2,000 stores is 20 ms (fine online), scoring 30,000 titles is 300 ms (fine in a nightly batch, too slow at 20,000 QPS) and scoring 100 million products is 1,000 seconds (never).
Saying "it depends on the catalog size per user" and then running these numbers is a strong opening. It shows you won't bolt an ANN index onto a problem that has 2,000 candidates, and you won't try to score 100 million products online either.
Framing It as an ML Problem
ML Objective
The business metrics differ by variant:
- E-commerce: purchases and revenue (GMV) per visit, and long-term repeat purchase.
- Food delivery: orders per session and order conversion, while keeping delivery times and cancellations in check.
- Streaming: hours watched, and ultimately subscriber retention.
- Music: listening time, saves and follows, low skip rate, retention.
None of these can be the training label directly: retention is months away, and revenue is noisy. We train on per-impression outcomes that roll up to them:
- P(click) or P(play) for every item on the page.
- P(purchase | click), P(order | store visit), or P(play ≥ 30 s) and P(completion) for conversion and satisfaction.
- Negative outcomes: P(skip) for music, P(cancel) or P(return) for orders.
And we combine them per item into an expected value:
e-commerce: value = P(click) · P(purchase | click) · margin_weight
delivery: value = P(click) · P(order | click) − λ · P(late or cancel)
streaming: value = P(play) · E[minutes | play] · completion_bonus
music: value = P(play) · (1 − P(skip < 30 s)) · E[listen time]
The value of a whole page is the sum of the item values weighted by how likely each slot is to be seen. That last part, slot visibility, is what makes the home page different from a single ranked list.
Inputs and Outputs
- Input: user ID, request context (time, device, location or delivery address, country), and the catalog of available items.
- Output: a page: an ordered list of rows, each with a title, an explanation where relevant ("Because you watched Dark") and an ordered list of items. Plus a request ID for logging.
Choosing the ML Approach
We split the problem into three parts:
- Row generation (candidate generation): each row type is a generator that produces a themed candidate list. "Because you bought X" is item-to-item similarity from X. "Top picks" is two-tower retrieval. "Order again" is the user's own history.
- Item ranking: one shared ranking model scores every candidate in every row for this user and context.
- Page assembly: choose which rows to show, in what order, and remove duplicates across rows.
This is a learning-to-rank problem with pointwise multi-task predictions at the item level, and a separate (smaller) decision at the row level. Treating the page as one flat list would be simpler, but users read home pages row by row, and themed rows with explanations are a big part of why people trust them.
Data and Labels
Sources
- Impressions: which items were actually visible, logged from the client viewport (an item counts as seen after, say, 50% of it is on screen for a second). Items in a row the user never scrolled to are not negatives; they were never seen.
- Engagement: clicks, add-to-cart, purchases; store visits and orders; plays, minutes watched, completions; track plays, skips, saves.
- Catalog: product categories, prices, stock; store cuisine, menu, hours, delivery radius, ratings; title genres, cast, release date, availability by country; track audio features, artist, genre.
- Context: time, device (TV, phone, web), location.
How labels are produced
Clicks and plays are immediate implicit labels. Conversions are delayed: a purchase can come days after a click, after the user compared prices elsewhere. We join outcomes to impressions with an attribution window (for example 7 days for e-commerce, the same session for delivery) and accept that a model trained today has incomplete labels for the last few days. A common fix is to train on data that's at least one window old for the conversion head, and fresher data for the click head.
Explicit labels exist but are sparse: thumbs up/down, star ratings, "not interested". They're valuable as features and as evaluation data, and they should override implicit signals (a thumbs-down title must not come back next week just because the user hovered over it).
Class imbalance. Click rates on home-page items are low, often a few percent, and purchase rates per impression are far lower. We downsample negative impressions (keeping, say, 10%) and correct the predictions back afterwards.
Label leakage. Common traps:
- A feature like "user's total purchases in this category" computed over the whole day includes the purchase you're trying to predict. Use point-in-time features, as of the impression timestamp.
- "Continue watching" rows have near-certain clicks. If they're in the training data unmarked, the model learns that "item is in progress" means "click" and scores everything else too low. Add row type as a feature or train those rows separately.
Position bias is huge on a 2D page. The first two or three items of the top rows get most of the clicks no matter what's in them. If you train on raw clicks without accounting for that, the model mostly learns to predict where things were placed. We'll come back to this in the deep dives.
Feature Engineering
User features
- History embeddings: an average (or attention-weighted sum) of embeddings of recently purchased, ordered, watched or played items.
- Category, cuisine, genre and artist affinities over 7 and 90 days.
- Price sensitivity (average spend, share of discounted purchases), dietary preferences inferred from orders.
- Tenure, subscription tier, device mix.
Item features
- ID embedding (learned), category or genre, price, rating, popularity over several windows.
- Content embeddings: product title and image embeddings, menu text embeddings for stores, synopsis and artwork embeddings for titles, audio embeddings for tracks. These are what make cold start work.
- Delivery: store distance, estimated delivery time, delivery fee, current busyness, rating, open status.
Context features
- Time of day and day of week (breakfast vs dinner for delivery, weekday evening vs Sunday afternoon for streaming), device (TV sessions are long-form, phone sessions are short), weather (rainy evenings increase delivery orders and comfort food), location.
- Session features: what the user clicked or searched in the last few minutes.
Cross features
- User × item history: has the user bought, ordered from or watched this before, and how recently? For delivery, "ordered from this store 3 times" is the strongest single feature on the page.
- User × category affinity for the item's category.
- Similarity between the item's content embedding and the user's history embedding.
- Row × user: how often this user engages with this row type.
Real-time vs batch
- Batch (daily, Spark): affinities, history embeddings, item popularity, content embeddings.
- Near real-time (Flink, seconds to minutes): session clicks, store busyness and ETA, stock levels, trending items.
Everything is served from a feature store with point-in-time training data generation; see Feature Store.
Modeling
Row Generation
Each row type is a candidate generator, and most of them are simple:
- Resume rows ("Continue watching", "Order again", "Buy again"): the user's own history, filtered to items that are resumable or replenishable. Buy-again needs a model of repurchase timing: coffee beans every 3 weeks, a TV never.
- Anchored rows ("Because you bought a tent"): item-to-item neighbors of a recent anchor item, from co-purchase statistics or embedding similarity. Pick anchors that are recent and that the user engaged strongly with.
- Personalized picks: two-tower retrieval over the whole catalog (needed for e-commerce and music; for delivery, just score every deliverable store).
- Popular and new: popular in your region, new arrivals, trending. Cheap, and they keep the page from becoming an echo chamber.
A generator proposes more items than the row can hold (say 50 for a 20-item row), so the ranker has room to choose.
Item Ranking
Bad Solution: Popularity Per Segment
Approach
Rank each row's candidates by popularity within the user's segment (country, age bracket, device).
Challenges
Everyone in a segment sees the same page. It ignores what this user has bought or watched, and it rewards items that are already popular. Good enough as a fallback and for logged-out users; not a recommender.
Good Solution: Collaborative Filtering Plus a GBDT Ranker
Approach
Use matrix factorization (ALS on the implicit user × item matrix) for user and item embeddings, then train a GBDT ranker (LightGBM with a LambdaMART objective, or XGBoost on a click label) on a few hundred features: the MF dot product, history and affinity features, item stats, context.
Challenges
This is a strong baseline and, for food delivery, often hard to beat: the candidate set is small, the features (distance, ETA, past orders, cuisine affinity) are crisp, and GBDTs handle them well. It struggles with sequences (what the user did in the last ten minutes, in order), with raw content embeddings, and with sharing learning across several labels.
Great Solution: Multi-Task Deep Ranker
Approach
A deep ranker that takes sparse IDs, embeddings, sequences and dense features, and predicts several outcomes at once:
- Feature interaction layers: Wide & Deep, DCN-v2 or DLRM-style dot-product interactions between embedding vectors, so the model learns crosses like "this user × this cuisine at dinner time" without hand-building them.
- Session sequence: attention over the user's last 50 to 100 actions, with the candidate as the query.
- Multi-task heads: P(click), P(conversion | click), P(negative outcome). The conversion head is trained on clicked impressions only, which is a biased sample. The fix is to train P(click and convert) on all impressions as P(click) × P(convert | click), so both heads learn from the full impression space; this is the idea behind ESMM.
Challenges
More infrastructure (GPU or optimized CPU inference, embedding tables), harder to debug than trees, and it needs real volume to beat a tuned GBDT. Calibration matters because the value formula multiplies probabilities: if P(click) is overestimated by 30% in one country, that country's page is miscomputed.
Page Assembly
Once every item in every candidate row has a value, we pick and order the rows.
Bad Solution: Fixed Row Order
Approach
A product manager sets the row order: Continue watching, Top picks, Trending, then genre rows.
Challenges
A user who only watches documentaries sees a "Comedies" row in slot 4 every day. Nothing learns.
Good Solution: Score Rows by Their Items, Greedily
Approach
Score each row by the sum of its top items' values, discounted by item position in the row. Then fill the page greedily: pick the best row, remove its items from all other rows (so the same title isn't in three rows), re-score the remaining rows and repeat.
Challenges
Better, but the rows all end up looking alike: the top five rows are all "things like the one show you binged last week." It also ignores that users engage with rows as rows: some people always scroll to "New releases" regardless of what's in it.
Great Solution: A Row-Level Model With Diversity
Approach
Train a separate row model that predicts engagement with a row at a given slot, using the row type, its top item values, the user's history with that row type, and what's already above it on the page. Assemble greedily with this model, adding a diversity penalty for rows too similar to the ones already placed (by genre or category mix), plus a few hard rules: resume rows near the top, a cap on how many rows can be "Because you watched X" for the same X.
Challenges
The row model's labels are thin (one row impression per slot per page load) and heavily position-biased. A little exploration in row order, such as occasionally swapping two adjacent rows, gives the unbiased data it needs. The page is now the output of two models and a rule set, so log enough to explain why any given row landed where it did.
Training
Losses. Binary cross-entropy for each head, with per-task weights. For a GBDT ranker, LambdaMART optimizes NDCG directly by weighting pairwise swaps by how much they'd change NDCG.
Negatives. For the ranker: visible, unclicked impressions. For two-tower retrieval: in-batch negatives with a logQ correction for item popularity, plus random catalog negatives. Don't use unseen items as ranker negatives; the user may have loved them if they'd scrolled.
Position. Add the item's slot (row index, column index) as a training feature and set it to a fixed default at serving time, or train a separate position model and divide its effect out. Both are covered in the deep dives.
Retraining cadence. Daily retraining is enough for most variants because tastes change slowly and the fast signals come in through real-time features. Delivery benefits from more frequent updates around meal peaks, and new item embeddings need to be added daily so new products and titles aren't stuck with untrained IDs.
Scale. Training data is around 300M page loads × ~50 visible items, so ~15 billion impressions a day before downsampling. After keeping all positives and ~10% of negatives, a day of data is on the order of a couple of billion rows, comfortably trainable on a handful of GPUs with sharded embeddings.
Evaluation
Offline Metrics
- Item ranking: AUC and log loss per head, NDCG@K and recall@K per row on held-out impressions, all on a time-based split.
- Calibration per country, device and row type.
- Page-level: replay the logged pages and compute the expected value of the page the new model would have built. Logged data only has outcomes for what was shown, so use inverse propensity scoring with logged slot probabilities, or limit it to rows and items both models would have shown.
- Coverage and diversity: share of catalog shown, share of exposure to the long tail and small suppliers, genre entropy per page.
Beware offline metrics that reward the model for predicting position. If AUC jumps after you add the position feature, that's position bias being explained, not better recommendations. Evaluate with the position feature fixed.
Online Metrics and A/B Testing
- Primary: purchases or orders per visitor, GMV per visitor; streaming hours per member; listening time per user.
- Secondary: home-page click-through, time to first click (did they find something fast?), share of sessions that start from the home page rather than search.
- Guardrails: page latency, delivery time and cancellation rate, return rate, supplier concentration, unsubscribes.
- Long-term: retention and subscription churn, which need weeks of testing and a long-term holdout.
Interleaving is a useful complement for ranking changes: show one user a list that interleaves items from model A and model B and see which model's items get clicked. It detects ranking differences with far less traffic than a normal A/B test, then the A/B test confirms the business impact.
Serving
We use a hybrid of batch and online prediction, and the mix depends on the variant:
- Batch: a nightly job scores the whole regional catalog for every active user (cheap for 10,000–50,000 titles) and stores the top few hundred candidates per row type. This is the streaming default and the fallback for everyone.
- Online: at request time, row generators pull from the precomputed lists and the ANN index, then the ranker rescores the candidates with real-time context features (time, device, session). For delivery, the whole page is online: the candidate set depends on the current address and which stores are open right now.
A latency budget for a 300 ms p99:
| Step | Budget |
|---|---|
| Load user features and precomputed rows | ~20 ms |
| Row generators in parallel (ANN, item-to-item, history) | ~40 ms |
| Availability filter (stock, licensing, open and deliverable) | ~15 ms |
| Fetch item features (batched) | ~30 ms |
| Rank ~1,500 items (30 rows × 50) | ~60 ms |
| Page assembly with row model | ~20 ms |
| Serialization, network, slack | the rest |
Caching helps a lot: the per-user precomputed rows are a cache by design, item features for popular items are cached in-process, and for logged-out users the whole page can be cached per country and device.
Potential Deep Dives
1) How do we deal with position bias on a 2D page?
Users scan the top-left first and read fewer items the further down and right they go. An item in row 1, slot 1 gets several times the clicks of the same item in row 6, slot 8. If we train on raw clicks, the model learns "items we already put at the top get clicked," and keeps putting them there.
Bad Solution: Ignore It
Approach
Train on raw clicks.
Challenges
The model reinforces its own past rankings. New items placed low never get clicks, so they never move up.
Good Solution: Position as a Training Feature
Approach
Add row index and column index as features during training. At serving time, set them to a fixed value (say row 1, column 1) for every candidate, so all candidates are compared as if they were in the same spot.
Challenges
Simple and widely used, but it assumes position and relevance don't interact, and the position feature can soak up some real relevance signal (good items were placed higher, after all).
Great Solution: A Separate Position Model and Randomized Data
Approach
Train a small, shallow position tower that takes only position and context (device, row type) and add its output to the main model's logit during training. At serving time, drop it. Because it's shallow and only sees position, it can only learn the position effect, and the main model learns relevance. Estimate the true position curve from a small amount of randomized traffic: for a tiny slice of page loads, shuffle the top few items within a row and measure how clicks change with position alone.
Challenges
The randomized slice costs a bit of engagement, so keep it small. The position curve differs by device (TV rows show 5 items, phone rows show 2.5), so model it per device.
2) How do we handle new users, new items and new suppliers?
- New users: fall back to popular-in-region and editorial rows, ask for a few preferences at sign-up (genres, cuisines, artists), and use context: device, location, time, the referral link they came in on. Rows like "Popular near you" carry the page until we have a few interactions, and session features make the second page load already better than the first.
- New items: content embeddings (product title and image, menu text, synopsis, audio) put a new item near similar existing ones, so the two-tower model and item-to-item rows can recommend it on day one. Reserve a small exploration share of slots in personalized rows for new items, and promote the ones that perform.
- New suppliers (a new restaurant, a small seller): the same exploration slots, plus a boost that decays over the first few weeks. Marketplaces need this explicitly, because a supplier with no orders gets no exposure and leaves.
3) What changes for food delivery?
Delivery breaks a few assumptions:
- The candidate set is the address. Only stores whose delivery radius covers the user's location and that are open now are eligible. That's a geo filter (see Proximity Service), recomputed every request, not something we can precompute nightly.
- Real-time features dominate. Estimated delivery time, current prep time and store busyness change minute to minute and strongly affect conversion. They come from a streaming pipeline (see ETA Prediction).
- Time of day changes intent. Breakfast, lunch and late-night orders look nothing alike. Time features, and often separate row generators per meal period, matter more than in other variants.
- It's a three-sided marketplace. Pushing every user to the fastest popular store overloads it, delivery times climb and orders cancel. The value formula should include P(late or cancel), and we may cap how many top slots one store gets in a region during peak.
- Small candidate set, rich features. A GBDT or a compact deep model scoring all ~2,000 stores online is usually the right call. No ANN index needed.
4) What changes for streaming video and music?
Streaming video has a small catalog and slow taste changes, so almost everything is precomputed overnight and rescored lightly online with device and time. The hard part is the objective: one play is a weak signal, and what the business cares about is whether a member keeps the subscription. Teams use proxies like "watched at least two episodes" or "completed," and weight them by how predictive they've been of retention. Because titles are few and appear in many rows, dedupe across rows and explanations ("Because you watched X") matter more. Artwork personalization (choosing which image to show for each title per user) is often a contextual bandit on top of the page; mention it if you have time.
Music home pages recommend containers (playlists, albums, artists, podcasts) as well as tracks, so there's a candidate generator per container type and a ranker that handles mixed types. The best negative signal is a skip within 30 seconds. Session context is strong: a morning commute and a Friday night want different shelves. Audio embeddings (from a model over spectrograms) solve cold start for new tracks, which matters because tens of thousands of tracks are uploaded every day. "Made for you" mixes are usually generated offline weekly, with a sequence model ordering tracks so transitions sound right.
5) How do we stop the home page from narrowing over time?
Every row trained on engagement favors what the user already engages with, so the page tends to collapse onto one interest. Counter it with exploration slots, diversity penalties in page assembly, a minimum number of non-personalized discovery rows, and guardrail metrics on genre and category spread per user. Measure it over weeks, because a narrow page can look great in a one-week A/B test and hurt retention over a quarter.
What is Expected at Each Level?
Mid-level
You should split the page into candidate generation and ranking, choose sensible labels (clicks, purchases or plays, with negatives from visible impressions only), propose a GBDT baseline with user, item and context features, and evaluate with AUC and NDCG on a time-based split. With prompting, you should handle cold start with popularity and content features and recognize that availability filtering is required.
Senior
You should handle the page as rows: row generators, an item ranker and page assembly with dedupe across rows. Expect to discuss delayed conversion labels and attribution windows, position bias on a 2D grid with a concrete correction, multi-task ranking with an expected-value formula, and which variants need retrieval (e-commerce, music) versus scoring everything (delivery). You should design a batch-plus-online serving split with a latency budget.
Staff+
You should drive the conversation toward the objective: how per-item proxies relate to retention or marketplace health, who owns the value weights, and how to measure long-term effects with holdouts and interleaving. Expect to discuss multi-stakeholder trade-offs (supplier exposure, delivery capacity), counterfactual page evaluation, exploration budgets, and how the design changes across the four variants. Knowing that a tuned GBDT is often the right answer for delivery is a strong signal.