Recommendation, Ranking, and Personalization Questions
Systems that select and order items for users. Covers candidate generation and ranking (two-stage retrieval, embedding-based retrieval with two-tower models and approximate nearest-neighbour candidate lookup, multi-stage scoring and cross-encoder re-ranking), collaborative and content-based filtering, matrix factorization (alternating least squares, Bayesian personalized ranking), sequence-aware and graph-based recommenders, cold start, learning-to-rank and negative sampling, turning noisy implicit feedback into labels, position, exposure and popularity bias and feedback loops, diversity, fairness-aware exposure and multi-objective re-ranking, counterfactual (off-policy) evaluation of recommenders (inverse propensity scoring, doubly robust estimators), and exploration with multi-armed and contextual bandits (epsilon-greedy, upper-confidence-bound and Thompson sampling, LinUCB, regret, non-stationarity, constraints, rollout, and when a bandit beats a fixed split or full reinforcement learning). Includes end-to-end recommender and personalized feed design. Focuses on the modeling and evaluation patterns specific to recommendation and ranking at scale. General A/B test design, generic ranking-metric definitions and ML serving infrastructure are covered elsewhere.
Implement a simple two-stage pipeline: retrieve candidate items with an inverted index on tags, then score the candidates with a lightweight model.
Sample Answer
Direct answer
A two-stage pipeline splits the work by cost. Stage 1 (retrieval) uses an inverted index (a map from each tag to the list of items carrying it; that list is called the tag's posting list) to pull only items that share at least one tag with the user, ranked by how many tags they share and capped at a fixed number of candidates. Stage 2 (ranking) scores just those candidates with a small model (here logistic regression, a model that turns a weighted sum of features into a click probability) and returns the top few. Stage 1 keeps the work proportional to the matching items instead of the whole catalogue; stage 2 spends model effort where it matters.
Approach
- Build the index once: for every item, add its id to the posting list of each of its (de-duplicated) tags. Cost: proportional to the total number of (item, tag) pairs.
- Retrieve: for each distinct tag of the user, walk the posting list and count, per item, how many of the user's tags it shares (the overlap). Keep the
capitems with the highest overlap, ties broken by item id so results are deterministic. A heap (a structure that keeps only the bestcapitems seen so far, so you never sort all the matches) makes the selection O(Mlogcap) for M distinct matched items; big-O notation says the work grows roughly in proportion to M times logcap. - Featurise each candidate: overlap count, the sum of the user's affinity weights over the item's tags, Jaccard similarity (shared tags divided by the size of the union of the two tag sets) and log popularity.
- Score and sort: model scores for the
capcandidates, return the top k. The score is the model'sdecision_function, the weighted sum of the features before it is turned into a probability; because the probability rises with that sum, sorting by it gives the same order as sorting by probability. - Train: from logged impressions (shown items and whether they were clicked). The training rows come from the same retrieval stage, so the model sees the candidate distribution it will be used on.
The features on three items, by hand
Take a user who likes tag 2 (weight 1.5) and tag 3 (weight 0.5), and three items with tags A = {2, 3, 7}, B = {2}, C = {3, 9, 11, 12}. The overlap is how many of the user's tags the item carries; the affinity sum adds up the user's weights on those shared tags; Jaccard is overlap divided by (item tags + user tags - overlap).
affinity = {2: 1.5, 3: 0.5} # the user's liked tags and weights
items = {"A": [2, 3, 7], "B": [2], "C": [3, 9, 11, 12]}
for name, tags in items.items():
shared = set(tags) & set(affinity)
overlap = len(shared)
aff = sum(affinity[t] for t in shared)
jac = overlap / (len(set(tags)) + len(affinity) - overlap)
print(name, "overlap", overlap, "affinity sum", aff, "jaccard", round(jac, 3))
Output:
A overlap 2 affinity sum 2.0 jaccard 0.667
B overlap 1 affinity sum 1.5 jaccard 0.5
C overlap 1 affinity sum 0.5 jaccard 0.2
Item A leads on all three. B and C tie on overlap (1 each), so retrieval order alone cannot separate them; the affinity sum can (1.5 against 0.5), and Jaccard also favours B because B has fewer unrelated tags. Those extra signals are what stage 2 weighs.
Code
The simulation below builds a 2,000-item catalogue with 60 tags, gives users 6 liked tags with weights, defines a click probability the simulator knows (so each strategy can be scored exactly), trains the model on 300 simulated impression lists, and evaluates 200 new users per world over 10 worlds. The assert compares the index's output (with no cap) against a brute-force scan of every item for the same user, so the index is checked against the definition rather than against itself. The last four lines run the edge cases. This is a simulation, not field data.
import heapq
from collections import defaultdict
import numpy as np
from sklearn.linear_model import LogisticRegression
class InvertedIndex:
"""tag -> sorted list of item ids that carry the tag."""
def __init__(self, item_tags):
self.postings = defaultdict(list)
for item_id, tags in enumerate(item_tags):
for t in set(tags):
self.postings[t].append(item_id)
def candidates(self, user_tags, cap):
"""Items sharing >=1 tag with the user, ranked by number of shared tags, at most `cap`."""
overlap = defaultdict(int)
for t in set(user_tags): # set(): a repeated tag counts once
for item_id in self.postings.get(t, ()): # unknown tag -> empty posting list
overlap[item_id] += 1
# tie-break on item id so the result is deterministic
return heapq.nsmallest(cap, overlap, key=lambda i: (-overlap[i], i)), overlap
def features(item_ids, overlap, affinity, item_tags, pop):
rows = []
for i in item_ids:
tags = set(item_tags[i])
aff = sum(affinity.get(t, 0.0) for t in tags)
jac = overlap[i] / (len(tags) + len(affinity) - overlap[i])
rows.append([overlap[i], aff, jac, np.log1p(pop[i])])
return np.array(rows)
def make_world(seed, n_items=2000, n_tags=60):
rng = np.random.default_rng(seed)
item_tags = [list(rng.choice(n_tags, rng.integers(1, 5), replace=False)) for _ in range(n_items)]
pop = rng.zipf(1.6, n_items).clip(max=5000) # skewed popularity: a few items are very popular (Zipf distribution)
return rng, item_tags, pop, n_tags
def make_user(rng, n_tags):
liked = rng.choice(n_tags, 6, replace=False)
return {int(t): float(rng.uniform(0.5, 2.0)) for t in liked}
def true_click_prob(items, affinity, item_tags, pop):
z = np.array([-3.5 + 0.9 * sum(affinity.get(t, 0.0) for t in item_tags[i]) + 0.15 * np.log1p(pop[i])
for i in items])
return 1 / (1 + np.exp(-z))
def run(seed, cap=100, k=5):
rng, item_tags, pop, n_tags = make_world(seed)
index = InvertedIndex(item_tags)
X, y = [], []
for _ in range(300): # training impressions drawn from retrieved candidates
u = make_user(rng, n_tags)
cands, ov = index.candidates(list(u), cap)
shown = rng.choice(cands, min(10, len(cands)), replace=False)
p = true_click_prob(shown, u, item_tags, pop)
X.append(features(shown, ov, u, item_tags, pop)); y.append(rng.random(len(shown)) < p)
model = LogisticRegression(max_iter=1000).fit(np.vstack(X), np.concatenate(y))
coef_list.append(model.coef_[0]) # keep the learned weights to inspect later
res = {"popularity only": [], "retrieval order only": [], "two-stage": []}
for _ in range(200):
u = make_user(rng, n_tags)
cands, ov = index.candidates(list(u), cap)
# check: the index returns exactly what brute force would (before the cap)
full, _ = index.candidates(list(u), len(item_tags))
brute = {i for i, t in enumerate(item_tags) if set(t) & set(u)}
assert set(full) == brute
score = model.decision_function(features(cands, ov, u, item_tags, pop))
two = [cands[j] for j in np.argsort(-score, kind="stable")[:k]]
res["two-stage"].append(true_click_prob(two, u, item_tags, pop).mean())
res["retrieval order only"].append(true_click_prob(cands[:k], u, item_tags, pop).mean())
res["popularity only"].append(true_click_prob(np.argsort(-pop, kind="stable")[:k], u, item_tags, pop).mean())
return {k_: float(np.mean(v)) for k_, v in res.items()}
coef_list = []
results = [run(s) for s in range(10)]
for name in results[0]:
vals = np.array([r[name] for r in results])
print(f"{name:22s} mean true click prob of top-5: {vals.mean():.4f}")
coefs = np.mean(coef_list, axis=0)
print("average model weights (overlap, affinity sum, jaccard, log popularity):", np.round(coefs, 2))
wins = sum(r["two-stage"] > max(r["popularity only"], r["retrieval order only"]) for r in results)
print("worlds where two-stage beats both baselines:", wins, "of", len(results))
# edge cases on a small catalogue
idx = InvertedIndex([[1, 2], [2], [3, 3], []])
print("empty user tags :", idx.candidates([], 5)[0])
print("unknown tag :", idx.candidates([99], 5)[0])
print("repeated user tag :", idx.candidates([2, 2, 2], 5)[0])
print("cap smaller than hits:", idx.candidates([1, 2, 3], 2)[0])
Output:
popularity only mean true click prob of top-5: 0.1378
retrieval order only mean true click prob of top-5: 0.3533
two-stage mean true click prob of top-5: 0.4789
average model weights (overlap, affinity sum, jaccard, log popularity): [-0.02 0.87 0.04 0.14]
worlds where two-stage beats both baselines: 10 of 10
empty user tags : []
unknown tag : []
repeated user tag : [0, 1]
cap smaller than hits: [0, 1]
Reading the output:
- Popularity alone (the same five items for everyone) gives 0.1378 mean true click probability for the top 5.
- Retrieval order only (most shared tags first, no model) gives 0.3533: matching tags is already a large gain.
- The two-stage pipeline gives 0.4789 and beats both baselines in all 10 worlds. The model contributes because overlap count ignores how much the user cares about each tag and how popular the item is; the model learns those weights.
- What the model learned. The averaged weights on (overlap, affinity sum, Jaccard, log popularity) are about (-0.02, 0.87, 0.04, 0.14). In this simulation the click rule is known to be roughly 0.9 times the affinity sum plus 0.15 times log popularity, and the fitted weights recover that: the affinity sum and popularity carry the weight, while overlap and Jaccard get near zero because the simulated click rule has no term for them. A feature that the true click behaviour does not use ends up with a weight near zero in the same way on real logs. On real logs the weights are whatever the data supports; reading them this way is a quick sanity check of what stage 2 uses.
- The edge cases behave as designed: a user with no tags or only an unknown tag gets an empty list (the caller falls back to popular items), a repeated tag counts once, and a cap of 2 keeps the two highest-overlap items with deterministic tie-breaking (items 0 and 1).
Complexity
- Build: O(P) for P total (item, tag) pairs; memory O(P).
- Query, stage 1: the sum of the posting-list lengths of the user's tags (every matched item is visited once per shared tag), plus O(Mlogcap) for selection.
- Query, stage 2: O(cap×F) for F features. The cap bounds model cost regardless of catalogue size.
Edge cases and failure modes
- Empty or unknown tags: return no candidates; fall back to a popularity list so the page is never empty.
- Fewer candidates than k: return what exists, or top up from the fallback.
- Very common tags produce huge posting lists. Options: skip tags that match more than a set share of the catalogue (they carry little signal), cap per-tag scanning, or process lists in popularity order and stop early.
- Retrieval recall limits everything. Stage 2 cannot rescue a relevant item with no shared tag; measure what share of later-engaged items stage 1 returned, and add a second source (embedding similarity, popularity within a segment) if recall is low.
- Training-serving mismatch (the model sees different feature values or candidates in training than in serving): compute features with the same function at training and serving time, as the code does.
- Selection bias in training data: the model only sees items stage 1 returned and the system displayed; add some exploration for items outside the usual candidates, and log propensities.
Running the code
pip install numpy scikit-learn
python two_stage.py
Save the listing above as two_stage.py. It uses fixed seeds, so the printed numbers repeat on the same library versions.
Design an ANN-backed candidate retrieval service for a recommender with a 200 ms end-to-end budget at 10k QPS. How do you choose and configure the index, shard and replicate it, warm it, and handle cold items?
Sample Answer
Direct answer
The service is an ANN (approximate nearest neighbor) index: a structure that finds the item vectors very likely to be among the closest to a query vector without comparing against every item. It serves the retrieval stage of a two-tower recommender: a user tower (a neural network that turns the user's features and recent activity into a vector) and an item side (vectors computed ahead of time, from a content tower that uses item features only, or from click history) share one space, and the best items are those with the largest dot product to the user vector. A later ranker, a model that orders the retrieved candidates using richer features, picks the final list.
Retrieval gets a slice of the 200 ms budget (here 40 ms for the ANN fan-out and merge), not the whole of it, because a ranker, business rules and network hops follow. My design: an HNSW (a layered neighbour graph) index over compressed item vectors (float16, 16-bit numbers that take half the memory of 32-bit floats) held entirely in RAM, a single shard until the memory arithmetic forces more, many identical replicas behind a load balancer to carry 10k queries per second (QPS), a separate small exact-scan "fresh" index for new items, and a nightly full rebuild with an atomic swap. The numbers below are planning arithmetic from stated assumptions; every assumption is meant to be replaced by a load-test measurement before you commit.
Architecture
flowchart LR
A[Gateway] --> B[User tower]
B --> C[Router]
C --> D[Main ANN index replicas]
C --> E[Fresh index: new items, exact scan]
D --> F[Merge and dedupe]
E --> F
F --> G[Ranker]
G --> H[Re-rank and rules]
Step 1: define the budget first
Work backwards from 200 ms end to end. An allocation, not a measurement, is shown in the program output below: 10 ms gateway, 20 ms user tower, 40 ms ANN fan-out and merge, 70 ms ranker, 30 ms re-rank and rules, 30 ms slack. Retrieval has to fit its 40 ms at the tail (p99, the slowest 1% of requests), not at the average, because the end-to-end p99 is what users feel.
Step 2: choose the index
| Option | Strength | Weakness | Choose when |
|---|---|---|---|
| Exact scan on accelerators | exact, simple | work grows linearly with catalogue and QPS | catalogue is small |
| IVF with compression | small memory, cheap rebuild | recall depends on nprobe (how many clusters of vectors a query scans) and cluster quality | memory is the binding constraint |
| HNSW graph | strong recall at low latency, supports inserts | extra memory for links, rebuilds are heavy | RAM fits and latency matters (my pick) |
IVF and HNSW are the two index families. Product quantisation (PQ) is not a third index: it cuts each vector into pieces and stores each piece as the number of its nearest entry in a small learned table, so it compresses the vectors held by either family, at some loss of accuracy.
I pick HNSW over float16 vectors and keep PQ codes in reserve if memory binds. Configure by sweeping HNSW's search-width parameter, usually called ef (how many best-so-far candidates the graph walk keeps), against recall@k (the share of the exact top k that the index returns) measured on a held-out query sample versus exact search, and choose the smallest width that meets the recall target at the 40 ms p99. A sweep might try ef values such as 32, 64, 128 and 256 (illustrative values, not results); each point records recall@k and p99 latency, and the chosen ef is the cheapest one that clears both limits. The links per node, graph_links in the code below (called M in the HNSW literature), is fixed at build time.
Step 3: size it (computed)
import math
# PLANNING ASSUMPTIONS (inputs, not measurements): replace each with a number from your own load test.
dim = 64
qps_target, budget_ms = 10_000, 200
node_ram_gb = 32 # RAM per index node
usable = 0.5 # use half for vectors + graph; the rest is OS, query buffers, rebuild headroom
per_replica_qps = 400 # sustained queries/s one replica serves at the target recall (assumed)
headroom = 0.6 # run at 60% of that so a lost node or a spike is absorbed
graph_links = 16 # HNSW "M"; layer 0 stores up to 2*M neighbour ids of 4 bytes each
GB = 1e9
def plan(n_items):
f32 = n_items * dim * 4 / GB
f16 = n_items * dim * 2 / GB
graph = n_items * 2 * graph_links * 4 / GB
index = f16 + graph
shards = math.ceil(index / (node_ram_gb * usable))
# Every query fans out to every shard, so each shard's replica group must absorb the full QPS.
replicas = math.ceil(qps_target / (per_replica_qps * headroom))
print(f"{n_items:>11,} items: f32 {f32:7.2f} GB | f16 {f16:7.2f} GB | graph {graph:7.2f} GB | "
f"shards {shards:3d} x replicas {replicas} = {shards * replicas} nodes")
plan(20_000_000)
plan(500_000_000)
# Tail latency under fan-out: P(at least one of S shards is slower than its own p99).
for s in [1, 2, 8, 32]:
print(f"fan-out {s:2d} shards: P(some shard beyond its p99) = {1 - 0.99 ** s:.4f}")
# Design budget for one request (an allocation, not a measurement).
stages = {"gateway": 10, "user tower": 20, "ANN fan-out + merge": 40, "ranker": 70, "re-rank + rules": 30, "slack": 30}
print("budget ms:", stages, "sum =", sum(stages.values()), "of", budget_ms)
assert sum(stages.values()) == budget_ms
Output:
20,000,000 items: f32 5.12 GB | f16 2.56 GB | graph 2.56 GB | shards 1 x replicas 42 = 42 nodes
500,000,000 items: f32 128.00 GB | f16 64.00 GB | graph 64.00 GB | shards 8 x replicas 42 = 336 nodes
fan-out 1 shards: P(some shard beyond its p99) = 0.0100
fan-out 2 shards: P(some shard beyond its p99) = 0.0199
fan-out 8 shards: P(some shard beyond its p99) = 0.0773
fan-out 32 shards: P(some shard beyond its p99) = 0.2750
budget ms: {'gateway': 10, 'user tower': 20, 'ANN fan-out + merge': 40, 'ranker': 70, 're-rank + rules': 30, 'slack': 30} sum = 200 of 200
Reading it: the 400 queries per second per replica is only meaningful at a stated search width: a wider ef compares more points per query and lowers it, so it must be measured at the ef chosen in the sweep, and the 42-replica figure then follows by the arithmetic in the code. Latency (the 40 ms limit for one query) and throughput (queries per second one replica can carry) are separate measurements that both have to hold at that ef. At an assumed 20 million items the index is 5.12 GB (float16 vectors 2.56 GB plus graph 2.56 GB) and fits one node, so the right answer is one shard, not several. Sharding is a cost (every request fans out to every shard and waits for the slowest), so it is added only when memory forces it. At an assumed 500 million items the same arithmetic gives 128 GB of index and 8 shards. The replica count comes from throughput: with the assumed 400 QPS per replica run at 60%, you need 42 replicas per shard group.
The fan-out rows show why shard count is not free: if each shard exceeds its own p99 latency 1% of the time (independently, an assumption), then with 8 shards 7.73% of requests have at least one slow shard. Mitigations: a deadline merge, which stops waiting at a time limit and merges the shards that have answered (the cost is a small recall loss), and a hedged duplicate request, which sends the same query to a second replica if the first has not answered after a short wait and uses whichever replies first.
Step 4: replicate, warm, deploy
- Replicate for throughput and failure, not for capacity of data: each replica holds a full copy of its shard. Keep spare capacity (the 60% headroom) so a lost node does not tip the rest over.
- Warm before serving: load the index into RAM, touch every page (or run a sample of real queries) so the first live queries do not pay for cold memory. A replica joins the load balancer only after a readiness check passes: it answers a canary query set (a fixed set of test queries whose exact answers are known) with recall at or above target versus the exact baseline.
- Rebuild and swap: build a new index offline from the latest vectors, warm it, then swap atomically (switch traffic from the old index to the new one in a single step, so no request sees a mixture), or shift traffic gradually, and keep the old one for rollback.
Step 5: handle cold items
New items have no click history, so their embeddings come from a content tower (item features only). They go into the small fresh index, which holds only recent items and is scanned exactly because it is small. Results merge with the main index, and a fraction of ranker slots can be reserved for fresh items so they gather clicks (this is where exploration enters). Once an item has enough interactions, the nightly rebuild moves it into the main index with a behaviour-informed vector.
Failure modes and diagnostics
- Recall drifts after a model update: embeddings from a new model version must never be queried against an index built with the old one. Version the index and the user tower together.
- A hot shard or slow replica inflates the tail: watch per-shard p99, not only the average.
- Filters (region, availability) applied after retrieval can empty the candidate list; over-fetch, or apply filters inside the index where the engine supports it.
What would flip the design
Much larger catalogue: more shards and PQ. Much lower budget: smaller search width, accept lower recall, or drop the ranker depth. Frequent inserts: lean on the fresh index and shorter rebuild cycles.
Per inference call you must produce top-k recommendations for a user from millions of items. What algorithmic and numerical techniques make this efficient and stable?
Sample Answer
Direct answer
Do not score every item with a heavy model. Serve in two stages: a cheap retrieval stage that narrows millions of items to a few hundred using precomputed item embeddings and an approximate nearest-neighbour index, then a heavier ranker on those few hundred. Inside retrieval, three ideas do the work: precompute everything that does not depend on the user, avoid sorting what you do not need to sort, and trade a little recall for a large cut in items scanned and bytes read. Start with partial selection, an IVF index and 8-bit storage; a graph index or product quantisation are added when the catalogue or the memory budget demands them. Numerical stability is handled by normalising vectors (scaling each to length 1), accumulating in 32-bit floats, and breaking score ties deterministically.
Mechanism
The user tower (a model that turns the user and context into a vector) runs once per request and produces a vector u∈Rd. Item vectors vi were computed offline and stored as an N×d matrix V. The retrieval score is the inner product si=u⋅vi (multiply the two vectors element by element and add up the results), so scoring all items is one matrix-vector product s=Vu. Quality of retrieval is reported as recall@k: the share of the true top k items (found by scoring every item exactly) that the approximate search also returns. If the exact top 10 has ten items and the fast search returns eight of them, recall@10 is 0.8.
- Exact scoring cost. For N=10,000,000 items and d=128, one request costs 2Nd floating-point operations (one multiply and one add per element), which the program below prints as 2.56 GFLOP (billions of floating-point operations), and reads the whole table from memory. That is feasible for offline jobs and small catalogues, but it is the cost that approximate search removes.
- Selection instead of sorting. You need the best k (say 10 to 500) of N scores. A full sort is O(NlogN). A partial selection (
np.argpartition, or a size-k heap) is O(N) for selection plus O(klogk) to order the winners. The program checks that the two give the same top-10. - Approximate nearest-neighbour (ANN) search. An ANN index gives up exactness for speed. Two common families: an inverted file (IVF), which clusters items with k-means (repeatedly assign each item to its nearest centre, then move each centre to the mean of its items) into lists and scans only the
nprobelists whose centroid (the centre of a list) scores highest for this user; and a graph index such as HNSW (hierarchical navigable small world), which walks a proximity graph toward the query. Both are approximate: you tune a knob (nprobe, or the graph's search breadth) to trade recall for speed. - Compression. Item tables dominate memory. Storing vectors in 16-bit floats (fp16, against fp32 for the usual 32-bit floats) halves them, 8-bit integers (int8) cut them to a quarter, and product quantisation (PQ, which splits each vector into sub-vectors and stores a short code per sub-vector) can reach tens of bytes per item. Smaller tables mean fewer cache misses (the processor needing data that is not in its small fast cache and waiting for main memory) and fewer shards.
- Sharding and batching. Split the catalogue into shards (slices, each held by one machine), take each shard's top-k, and merge: the global top-k is always inside the union of the shard top-k lists. The reason: suppose a global top-k item were missing from its own shard's top-k. Then at least k items in that shard would outscore it, so at least k items in the whole catalogue would outscore it, and it could not be in the global top-k. Batch several users into one matrix-matrix product so the item table is read once for many requests.
- Filters. Business rules (in stock, region, already seen) are applied inside the search or by over-fetching and filtering. Pure post-filtering of a too-small candidate list can return fewer than k items.
Numerical stability
- Scale. Cosine similarity (the cosine of the angle between two vectors) equals the dot product only for unit-norm vectors (vectors of length 1). If item norms vary, a raw inner product favours long vectors; decide on purpose whether that is wanted (a popularity-like signal) or normalise. An index built for cosine or L2 distance (ordinary straight-line distance) does not rank by raw inner product unless the vectors are normalised or the index supports inner product, so check which metric your index uses.
- Accumulation precision. Store in low precision if you like, but accumulate dot products in 32 bits. The program prints a 4096-term dot product: the fp32 result matches fp64 to three decimals, while a running sum kept in fp16 is off by 4.4 in this draw (-47.438 against -43.046). The size of the fp16 error changes with the random numbers drawn, because rounding errors pile up over 4096 additions and may partly cancel, but it is far above the fp32 error in every draw, so keep the accumulator in 32 bits.
- No softmax over millions. Ranking needs only the order of scores, and softmax (which turns scores into probabilities that sum to 1) is monotone, meaning it never reverses the order of two scores, so skip it at serving time. If you need probabilities, compute them on the short list with the log-sum-exp trick: subtract the largest score before exponentiating so that escore cannot overflow.
- Ties and bad values. Break ties by item id so two replicas return the same list, and drop NaN or infinite scores before selection, since comparisons with NaN are not ordered.
Worked example (synthetic stand-in data)
First the IVF idea on six items in two dimensions, small enough to follow by hand. The items fall into three lists with centroids (0.95, 0.1), (0.05, 0.95) and (-0.95, -0.05); the user vector is (0.8, 0.5). The user scores each centroid, probes the best list only (nprobe = 1), and scores just the items inside it.
import numpy as np
items = {"A": (1.0, 0.0), "B": (0.9, 0.2), "C": (0.0, 1.0), "D": (0.1, 0.9), "E": (-1.0, 0.0), "F": (-0.9, -0.1)}
lists = {0: ["A", "B"], 1: ["C", "D"], 2: ["E", "F"]}
centroids = {0: (0.95, 0.1), 1: (0.05, 0.95), 2: (-0.95, -0.05)}
u = np.array([0.8, 0.5])
exact = sorted(items, key=lambda n: -np.dot(items[n], u))
print("exact scores:", {n: round(float(np.dot(items[n], u)), 2) for n in items})
print("centroid scores:", {c: round(float(np.dot(v, u)), 3) for c, v in centroids.items()})
best = max(centroids, key=lambda c: np.dot(centroids[c], u))
scanned = lists[best]
found = sorted(scanned, key=lambda n: -np.dot(items[n], u))[:3]
print("probed list", best, "scanned", scanned, "returned", found)
print("exact top 3:", exact[:3], " recall@3 =", round(len(set(found) & set(exact[:3])) / 3, 3))
Output:
exact scores: {'A': 0.8, 'B': 0.82, 'C': 0.5, 'D': 0.53, 'E': -0.8, 'F': -0.77}
centroid scores: {0: 0.81, 1: 0.515, 2: -0.785}
probed list 0 scanned ['A', 'B'] returned ['B', 'A']
exact top 3: ['B', 'A', 'D'] recall@3 = 0.667
The list whose centroid scores highest (0.81) is list 0, so only A and B are scored (2 of 6 items); the exact top 3 also contains D, which sits in list 1 and is never looked at, so recall@3 is 2/3. Probing the second list too (nprobe = 2) would find D. That is the whole trade: fewer items scored, occasionally a miss.
The larger program below applies the same idea at scale. It builds 20,000 items in 40 taste clusters (a synthetic stand-in for real embeddings) with d=32 and 200 users, and measures recall@10 against exact search. IVF here uses scikit-learn 1.5.2 k-means with 64 lists.
import numpy as np
from sklearn.cluster import KMeans
rng = np.random.default_rng(0)
n_items, d, k = 20000, 32, 10
# Items drawn from 40 taste clusters so the index has structure to exploit.
centers = rng.normal(size=(40, d))
items = centers[rng.integers(0, 40, n_items)] + 0.6 * rng.normal(size=(n_items, d))
items = items.astype(np.float32)
users = (centers[rng.integers(0, 40, 200)] + 0.6 * rng.normal(size=(200, d))).astype(np.float32)
def exact_topk(u, X, k):
s = X @ u
idx = np.argpartition(-s, k)[:k] # O(n) selection, not a full sort
return idx[np.argsort(-s[idx])]
# 1. partial selection gives the same top-k as a full sort
u = users[0]
full = np.argsort(-(items @ u))[:k]
print("argpartition == full sort:", bool(np.array_equal(exact_topk(u, items, k), full)))
truth = [exact_topk(u, items, k) for u in users]
def recall(found):
return np.mean([len(set(a) & set(b)) / k for a, b in zip(found, truth)])
# 2. int8 scalar quantization of the item table (one scale per table)
scale = np.abs(items).max() / 127.0
q = np.round(items / scale).astype(np.int8)
found = []
for u in users:
s = q.astype(np.int32) @ np.round(u / scale).astype(np.int32)
idx = np.argpartition(-s, k)[:k]
found.append(idx[np.argsort(-s[idx])])
print(f"int8 recall@{k}: {recall(found):.3f} bytes: {items.nbytes} -> {q.nbytes}")
# 3. IVF: coarse k-means lists, scan only the nprobe closest lists
n_lists = 64
km = KMeans(n_clusters=n_lists, n_init=1, random_state=0).fit(items)
lists = [np.where(km.labels_ == c)[0] for c in range(n_lists)]
for nprobe in (1, 4, 16):
found, scanned = [], []
for u in users:
near = np.argsort(-(km.cluster_centers_ @ u))[:nprobe]
cand = np.concatenate([lists[c] for c in near])
scanned.append(len(cand) / n_items)
s = items[cand] @ u
found.append(cand[np.argsort(-s)[:k]])
print(f"IVF nprobe={nprobe:2d}: recall@{k}={recall(found):.3f} items scanned={np.mean(scanned):.3f}")
# 4. memory and compute budget for 10 million items, 128 dims
N, D = 10_000_000, 128
print("fp32 GB:", N * D * 4 / 1e9)
print("fp16 GB:", N * D * 2 / 1e9)
print("int8 GB:", N * D * 1 / 1e9)
print("PQ 16 bytes/item GB:", N * 16 / 1e9)
print("brute-force GFLOP per user:", 2 * N * D / 1e9)
# 5. numerical stability: a long dot product accumulated in fp16 vs fp32
x = (rng.normal(size=4096) * 4).astype(np.float16)
y = (rng.normal(size=4096) * 4).astype(np.float16)
print("dot fp64:", round(float(np.dot(x.astype(np.float64), y.astype(np.float64))), 3))
print("dot fp32:", round(float(np.dot(x.astype(np.float32), y.astype(np.float32))), 3))
acc = np.float16(0)
for p, q2 in zip(x, y):
acc = np.float16(acc + p * q2)
print("dot fp16 running sum:", round(float(acc), 3))
Output:
argpartition == full sort: True
int8 recall@10: 0.972 bytes: 2560000 -> 640000
IVF nprobe= 1: recall@10=0.819 items scanned=0.019
IVF nprobe= 4: recall@10=1.000 items scanned=0.065
IVF nprobe=16: recall@10=1.000 items scanned=0.248
fp32 GB: 5.12
fp16 GB: 2.56
int8 GB: 1.28
PQ 16 bytes/item GB: 0.16
brute-force GFLOP per user: 2.56
dot fp64: -43.046
dot fp32: -43.046
dot fp16 running sum: -47.438
Reading the code: the int8 block uses one scale for the whole table, scale = max |value| / 127, so every number is rounded to an integer between -127 and 127 (np.round(items / scale)); the user vector is rounded with the same scale and both are cast to 32-bit integers before the dot product so that sums of products cannot overflow 8 bits. The integer score equals the real score divided by scale squared, a positive constant, so the order is unchanged apart from rounding. The IVF block fits k-means once (the lists), then for each user ranks the 64 centroids by inner product with the user, concatenates the items of the best nprobe lists into cand, scores only those, and keeps the 10 best.
Reading it: scanning about 6.5% of items (nprobe=4) already recovers essentially all of the exact top-10 on this clustered data (recall 1.000 here; it stays within 0.002 of that on other random draws of the same data), nprobe=1 scans 1.9% and loses some (recall 0.819), and int8 storage quarters the table (2,560,000 to 640,000 bytes) at recall 0.972. The 10-million-item budget lines are plain arithmetic: 5.12 GB in fp32, 1.28 GB in int8, 0.16 GB at 16 bytes per item. Real catalogues are less cleanly clustered, so recall at a given nprobe will be lower than here; always measure on your own data.
Trade-offs and pitfalls
- Recall versus latency. Measure recall@k against exact search on a sample of real queries, and also the downstream metric, since the ranker can only reorder what retrieval returns. A missed item is invisible to every later stage.
- Index freshness. New items must reach the index; HNSW inserts are cheap but IVF centroids drift as the catalogue changes, so schedule retraining or rebuilds.
- Memory is usually the binding limit. Compress first, then shard.
- Common mistakes: sorting all scores; mixing normalised queries with unnormalised items; accumulating in fp16; trusting ANN recall measured on a different distribution than production traffic; filtering after retrieval without over-fetching.
Implement brute-force top-k retrieval in NumPy: given item embeddings and a user embedding, return the top-k items by cosine similarity. Discuss complexity and when this stops being viable.
Sample Answer
The idea in plain words
An embedding is a list of numbers (a vector) that places an item or user in space so that similar things land close together. Brute-force top-k retrieval means: score the user against every item, then keep the k best. Cosine similarity compares directions and ignores length:
cos(u,v)=∥u∥∥v∥u⋅vHere u⋅v is the dot product (sum of element-wise products) and ∥u∥ is the vector's length (its L2 norm, the straight-line length ∑kuk2). Cosine equals the plain dot product when the two lengths multiply to 1 (in particular when both vectors have length 1), so you either normalize first or divide by the lengths while scoring.
Implementation
The steps with shapes, for N items of dimension d:
itemsis an (N,d) matrix andusera (d,) vector.items @ usergives N dot products in one pass: 2Nd floating-point operations.- Divide by the item norms (shape (N,)) times the user norm to get cosines.
- Zero vectors (an item without an embedding) have no direction, so cosine is undefined. The code gives them a score of negative infinity so they are never returned, and raises an error if the user vector is zero.
np.partitionfinds the k-th best score in O(N) without sorting everything. Every item scoring at least that value is kept, which includes every item tied with the k-th one, and only those few are sorted.- Scores are rounded to 6 decimals so float noise cannot reorder exact ties, and ties are broken by the lowest index, both inside the top k and at its edge (which of several tied items make the cut), so the output is the same on every run.
- To recommend for a user id instead of an embedding you already hold, look up that user's row in the user-embedding table and pass it as
user; the function is the same, only the source of the vector changes.
The driver builds 10,000 random item vectors, plants an item with no embedding (index 7) and an item (index 3) pointing in the same direction as item 100 but five times longer, and makes the user close to item 100. It checks the result against scikit-learn's cosine_similarity (with the zero row removed before the call, since the reference should not have to decide how to score it), shows that ranking by raw dot product gives a different list, and asks for the top 5 of 50 identical items to show that the lowest indices win a tie at the edge of the top k.
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
def top_k_cosine(user, items, k, eps=1e-12):
"""items: (N, d), user: (d,). Returns (indices, scores) of the k most similar items."""
item_norm = np.linalg.norm(items, axis=1) # (N,)
user_norm = np.linalg.norm(user) # scalar
if user_norm < eps:
raise ValueError("zero user vector: cosine is undefined")
dots = (items @ user).astype(np.float64) # (N,) one pass over the matrix
scores = np.where(item_norm < eps, -np.inf, dots / np.maximum(item_norm * user_norm, eps))
scores = np.round(scores, 6) # so float noise cannot reorder exact ties
k = min(k, int((scores > -np.inf).sum()))
if k < 1:
return np.empty(0, dtype=np.int64), np.empty(0)
kth = np.partition(scores, scores.size - k)[scores.size - k] # k-th largest score, O(N)
cand = np.flatnonzero(scores >= kth) # the k best plus anything tied with the k-th
order = cand[np.lexsort((cand, -scores[cand]))][:k] # score descending, then lowest index
return order, scores[order]
rng = np.random.default_rng(0)
N, d, k = 10_000, 64, 5
items = rng.normal(size=(N, d)).astype(np.float32)
items[7] = 0.0 # an item with no embedding yet
items[3] = 5.0 * items[100] # same direction as item 100, 5x the length
user = items[100] + 0.1 * rng.normal(size=d).astype(np.float32)
idx, sc = top_k_cosine(user, items, k)
print("top-k idx ", idx.tolist())
print("top-k scores", np.round(sc, 4).tolist())
print("norms of items 3 and 100:", round(float(np.linalg.norm(items[3])), 2), round(float(np.linalg.norm(items[100])), 2))
ref = cosine_similarity(user[None, :], np.delete(items, 7, axis=0))[0] # sklearn, zero row removed
ref_idx = np.delete(np.arange(N), 7)[np.argsort(-ref)[:k]]
print("same index set as sklearn:", set(idx.tolist()) == set(ref_idx.tolist()),
"| scores close:", bool(np.allclose(sc, np.sort(ref)[::-1][:k], atol=1e-5)))
dot_idx = np.argsort(-(items @ user))[:k]
print("raw dot-product top-k:", dot_idx.tolist(), "| same as cosine:", bool(np.array_equal(dot_idx, idx)))
try:
top_k_cosine(np.zeros(d, dtype=np.float32), items, k)
except ValueError as e:
print("zero user ->", e)
tied = np.tile(items[100], (50, 1)) # 50 identical items: every score ties
print("50 identical items, k=5 ->", top_k_cosine(items[100], tied, 5)[0].tolist())
for n_items, dim in [(10_000, 64), (10_000_000, 128)]:
gb = n_items * dim * 4 / 1e9
gflop = 2 * n_items * dim / 1e9
print(f"N={n_items:>10,} d={dim}: matrix {gb:9.4f} GB float32, {gflop:8.4f} GFLOP per query")
Output:
top-k idx [3, 100, 7048, 9369, 7951]
top-k scores [0.9954, 0.9954, 0.4419, 0.4353, 0.4288]
norms of items 3 and 100: 38.04 7.61
same index set as sklearn: True | scores close: True
raw dot-product top-k: [3, 100, 1326, 9369, 7951] | same as cosine: False
zero user -> zero user vector: cosine is undefined
50 identical items, k=5 -> [0, 1, 2, 3, 4]
N= 10,000 d=64: matrix 0.0026 GB float32, 0.0013 GFLOP per query
N=10,000,000 d=128: matrix 5.1200 GB float32, 2.5600 GFLOP per query
Reading the output:
- Items 3 and 100 tie at the top with cosine 0.9954 despite norms of 38.04 and 7.61: cosine ignores length. The zero vector (index 7) never appears.
- The raw dot product returns [3, 100, 1326, 9369, 7951]; cosine returns [3, 100, 7048, 9369, 7951]. The third place differs because item 1326 has a long vector, and a dot product rewards length as well as direction. If your embeddings encode popularity in their length, a dot product ranks by popularity and direction together, which can be what you want, but it is a decision, not an accident.
- The check against scikit-learn prints that the index sets match and the scores agree to within 1e-5.
- With 50 identical items and k = 5, the result is the five lowest indices, 0 to 4, every run.
Complexity and when it stops being viable
- Time per query: O(Nd) for the scoring pass plus O(N) for the partition plus a final sort of the k best and any items tied with the k-th (usually about klogk).
- Memory: the item matrix costs N⋅d⋅4 bytes in float32. The last two printed lines compute it: 10,000 items at 64 dimensions is 0.0026 GB and 0.0013 GFLOP per query; 10,000,000 items at 128 dimensions is 5.1200 GB and 2.5600 GFLOP per query.
- Every query reads the entire matrix from memory. Each number fetched takes part in only about one multiply and one add, so the processor mostly waits for data to arrive: memory bandwidth (how many bytes per second memory can deliver) is the limit, not arithmetic. Batching many users into one matrix multiply lets each item row, once fetched, be used for every user in the batch, so one read of the matrix serves many queries (the reads are amortized over the batch). That is the first optimization.
- It stops being viable when the catalog no longer fits in one machine's memory, or when queries per second times the per-query cost exceeds the hardware, or when the latency budget (tens of milliseconds for a recommendation request) cannot afford a full scan. Then move to an approximate nearest-neighbour (ANN) index such as an inverted file (IVF, which groups vectors into clusters and scans only the nearest clusters) or HNSW (a navigable graph of neighbours). These trade a little recall for far fewer comparisons, so you must measure their recall against this exact brute-force baseline, which is the reason to keep the exact function around.
Edge cases and pitfalls
- Zero vectors and a zero user vector (handled above).
- Fewer than k valid items (the code clamps k, and returns empty arrays if no item is valid).
- Normalizing once offline and storing unit vectors makes cosine a plain dot product at query time and saves the norm division.
- float16 or int8 storage cuts memory but changes scores slightly; re-check recall.
- Ties and near-ties make results order-dependent unless you break them explicitly. A partition alone does not do it: it may keep any of the items tied at the k-th score, so the tied items are gathered and ordered by index, as the code does.
Design a recommendation system for a video streaming service with tens of millions of users and millions of items. Specify the stages, candidate sizes, retrieval method, ranking features and how you evaluate it offline and online.
Sample Answer
Direct answer
Use a funnel that narrows the catalog in stages, because scoring millions of items per request with a rich model is far too expensive: several cheap candidate sources pull about a thousand items, a light ranker cuts them to a few hundred, a heavy ranker scores those with all the features, and a re-ranking step enforces diversity and business rules before about 40 items are shown. Retrieval is optimized for recall (the share of items the user would like that make it into the candidate set; do not lose them), ranking for precision at the top of the page. Items with no watch history are the cold-start problem: a model that learns from past behaviour has nothing to go on for them, so the design reserves slots and uses content features for them. Evaluate offline with a time-based split, then decide with an online A/B test on long-run user value, not clicks alone.
Stages and candidate sizes
The sizes below are design targets chosen for this scale, to be tuned against the latency budget; the arithmetic is computed in the program that follows. The funnel counts reconcile as follows: the five sources return 1150 items in total, the same video is often returned by two sources, so merging and de-duplicating by video ID leaves about 1000 (an assumed 13% overlap, a figure to measure on real traffic), and the light ranker receives those 1000.
flowchart LR
A["Catalog: millions of items"] --> B["Candidate generation: 1150 items from 5 sources"]
B --> B2["Merge and de-duplicate: about 1000 items"]
B2 --> C["Light ranker: keep 200"]
C --> D["Heavy ranker: score 200"]
D --> E["Re-rank: diversity and rules"]
E --> F["Page: 40 items"]
| Stage | Input to output | Purpose | Method |
|---|---|---|---|
| Candidate generation | millions to 1150 (before de-duplication) | recall | several sources in parallel |
| Merge and de-duplicate | 1150 to about 1000 | remove videos several sources returned | union by video ID |
| Light ranker | about 1000 to 200 | cheap precision | small model on a few dozen features |
| Heavy ranker | 200 scored | precise ordering | deep model, many features, multiple objectives |
| Re-ranking | 200 to 40 | page quality | diversity, freshness, rules, de-duplication of series |
Retrieval method
Run several sources and merge them, because each one finds items the others miss:
- Two-tower embedding retrieval: one neural network turns the user (history, context) into a vector, another turns each video into a vector, and the score is their dot product. Item vectors are precomputed and stored in an approximate nearest-neighbour (ANN) index; only the user vector is computed per request. Take 500 candidates.
- Item-to-item co-watch: videos watched by the same people as the user's recent videos (300).
- Recent-history neighbours: items similar to the last few things watched in this session (200).
- Trending in the user's region (100) and a slot reserved for new releases (50), which solves part of the cold-start problem for items with no history.
Total before de-duplication: 500 + 300 + 200 + 100 + 50 = 1150 candidates; after de-duplication, about 1000. These proportions are starting targets, not derived constants. To set your own, measure for each source the share of later-watched videos that only that source found per slot it uses, give slots to the sources with the most unique recall per slot, and cut until the latency budget fits. The item vectors at 5 million items and 64 dimensions occupy about 1.28 GB in 32-bit floats (0.32 GB at 8-bit integers), small enough to hold in memory per index shard.
import numpy as np
from sklearn.metrics import ndcg_score
# Funnel sizes and cost, all inputs are stated assumptions for the design (not measurements).
items, dim = 5_000_000, 64
bytes_f32 = items * dim * 4
print(f"item embedding table: {bytes_f32 / 1e9:.2f} GB float32, {items * dim * 1 / 1e9:.2f} GB at int8")
sources = {"two-tower ANN": 500, "co-watch / item-to-item": 300, "recent-history neighbours": 200,
"trending / popular in region": 100, "new-release slot": 50}
cand = sum(sources.values())
print("candidate sources:", sources, "total before dedup:", cand)
after_dedup = 1000 # assumed: overlapping sources return some of the same videos
print(f"after merge and de-duplication: {after_dedup} items ({1 - after_dedup / cand:.1%} of the merged list was repeats)")
for name, n_in, per_item_flops in [("light ranker", 1000, 2e5), ("heavy ranker", 200, 5e6)]:
print(f"{name}: {n_in} items x {per_item_flops:.0e} FLOP = {n_in * per_item_flops / 1e9:.2f} GFLOP per request")
print(f"final page: 40 items shown from 200 heavy-ranked, i.e. {40 / items:.6%} of the catalog")
# Offline metric on a 5-item page: NDCG@5 with linear gain (gain = relevance), log2 discount.
rel = np.array([[3, 0, 2, 0, 1]]) # watch-based relevance of items in shown order
good = np.array([[0.9, 0.1, 0.8, 0.2, 0.7]]) # scores that order items by true relevance
bad = np.array([[0.1, 0.9, 0.2, 0.8, 0.3]])
for name, s in [("ranker that agrees", good), ("ranker that disagrees", bad)]:
print(f"NDCG@5 {name}: {ndcg_score(rel, s, k=5):.4f}")
# The same number by hand for the ranker that disagrees: DCG = sum of gain / log2(position + 1).
def dcg(gains):
return sum(g / np.log2(pos + 1) for pos, g in enumerate(gains, start=1))
shown = rel[0][np.argsort(-bad[0])] # relevances in the order the bad ranker puts them
ideal = np.sort(rel[0])[::-1]
print(f"order shown {shown.tolist()}: DCG = {dcg(shown):.4f}; ideal order {ideal.tolist()}: DCG = {dcg(ideal):.4f}; "
f"ratio = {dcg(shown) / dcg(ideal):.4f}")
# Combining heads into one ranking score. Weights are illustrative; real ones are tuned online.
w_play, w_watch, w_abandon = 0.5, 0.4, -0.3
for name, p_play, watch, p_abandon in [("clickable but abandoned", 0.60, 0.30, 0.40), ("less clicked but watched", 0.40, 0.80, 0.05)]:
score = w_play * p_play + w_watch * watch + w_abandon * p_abandon
print(f"{name:<26} P(play)={p_play:.2f} watch={watch:.2f} P(abandon)={p_abandon:.2f} -> score {score:.3f}")
Output:
item embedding table: 1.28 GB float32, 0.32 GB at int8
candidate sources: {'two-tower ANN': 500, 'co-watch / item-to-item': 300, 'recent-history neighbours': 200, 'trending / popular in region': 100, 'new-release slot': 50} total before dedup: 1150
after merge and de-duplication: 1000 items (13.0% of the merged list was repeats)
light ranker: 1000 items x 2e+05 FLOP = 0.20 GFLOP per request
heavy ranker: 200 items x 5e+06 FLOP = 1.00 GFLOP per request
final page: 40 items shown from 200 heavy-ranked, i.e. 0.000800% of the catalog
NDCG@5 ranker that agrees: 1.0000
NDCG@5 ranker that disagrees: 0.5296
order shown [0, 0, 1, 2, 3]: DCG = 2.5219; ideal order [3, 2, 1, 0, 0]: DCG = 4.7619; ratio = 0.5296
clickable but abandoned P(play)=0.60 watch=0.30 P(abandon)=0.40 -> score 0.300
less clicked but watched P(play)=0.40 watch=0.80 P(abandon)=0.05 -> score 0.505
A FLOP is one floating-point operation (one addition or multiplication on floating-point numbers, the computer's format for numbers with a fractional part), used here as a rough measure of compute per item. The per-item FLOP counts in the program are stated assumptions (a small model at 200,000 floating-point operations per item, a deep model at 5,000,000), not measurements; the point is the shape of the budget: the heavy ranker sees one fifth of the items but costs five times more per request than the light ranker, which is why it sits after the cut.
Ranking features and objectives
- User: watch history aggregates by genre with recency decay, device, time of day, language, subscription tier, recent session behaviour (updated within the session).
- Item: genre, age since release, duration, popularity trend, creator, embedding.
- Cross: user-genre affinity, whether the user has watched this series before, similarity of the item to the last five watched.
- Labels are implicit feedback (behaviour rather than ratings): a play start, the fraction watched, a like, a quick abandon. A click-only target rewards misleading thumbnails, so train a multi-task model (one network that learns several targets at once, with a shared body and one small output layer, called a head, per target) with heads for P(play), expected watch fraction and P(abandon within a minute) and combine them into one score with weights tuned online. With illustrative weights of 0.5 on P(play), 0.4 on watch fraction and -0.3 on P(abandon), a video that is often started but abandoned (0.60, 0.30, 0.40) scores 0.300 and a less clicked but watched one (0.40, 0.80, 0.05) scores 0.505, so the combined score reverses the click-only order; the last lines of the program print these. Real weights are tuned online against the long-run metric.
- Re-ranking: cap items per genre or series on the page, push down items the user already finished, mix in an exploration slot, respect licensing and regional rules.
Evaluation
Offline:
- Retrieval: recall@K against held-out future plays (what share of the items the user later watched were in the candidate set); the ceiling for everything after it.
- Ranking: NDCG@k, normalized discounted cumulative gain, a ranking metric where the gain at position i is divided by log2(i+1), so lower positions count for less. The convention in the program above is scikit-learn's default (gain equal to the relevance value, log2 discount): a ranker that orders the five shown items by true relevance scores 1.0000, and one that orders them badly scores 0.5296. By hand for the bad ranker: it shows the items with relevance 0, 0, 1, 2, 3 in that order, so DCG (discounted cumulative gain) is 0/log22+0/log23+1/log24+2/log25+3/log26=2.5219; the ideal order 3, 2, 1, 0, 0 gives 3/log22+2/log23+1/log24=4.7619; and NDCG is 2.5219/4.7619=0.5296, as printed.
- Splits are by time (train on the past, test on later days), never random, so the model cannot learn from the future. Logged data only contains what the old system showed, so offline gains are biased toward the old policy; treat them as a filter, not as the decision.
Online: an A/B test with randomization at the user level, a primary metric of long-run value (watch time per user over weeks, retention) and guardrails (metrics that must not get worse, even if the primary metric improves: abandon rate, diversity, latency, complaints). Keep a long-lived holdout without personalization to measure the cumulative effect.
E-commerce feeds and daily-update constraints
- E-commerce home feed: add stock and price eligibility to candidate generation, optimize expected value (probability of purchase times margin) rather than clicks, and for cross-sell and up-sell score the incremental effect on customer lifetime value (LTV), not just the next purchase. Show a short reason ("because you bought X") for explainability; it needs the retrieval source that produced the item to be carried along as a feature.
- Real-time personalization with daily updates: retrain the two towers and rebuild the item index daily, add new items to the index incrementally within minutes, and feed in-session behaviour as real-time features so the page reacts inside the session even though the heavy models change once per day. Every change ships behind an A/B test with logged impression data.
Pitfalls
- Optimizing retrieval and ranking separately without tracking recall of the final shown items.
- Offline metrics that rise while online watch time falls (popularity bias: the model favours already-popular videos, which score well on logged data but narrow what users see).
- Training-serving skew: features computed differently in the pipeline that builds training data and in the live serving path, so the model sees inputs at serving time that differ from those it learned on.
- No exploration, so new items never reach the ranker.
Unlock Full Question Bank
Get access to all 7 Recommendation, Ranking, and Personalization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.