Grokking the AI System Design Interview
Vote

0% completed

​

Design a Recommendation System

Frame the Problem: The Scale Is the Design

Define Success: Online Truth, Offline Proxies

Map the Data: Impressions Are the Labels

Pick the Model: One Model Per Funnel Stage

The Serving Path: A Funnel That Ends in Rules

Deep dive: cold start, both kinds

Keep It Working: The Loop and Its Traps

Count the Costs: Precompute Heavy, Serve Cheap

In the Interview

Common Mistakes

Same Design, Other Questions

TL;DR

Frame the Problem: The Scale Is the Design

The question: "Design a recommendation system for a video platform."

Start with scale and latency requirements. They help determine which designs are practical.

For this example, assume 50 million videos and 100 million daily users. The homepage should load in about 200 ms and display about 20 videos.

Running a detailed ranking model on all 50 million videos for every request would exceed this latency and cost budget.

A common solution is a funnel: a sequence of stages that reduces the number of candidates.

Each stage processes fewer items, so later stages can spend more computation on each item.

This design uses three stages. A cheap stage narrows millions down to hundreds. An expensive stage ranks those hundreds. A last stage applies business rules.

Say this framing out loud early. This is a prediction problem. The shape is a ranking funnel. You are designing the homepage feed, and search and notifications are out of scope.

Define Success: Online Truth, Offline Proxies

Success gets measured at two levels, per the framework.

What the business actually cares about, measured online. Do people come back? That is the daily return rate. Do they watch more? That is watch time per session.

These are product goals. Historical data helps estimate them, while controlled online experiments measure how a change affects users.

What you can train on. Engagement per impression provides faster feedback than long-term retention. Use it as a training signal, while checking whether it supports the product goals.

An impression is one item shown to one user, one time. Did they click it? Did they finish the video? These signals arrive within minutes, so a model can learn from them.

What you check before shipping, offline. Before anything goes live, you score it on held-out data. Two numbers matter.

Recall@K grades retrieval. Of the items the user actually engaged with, how many made it into the top K candidates?

AUC, or a ranking loss, grades the ranker. How often does it score a good item above a bad one?

Explain how these measures work together. Offline tests help select models for online evaluation. A launch also needs acceptable product metrics, safety checks, latency, and cost.

One constraint comes straight from the frame: about 200 ms for the whole page. That caps how much model work the request path can afford. Step 7 does the full cost story.

Map the Data: Impressions Are the Labels

You have three kinds of data. Interaction logs, catalog content, and signup signals.

Interaction logs provide training labels. Record impressions, model versions, allowed ranking features, and timestamped outcomes. Apply the product's privacy and retention requirements.

Join impressions with outcomes using stable identifiers and a defined observation window. Engagement can provide a positive label. A skipped item is a weaker negative signal: the user may not have noticed it.

These events can arrive quickly and in large numbers, but joining them correctly and interpreting missing events still require care.

But they have two flaws, and naming them now is worth doing.

1. Interaction labels cover exposed items. The model may generalize to other items, but their outcomes are not directly observed.

2. They carry the bias of the slot they appeared in. An item shown first looks better than it really is.

Step 6 returns to both.

Catalog content and signup signals cover what the logs cannot: brand-new users and brand-new items. The cold-start deep dive in step 5 uses these.

Set freshness targets by feature. Some stable item features can refresh nightly. New uploads, availability, and the user's short-term interests may need updates during the session.

Pick the Model: One Model Per Funnel Stage

Different stages can use different models. Start with a simple baseline, then add complexity where measured quality gains justify the cost.

Candidate generation runs three cheap sources at the same time. Here is each one, and why it is there.

1. Collaborative filtering with embeddings. The main source. A two-tower model learns a short vector for each user and each item.

Training places the vectors so that a user sits close to the items they engage with, which turns similarity into a distance you can measure. Step 5 covers how this gets served.

2. Co-occurrence. "People who watched X also watched Y." These are item-to-item lists computed ahead of time, looked up by the user's recent watches. Cheap, easy to explain, and surprisingly strong.

3. Non-personalized sources. Trending now, new uploads, popular in the user's region. These serve brand-new users and keep the feed fresh.

Three cheap candidate sources running at the same time.
Three cheap candidate sources running at the same time.

The ranker. By now the list is small, so you can afford rich features. The user's full history, item statistics, user-item combinations, and context like device and hour.

It predicts the engagement events you defined in step 2. Most of your modeling effort goes here.

