Contents
Constraints
- 100M DAU, ~3 home loads/day each (~3.5k QPS average, ~15k peak)
- p99 latency budget ~200 ms
What to cover
Sketch your own design first. A complete answer has these parts; the notes say what each should settle.
- RequirementsDesign the system that picks and orders the shelves and cards on a listener’s home screen each time the app opens.
- Estimates100M DAU, ~3 home loads/day each (~3.5k QPS average, ~15k peak). Catalogue tens of millions of tracks, millions of podcast episodes, hundreds of candidate shelves per user. p99 latency budget ~200 ms.
- API
- Data model
- ArchitectureCandidate generation per shelf type: collaborative filtering or two-tower embeddings with ANN retrieval, recent-listening heuristics, editorial pools, new-release and podcast sources.; Ranking model scoring (user, shelf, card) with context (time, device).; Re-ranking for diversity and freshness, and business rules.; Explore/exploit layer (e.g. a contextual bandit over shelf slots and new content).; Feature store with batch user embeddings plus real-time session features; logging of impressions with positions.; Weekly or daily retraining pipeline with automated evaluation gates and an automatic push when a new model clears them.
- Deep dives
- Trade-offsbatch-precomputed vs real-time ranking (freshness vs cost); engagement vs long-term satisfaction and diversity; music vs podcast mix; exploration cost vs cold-start learning.
- EvaluationOffline: NDCG/recall@k on held-out future sessions, coverage, diversity.; Online: A/B on streams per session, retained listening days, minutes from Home.; Guardrails: skips within 30 s, latency, catalogue concentration.; Daily training/serving skew checks (data validation comparing training and serving feature distributions).
Reference design
One way to answer it, part by part. Open a part once you have your own version of it.
Requirements
Functional: on every app open, choose which shelves to show (“Jump back in”, “Made for you”, “New episodes”, genre and mood shelves, editorial, podcast recommendations), order them, and order the cards within each; adapt to context (time of day, device such as phone, car or TV, market); give each shelf a reason (“Because you listened to …”).
Non-functional and constraints
- p99 ≤ 200 ms server-side; a cached fallback home if ranking fails — the home screen must never be empty.
- Business rules: licensing availability by market, explicit-content settings, family and kids accounts, pinned editorial shelves, contractual podcast placements.
- Objective: not clicks. Primary success = listening that started from Home and that users keep (e.g. streams ≥ 30 s, saves, follows) plus long-term retention (listening days per month). Short-term engagement is balanced against satisfaction and diversity.
- Cold start for new users and new content (new releases, new podcast shows) is a first-class requirement.
- Assumptions to confirm: scale as given (100M DAU); music and podcasts share one home; mobile dominates traffic.
Estimates
CalculatorHow the 200 ms p99 budget splits across the home-screen pipeline
- Total p99
- 200 ms
Total p99 = Candidate fetch + Feature fetch + Ranking + Re-ranking and rules + Assembly + Headroom = 200 ms
| Case | Candidate fetch (ms) | Feature fetch (ms) | Ranking (ms) | Re-ranking and rules (ms) | Assembly (ms) | Headroom (ms) | Total p99 |
|---|---|---|---|---|---|---|---|
| Text budget | 40 | 30 | 50 | 10 | 20 | 50 | 200 ms |
CalculatorPeak inference capacity
- Peak inferences per second
- 4,200,000 inferences/s
- GPUs needed
- 21 GPUs
Peak inferences per second = Peak QPS × 1000 × Inferences per request = 4,200,000 inferences/s
GPUs needed = ceil(Peak inferences per second ÷ (Per-GPU throughput × 1000)) = 21 GPUs
| Case | Peak QPS (k QPS) | Inferences per request (inferences) | Per-GPU throughput (k inf/s) | Peak inferences per second | GPUs needed |
|---|---|---|---|---|---|
| Peak case | 15 | 280 | 200 | 4,200,000 inferences/s | 21 GPUs |
- Traffic: 100M DAU × 3 loads = 300M loads/day ÷ 86,400 ≈ 3.5k QPS, peak ~15k QPS (morning commute, evenings).
- Scoring work: ~200 candidate shelves per user plus the top ~10 cards of the ~8 visible shelves ≈ 280 model inferences per request → 15k × 280 ≈ 4.2M inferences/s at peak. Assuming a small multi-task MLP batched on one GPU sustains ~200k inferences/s: 4.2M ÷ 200k ≈ 21 GPUs, ~30 with headroom (or a larger CPU fleet).
- Batch candidates: top 20 cards for ~100 shelf types per user = 2,000 ids × 8 bytes ≈ 16 KB per user × 100M ≈ 1.6 TB, refreshed daily in a wide-column store.
- Embeddings: 100M users × 128 dims × 2 bytes ≈ 26 GB; ~50M tracks and episodes × 128 × 2 ≈ 13 GB — the item ANN index fits in memory per replica.
- Logging: ~30 impressions per load × 300M ≈ 9B impression rows/day × ~200 bytes ≈ 1.8 TB/day.
- Latency budget (p99 200 ms): candidate fetch in parallel 40 ms, feature fetch 30 ms, ranking 50 ms, re-ranking and rules 10 ms, assembly 20 ms, ~50 ms headroom for network and tail.
API
GET /v1/home?device=phone&locale=en-GB&tz=Europe/London&session_id=s_77
→ {request_id, ttl_s: 300,
shelves: [{shelf_id, type: "jump_back_in", title, reason, position,
cards: [{item_id, item_type: "track"|"album"|"playlist"|"episode"|"show",
artwork_url, reason}]}]}
POST /v1/events (batched from the client)
{request_id, events: [{type: "impression"|"play"|"skip"|"save"|"follow"|"scroll_depth",
shelf_id, item_id, shelf_position, card_position, ts, played_ms}]}
Internal:
CandidateSource.get(user_id, context, k) → [(item_id, source_score)]
Ranker.score(batch of (user, shelf, card, context) feature vectors) → {p_stream30, p_save, p_skip}
request_id ties every impression and outcome to the exact ranking decision, model version and logged propensity.
ttl_s lets the client re-show a cached home on rapid re-opens or when offline. Events are batched, delivered at least once and de-duplicated on (request_id, item_id, type), because they become training labels.
Data model
- UserProfile (batch, daily): long-term embedding, genre/artist/show affinities, listening aggregates by time of day and device, subscription tier, explicit filter, market.
- SessionState (real time): last N plays and skips, current context, shelves already seen this session.
- Item: track/album/playlist/episode/show metadata, embedding, popularity by market, release date, availability by market, explicit flag.
- ShelfDefinition: type, candidate source, title template, constraints, editorial owner, eligibility rules.
- BatchCandidates: (user, shelf type) → top 20 item ids with scores, generation date.
- ImpressionLog: request_id, user, shelf, item, positions, model version, exploration flag, propensity, feature snapshot reference.
- TrainingExample: impression joined with outcomes inside a window (stream ≥ 30 s, save, follow, skip < 30 s) and long-term labels (returned within 7 days).
Features logged at serving time are reused for training, which removes most training/serving skew by construction.
Architecture
Flow · 5 stepsServing path for a personalised home screen
- Open The app opens and the Home API hands the request to the orchestrator.
- Candidates and features Candidate sources run in parallel with a timeout; batch and real-time features are fetched.
- Rank The multi-task ranker scores (user, shelf, card, context) into p(stream ≥ 30 s), p(save) and p(skip).
- Re-rank and explore Diversity, freshness and business rules are applied, then the bandit explores shelf slots and logs propensities.
- Respond The response and impression log go back to the app; if ranking times out, the precomputed home is served instead.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Open | The app opens and the Home API hands the request to the orchestrator. |
| 2 | Candidates and features | Candidate sources run in parallel with a timeout; batch and real-time features are fetched. |
| 3 | Rank | The multi-task ranker scores (user, shelf, card, context) into p(stream ≥ 30 s), p(save) and p(skip). |
| 4 | Re-rank and explore | Diversity, freshness and business rules are applied, then the bandit explores shelf slots and logs propensities. |
| 5 | Respond | The response and impression log go back to the app; if ranking times out, the precomputed home is served instead. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| App | Input | every app open |
| Home API | Input | GET /v1/home |
| Home orchestrator | Compute | fans out in parallel |
| Candidate sources | Compute | two-tower ANN, recent listening, editorial |
| Feature store | Memory | batch embeddings + real-time session features |
| Ranker | Compute | multi-task MLP: p(stream), p(save), p(skip) |
| Re-ranker | Compute | diversity, freshness, business rules |
| Explore/exploit | Compute | contextual bandit over shelf slots |
| Precomputed home | Memory | nightly, served on timeout |
| Response + impression log | Output | request_id, ttl_s: 300 |
Source: This page's text
Flow · 4 stepsHow offline retraining and release work
- Log impressions Impressions are logged with positions, propensities and model version.
- Join labels Impressions are joined with outcomes inside a window, including long-term labels.
- Retrain and check skew The model is retrained daily or weekly while skew checks compare training and serving feature distributions.
- Gate and push Only models that beat the incumbent and pass skew checks reach the registry and are pushed automatically.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Log impressions | Impressions are logged with positions, propensities and model version. |
| 2 | Join labels | Impressions are joined with outcomes inside a window, including long-term labels. |
| 3 | Retrain and check skew | The model is retrained daily or weekly while skew checks compare training and serving feature distributions. |
| 4 | Gate and push | Only models that beat the incumbent and pass skew checks reach the registry and are pushed automatically. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| ImpressionLog | Data | request_id, positions, propensity |
| Label joins | Data | stream ≥ 30 s, save, follow, skip < 30 s |
| Retraining | Training | daily or weekly |
| Daily skew checks | Training | training vs serving feature distributions |
| Evaluation gates | Training | offline metrics beat incumbent |
| Registry | Release | |
| Automatic push | Release | when gates pass |
Source: This page's text
App ─► Home API ─► Home orchestrator
├─ Candidate sources (parallel, each with a timeout):
│ two-tower ANN (tracks, playlists, shows) · recent listening · new releases
│ from followed artists and shows · editorial pools · trending by market
├─ Features: batch user embeddings and aggregates (feature store, daily)
│ + real-time session features (stream processor)
├─ Ranker: multi-task model on (user, shelf, card, context)
│ → p(stream ≥ 30 s), p(save), p(skip) → weighted value score
├─ Re-ranker: diversity across shelves (genre, music/podcast mix), freshness,
│ de-duplicate cards across shelves, business rules and availability
├─ Explore/exploit: contextual bandit over shelf slots and new content,
│ logs propensities
└─ Response + impression log (request_id)
Offline: logs ─► label joins ─► daily/weekly retraining ─► evaluation gates
─► registry ─► automatic push when gates pass · daily skew checks
Fallback: precomputed home per user (nightly) served if ranking times outDeep dives
Cold start. New users: onboarding taste picks seed the user embedding; until history builds, use popularity by market, age band and device plus heavier exploration. New items: content embeddings (audio and text for podcasts, artist similarity for tracks) let the two-tower model retrieve them before interactions exist; the bandit gives them a guaranteed exploration budget, then performance decides.
Position bias and feedback loops. Top shelves get plays because they are on top. Log positions and propensities; train with position as a feature (set to a constant at serving) or reweight by inverse propensity; a small slice of randomised shelf order measures the bias directly. Without this the model only learns to repeat itself.
Long-term objective. Optimising p(stream) alone pushes familiar, repetitive content. The value score combines heads with weights tuned by online experiments against retained listening days; skips and “not interested” signals have negative weight.
Trade-offs
- Batch-precomputed vs real-time ranking: batch homes are cheap and robust but stale — they cannot react to what the user just played or to time of day. Real-time ranking costs a serving fleet but improves freshness; a hybrid (batch candidates, real-time ranking, batch fallback) gets most of the benefit.
- Engagement vs long-term satisfaction and diversity: chasing short-term plays narrows taste and inflates clickbait shelves; diversity constraints and long-term labels cost a little immediate engagement for retention.
- Music vs podcast mix: podcast sessions are longer and rarer, so raw probabilities are not comparable; calibrate heads and learn each user’s mix rather than fixing a quota, with a floor so podcasts get discovered.
- Exploration cost vs cold-start learning: exploration spends impressions on uncertain content; cap it (e.g. ~5% of slots), target it at new content, and measure its cost with the logged propensities.
Evaluation
- Offline: NDCG@k and recall@k on held-out future sessions (time-based split, never random); per-head log-loss and calibration; catalogue coverage and intra-home diversity; off-policy estimates using logged propensities for bandit changes.
- Online: A/B tests on streams per session from Home, minutes from Home and retained listening days (run long enough — 2–4 weeks — to see retention).
- Guardrails: skips within 30 s, “not interested” rate, p99 latency and fallback rate, catalogue concentration (share of streams going to the top 1% of items), podcast discovery rate.
- Training/serving skew: daily data validation comparing feature distributions in training data and serving logs; alerts on drift or missing features before a model is pushed.
- Release gates: automatic push only if offline metrics beat the incumbent by a margin and no slice (market, device, new users) regresses.
What a strong design shows
- Defines success as retained listening, not clicks, and builds a value score and guardrails around it.
- Uses a staged pipeline — candidate sources, multi-task ranker, diversity re-ranker, bandit — sized against the latency budget.
- Logs propensities and handles position bias, enabling off-policy evaluation.
- Has a concrete cold-start plan for users and new content.
- Validates offline on future sessions, A/B tests long enough to see retention, and checks training/serving skew daily.