Sub topic 14
Scaling to large catalogs
This chapter assumes you can write NumPy code and that you have read the chapters on neighborhood methods and matrix factorization. You should know what the item-item similarity matrix is and what the factor matrices P and Q hold.
The toy matrices in earlier chapters fit in memory and score instantly. A production catalog does not. This chapter covers where the cost comes from, how to cut it, and how approximate nearest neighbor (ANN) search trades a little accuracy for large speedups.
Where the cost comes from
Take a service with 10 million users and 1 million items. Four costs matter.
| Step | Naive cost | At this size |
|---|---|---|
| User-user similarity matrix | users² entries | 10¹⁴ entries, about 400 TB as float32 |
| Item-item similarity matrix | items² entries | 10¹² entries, about 4 TB as float32 |
| Scoring all items for one user with factors of size k | items × k multiply-adds | 64 million for k = 64 |
| Retraining factors | ratings × k per epoch | grows with data, not with catalog size |
Three points follow from the table.
- User-based neighborhoods rarely survive at this scale. Items usually number fewer than users, and item similarities change more slowly, so item-based methods are the usual choice.
- The item-item matrix is never stored densely. Most item pairs share no users, so the true matrix is sparse. Production systems also keep only the top k most similar items per item (often 20 to 200) and drop the rest.
- Serving is the bottleneck for factorization models. Training happens offline, but every request needs a top-N list within a latency budget of tens of milliseconds.
Precompute what you can
Item similarities depend on item behavior, which drifts slowly. Compute them in a batch job, for example nightly, keep the top-k neighbors per item in a key-value store, and look them up at request time. A prediction then needs only the user's recent items and a few lookups.
The trade-off is staleness. A new item has no neighbors until the next batch run, and a trending item takes a day to influence recommendations. Many teams add a cheap incremental path for recent interactions on top of the nightly job.
Exact top-N for factorization models
With learned factors, the score for a user is the dot product of the user vector and every item vector. Exact retrieval is one matrix-vector product followed by a partial sort. A full sort is unnecessary because you only need the top n.
import numpy as np
def top_n_exact(p, Q, n=10, exclude=()):
"""Return the ids of the n items with the highest score p . Q[i]."""
scores = Q @ p
if len(exclude) > 0:
scores[list(exclude)] = -np.inf # drop items the user already saw
cand = np.argpartition(scores, -n)[-n:] # O(items), unordered
return cand[np.argsort(scores[cand])[::-1]] # sort only n entries
rng = np.random.default_rng(0)
Q = rng.normal(size=(20000, 32)).astype(np.float32)
p = rng.normal(size=32).astype(np.float32)
print(top_n_exact(p, Q, n=5))argpartition runs in linear time, which beats the O(items log items) cost of a full sort. For one user this is fast. At 1 million items and k = 64, the product reads about 256 MB of item vectors per request, which takes tens of milliseconds and uses memory bandwidth you cannot spare under heavy traffic. Batching many users into one matrix-matrix product helps with throughput. It does not help with per-request latency.
Approximate nearest neighbors
ANN indexes skip most of the catalog. They return items that are probably among the best, in time far below linear. Four families are common.
- Inverted file (IVF): cluster the item vectors with k-means. At query time, scan only the few clusters whose centroids score highest.
- Graph indexes such as HNSW: link each item to nearby items in a layered graph. A query walks the graph greedily toward better scores.
- Product quantization (PQ): compress each vector into a short code so more of the catalog fits in memory and distance computations are faster. It is often combined with IVF.
- Locality-sensitive hashing (LSH): hash vectors so that similar ones tend to share a bucket. It is simple, but it usually gives lower recall than graphs at the same speed.
Libraries such as Faiss, hnswlib, Annoy, and ScaNN implement these. To show the idea without a dependency, here is a small IVF index in NumPy, with its recall measured against the exact answer.
import numpy as np
def kmeans(X, n_cells, iters=10, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), n_cells, replace=False)].copy()
for _ in range(iters):
d = (centroids ** 2).sum(1)[None, :] - 2 * X @ centroids.T
assign = d.argmin(1)
for c in range(n_cells):
members = X[assign == c]
if len(members) > 0:
centroids[c] = members.mean(0)
d = (centroids ** 2).sum(1)[None, :] - 2 * X @ centroids.T
return centroids, d.argmin(1)
def ivf_search(p, Q, centroids, cells, n=10, nprobe=4):
probe = np.argsort(centroids @ p)[::-1][:nprobe]
cand = np.concatenate([cells[c] for c in probe])
scores = Q[cand] @ p
order = np.argsort(scores)[::-1][:n]
return cand[order], len(cand)
rng = np.random.default_rng(0)
Q = rng.normal(size=(20000, 32)).astype(np.float32)
users = rng.normal(size=(50, 32)).astype(np.float32)
n_cells = 100
centroids, assign = kmeans(Q, n_cells)
cells = [np.where(assign == c)[0] for c in range(n_cells)]
exact = [set(np.argsort(Q @ u)[::-1][:10]) for u in users]
for nprobe in (1, 5, 20, 100):
recalls, scanned = [], []
for u, truth in zip(users, exact):
ids, count = ivf_search(u, Q, centroids, cells, n=10, nprobe=nprobe)
recalls.append(len(set(ids) & truth) / 10)
scanned.append(count / len(Q))
print(f"nprobe={nprobe:3d} recall@10={np.mean(recalls):.2f} "
f"scanned={np.mean(scanned):.0%}")The last row scans every cell, so its recall is 1.00. Lower nprobe values scan a smaller share of the catalog and lose some true top-10 items. Random Gaussian vectors have no cluster structure, so this is a hard case. Real learned embeddings cluster better and usually reach higher recall at the same scan fraction.
Every ANN index has a knob like nprobe: efSearch in HNSW, or the number of probes in LSH. Turning it up buys recall and costs latency. Pick the setting by measuring recall against brute-force results on a sample of real queries.
Inner product is not a distance
Matrix factorization scores items by dot product. This is maximum inner product search (MIPS), and it differs from nearest neighbor search in Euclidean or cosine terms. An item vector with a large norm can win for many users, and many ANN indexes assume a metric. Three options exist.
- Normalize all vectors and use cosine similarity. This changes the ranking, because item norms often carry popularity information, so check that quality still holds.
- Use an index that supports inner product directly. Faiss and HNSW implementations offer this.
- Reduce MIPS to L2 search. Let M be the largest item norm. Append one coordinate
sqrt(M² - ‖q‖²)to each item vectorq, and append 0 to the user vectorp. Then‖p' - q'‖² = ‖p‖² + M² - 2 p·q, so the nearest item in L2 is the one with the highest inner product.
Two-stage pipelines
Large systems rarely score the whole catalog with one model. Retrieval narrows millions of items to a few hundred candidates, using ANN over factors or precomputed item neighbors. A heavier ranking model then re-orders only those candidates, using features that would be too slow to compute for every item.
This split fixes the order of the mistakes that matter. The ranker cannot recover an item the retriever missed, so measure retrieval recall separately from final ranking quality.
Failure modes
- Index staleness. Retraining changes the factor space, so an index built on old item vectors is invalid for new user vectors. Rebuild the index and the user vectors together and swap them as a pair.
- Filtering after retrieval. If you retrieve 10 items and then remove those the user has seen, you may return fewer than 10. Over-fetch (for example 10 times n) or use an index that supports filtered search.
- Evaluating only the speed. An index that is 50 times faster but returns the wrong items shows up as a drop in precision@k and recall@k. Track both.
- Memory. Vectors for 100 million items at k = 64 take about 25 GB as float32. PQ or float16 storage cuts that, at some cost in accuracy.
Exercise
A catalog has 2 million items and factor size k = 64. Each request must return the top 20 items within 10 ms, and brute-force scoring takes 40 ms. Name one approach that fits the budget, and one check you should run before shipping it.
Show answer
Put the item vectors in an ANN index such as HNSW or IVF, optionally with product quantization, and retrieve a few hundred candidates for re-ranking. Before shipping, measure recall@20 of the index against exact brute-force results on a sample of real user vectors, and tune the search parameter (such as nprobe or efSearch) until recall is acceptable within the 10 ms budget.
Exercise
In the IVF code above, what happens to recall and to the fraction of the catalog scanned when you raise nprobe from 5 to 20, and why does nprobe = 100 give recall 1.00?
Show answer
Both increase. More cells are probed, so more true top-10 items are among the scanned candidates, but more vectors must be scored. With 100 cells, nprobe = 100 probes every cell, so every item is scored and the result equals the exact search.