If the interviewer asks for a baseline, give the simple answer. "Most popular plus recent" is the simplest thing that works. Everything above is the upgrade path from there.

The Serving Path: A Funnel That Ends in Rules

Example candidate counts and latency targets for the recommendation pipeline.
Example candidate counts and latency targets for the recommendation pipeline.

Stage 1: candidate generation. 50 million down to about 500. The three sources run at the same time, and you merge their results.

Compute item vectors in advance and load them into an approximate nearest neighbor (ANN) index. An index such as HNSW searches efficiently without comparing the user vector with every item. Choose the index using recall, memory, update, and latency measurements.

Approximate retrieval can miss relevant items. Measure this loss and choose a recall target that meets the product's needs.

At request time you grab the user's vector and pull the nearest few hundred items in a few milliseconds. That is how "50 million to 500" is even possible.

Stage 2: ranking. About 500 down to about 50. Score the candidates in one batched call. A 20 to 40 ms model budget is an example target, not a guarantee; test it with the chosen model, hardware, and concurrent load.

Stage 3: re-ranking. Business judgment on top. The score-ordered list is not what goes on screen yet. About 20 items survive to the page.

First the rules apply:

  • diversity, so not 20 videos from one channel,
  • freshness boosts,
  • policy demotions,
  • dropping items you just showed the user,
  • editorial pins.

Keep mandatory rules separate from learned scores so policy changes do not always require retraining. A learned re-ranker can also improve diversity. Apply eligibility checks early and recheck changing restrictions before display.

Each stage is also judged on its own job. Retrieval is judged on recall. Ranking is judged on precision near the top.

Deep dive: cold start, both kinds

Cold start means the system has no history to work with. It comes in two forms, and the interviewer will ask about both. Bring them up first.

A new user. Without interaction history, some personalized sources have limited information. Declared interests and session context can still help.

Fall back to popularity and regional trends. Use whatever the signup gave you: language, declared interests, platform.

Then use that first session to learn quickly. Weight their early clicks heavily, and update their state during the session rather than overnight.

A new item. Without engagement history, interaction-only retrieval has limited information about it.

Use content features instead: title, tags, and audio and visual embeddings. The item can then enter the candidate pool by looking similar to items that are already established.

Add a small exploration boost, since controlled exploration can reduce exposure bias. Without a new-item discovery mechanism, established videos may receive most of the exposure.

Keep It Working: The Loop and Its Traps

An example update schedule has three speeds; validate these intervals against freshness needs:

  • Retrain the ranker every day.
  • Rebuild item embeddings and the ANN index nightly, with quick incremental updates for new items.
  • Update each user's short-term state during their session, through the streaming path.

Now the two traps. This is the tricky part of the whole design, and interviewers know it, so raise them yourself.

The two training traps, and the fix for each.
The two training traps, and the fix for each.

Position bias. Items near the top are more likely to be seen and clicked. Click counts therefore reflect both placement and relevance.

Training directly on these clicks can reinforce the previous ranking rather than improve relevance.

One approach explicitly models how position affects examination, separately from relevance. Another uses inverse propensity weighting: examples are weighted using the estimated probability that an item was examined or exposed. Reliable estimates and controls on large weights matter. Simply adding position as a feature and setting it to zero at serving time does not guarantee unbiased scores.

The proxy trap. A proxy is a stand-in metric, one you optimize because the real goal is too slow to measure.

Optimizing clicks alone can favor misleading titles. Optimizing watch time alone can favor unnecessarily long videos.

The mature answer is to weigh several objectives at once, and to admit that long-term retention needs a sufficiently long evaluation window. This is a preview of feed ranking, where the objectives multiply.

Count the Costs: Precompute Heavy, Serve Cheap

The design moves substantial computation offline, but both batch processing and online serving contribute to cost.

Batch jobs compute and index item vectors in advance. Incremental updates can avoid recomputing unchanged items. This reduces request-time work at the cost of storage and background processing.

Each request pays for retrieval, feature lookups, ranking, rules, and data transfer. Limiting the expensive ranker to about 500 candidates helps control this cost.

Plan fallbacks for component failures:

  • If the index build fails, use the last validated index within a defined age limit. Continue enforcing current availability and policy restrictions.
  • If the ranker times out, use a tested fallback such as candidate order or trending items, with the same required filters.

Monitor index age, fallback rate, latency, quality, and user-visible errors. Fallbacks reduce failures but do not guarantee that every request succeeds.

💡 Raw item vectors require 50M x 128 x 4 bytes = 25.6 GB. This excludes index structures, identifiers, metadata, replicas, and runtime memory. Estimate those separately before choosing the number of machines.

In the Interview

The 30-second answer: "It is a three-stage funnel. First, candidate generation cuts 50 million videos down to about 500. It uses a few cheap sources in parallel. A two-tower embedding model served from an ANN index. Item-to-item co-occurrence. And a trending-plus-new source for cold start and freshness. Second, a feature-rich ranker scores those 500 for predicted engagement in one batched call. Third, a rule layer adds diversity, freshness, and policy before anything appears on screen. I log every impression and its outcome, retrain the ranker daily, refresh embeddings nightly, and correct for position bias during training. Offline recall and AUC decide which models get an A/B test. Long-term engagement decides what actually ships."

Likely follow-ups:

  1. "Why not one model end to end?" Cost and latency. No model good enough to rank well is cheap enough to run 50 million times on every request. The funnel is the compromise. And each stage gets judged on its own job: retrieval on recall, ranking on precision at the top.
  2. "Recall looks fine, but users seem bored. Where do you look?" Inspect the re-rank layer, objective, and retrieval performance by user group. Maybe diversity collapsed and every candidate comes from one taste cluster. Or your stand-in metric is favoring short-term clicks too much. Break watch time down by content category over time and look for it narrowing. Investigate feedback effects, segment-level retrieval quality, and model behavior.
  3. "How do you do real-time personalization?" Session events stream into the user's short-term features within seconds. The user embedding gets a quick in-session update, or a fast recency-weighted stand-in. Full retraining stays nightly. Two tiers of freshness, and you pay for each.
  4. "Your nightly embedding build fails. What do users see?" Usually a slightly older set of recommendations, if the fallback works. The ANN replicas keep serving yesterday's index. New items lean on content features and the trending source. An alert fires on index age. A second failure in a row starts to hurt new-item discovery, so the alert severity should rise with staleness.
  5. "Someone proposes a new candidate source. How do you decide whether to include it?" Measure its marginal value, not its standalone recall. What share of engaged impressions came from candidates only this source found? Run it in shadow first, then a small A/B. A source that only finds what the two-tower already returns adds latency without improving results.

Common Mistakes

  • Weak: starts by picking a model architecture. Strong: starts with 50 million items against a 200 ms budget, which forces the funnel before any model gets named.
  • Weak: treats clicks as the plain truth. Strong: brings up position bias unprompted and offers a fix (an explicit position-bias model or validated propensity weighting).
  • Weak: buries diversity and policy inside the ranking model. Strong: keeps re-ranking as a separate rule layer, so product teams can change rules without retraining.
  • Weak: waits to be asked about cold start. Strong: brings up both kinds, with different fixes for new users (popularity plus in-session learning) and new items (content features plus exploration).

Same Design, Other Questions

  • "Design 'customers also bought' for an online store." What changes: co-occurrence becomes the main source, and purchases replace watch time as the label (rarer, but cleaner). The funnel, the cold start, and the bias story are all the same.
  • "Design podcast discovery for an audio app." What changes: episodes are long, so "did they finish it" labels are slow and weak. Content embeddings from the audio and transcript now do more of the retrieval work, and the new-item path dominates because new episodes ship every week.

TL;DR

ShapeFunnel: multi-source retrieval (~500), then feature-rich ranking (~50), then rule re-rank (screen).
Main retrieval methodTwo-tower embeddings in an ANN index; plus co-occurrence and trending sources.
Cold startNew user: popularity + in-session learning. New item: content features + exploration.
Training trapsPosition bias (bias modeling or propensity weighting); clickbait proxy trap (multi-objective).
MetricsOffline recall/AUC gate experiments; online watch time and retention decide.
Cost shapePrecompute heavy, serve cheap: batch jobs fall back to yesterday's index; 25.6 GB of raw vectors, plus index overhead and replicas.
General
Test Your Knowledge
Check your understanding and reinforce the key concepts covered in this section with a short, targeted assessment.
9 Questions
~14 mins
Your progress is saved automatically

Reading Progress

0%


Vote for new content

On This Page

Frame the Problem: The Scale Is the Design

Define Success: Online Truth, Offline Proxies

Map the Data: Impressions Are the Labels

Pick the Model: One Model Per Funnel Stage

The Serving Path: A Funnel That Ends in Rules

Deep dive: cold start, both kinds

Keep It Working: The Loop and Its Traps

Count the Costs: Precompute Heavy, Serve Cheap

In the Interview

Common Mistakes

Same Design, Other Questions

TL;DR