What You'll Learn
- 1Split a recommender into candidate generation, ranking, and re-ranking with a recall target per stage
- 2Estimate the memory traffic of exact versus approximate nearest neighbor retrieval
- 3Budget end-to-end latency across retrieval, scoring, and re-ranking
- 4Size user and item embedding storage for a catalog at scale
Why This Matters
Recommendation systems drive engagement and revenue for major platforms:
- Netflix: 80% of content watched comes from recommendations
- Amazon: 35% of revenue from recommendation engine
- YouTube: 70% of watch time from recommendations
- Spotify: Discover Weekly has 40M+ users
âšī¸
A well-designed recommendation system can increase user engagement by 20-30% and revenue by 10-15%.
Recommendation System Architecture
Collaborative Filtering
Collaborative filtering discovers patterns in user-item interactions to make recommendations. The approach constructs a user-item matrix from interaction data (ratings, clicks, purchases) and applies matrix factorization (SVD) to decompose it into user and item latent factors. Predictions are made by computing the dot product between user and item factors. Top-N recommendations are generated by scoring all items for a user and selecting the highest-scoring ones.
Two-Tower Model
Two-tower models use separate neural networks (towers) to embed users and items into a shared embedding space. The user tower processes user features, and the item tower processes item features. Similarity is computed as the cosine similarity between embeddings, scaled by a temperature parameter. This architecture enables efficient candidate retrieval via approximate nearest neighbor search.
The training loop uses binary cross-entropy loss to learn embeddings where similar user-item pairs have high similarity scores.
Candidate Generation with FAISS
FAISS (Facebook AI Similarity Search) provides fast approximate nearest neighbor retrieval for candidate generation:
- IndexFlatIP: Exact inner product search for small-to-medium datasets
- IndexHNSWFlat: Hierarchical Navigable Small World graph for approximate search at scale
- Normalization: L2-normalize embeddings before indexing for cosine similarity
- Retrieval: Query the index with user embeddings to retrieve top-N candidate items
Ranking Model
The ranking model scores and orders candidates using gradient-boosted trees (LightGBM):
- Feature Preparation: Merge user, item, and interaction features; create derived features (user-item interaction, context score)
- Training: Train LightGBM with binary classification objective, using early stopping on validation data
- Ranking: Score candidates and sort by predicted relevance
Hybrid Recommendation System
A hybrid recommender combines multiple strategies for robust recommendations:
- Candidate Generation: Gather candidates from collaborative filtering, content-based, and two-tower models
- Ranking: Score all candidates using the ranking model
- Re-ranking: Apply diversity, freshness, and business rules to the final list
This approach leverages the strengths of each method while mitigating their individual weaknesses.
The Funnel Is a Recall Budget
A recommender narrows 10 million items to 1,000 candidates, scores them down to 100, and shows 10. Each stage can only lose items, so end-to-end recall multiplies:
With candidate recall at 0.95, ranking recall at 0.97, and re-ranking recall at 0.99, the funnel delivers of the relevant items the user would have engaged with. Drop candidate recall to 0.80 and the same downstream stages yield , a 16 percent relative loss that no ranking model can recover, because it never sees those items. This is why candidate generation gets the simpler, faster model and the ranking stage gets the capacity: recall is decided at the top, precision is decided at the bottom.
Retrieval Cost: Exact Versus Approximate
Exact nearest neighbor over items with -dimensional float32 embeddings touches:
That is 5.12 GB of memory traffic per query. At an effective 50 GB/s that is about 100 ms of pure bandwidth, before a single multiply, which already blows a 100 ms budget on one query alone. An HNSW index instead probes roughly neighborhoods: with a search width of 100, it reads about 100 x 128 x 4 = 51 KB, a 100,000x reduction, at the cost of 1 to 3 percent recall loss. Set the ANN parameters from a recall-at-100 measurement against the exact index on a held-out query set, not from a blog default.
Latency Budget Across the Stages
With 20 ms for ANN retrieval, 1,000 candidates each scored in 0.04 ms by a LightGBM model, and 10 ms to apply business rules and diversity in re-ranking, the request costs ms. That leaves 30 ms of a 100 ms budget for feature fetch, network, and serialization, and it shows which lever matters: doubling candidates to 2,000 costs 40 ms, while doubling the ANN search width costs only a few. Grow the candidate set only when offline recall curves say the extra items are worth the linear score cost.
Storing the Embeddings
User and item towers produce vectors that must live somewhere:
A hundred million users at 128 dimensions is 51.2 GB of user embeddings alone, before items, so it does not fit in one machine's memory alongside the index. Shard by user ID across serving pods with consistent hashing, or keep the embedding table in a memory-mapped store and accept a 2 to 5 ms lookup. Item embeddings for 10 million items take only 5.1 GB and belong inside the ANN index on GPU.
Interview Q&A
âšī¸
Q: How do you handle the cold start problem for new users?
Answer:
- Content-Based: Use item features for initial recommendations
- Popularity-Based: Recommend popular items initially
- Onboarding: Ask users for preferences
- Transfer Learning: Use similar user patterns
- Contextual Bandits: Explore and exploit
A cold start handler checks for user history, falls back to content-based recommendations if features are available, and ultimately returns popular items as a baseline. Exploration replaces a fraction of recommendations with random popular items to discover new preferences.
âšī¸
Q: How do you evaluate recommendation quality?
Answer:
| Metric | Description | Target |
|---|---|---|
| Precision@K | Relevant items in top-K | >0.3 |
| Recall@K | Coverage of relevant items | >0.5 |
| NDCG | Ranking quality | >0.4 |
| Diversity | Recommendation variety | >0.6 |
| Novelty | Surprise factor | >0.3 |
| Coverage | Item catalog coverage | >0.7 |
âšī¸
Q: How do you handle scalability in recommendation systems?
Answer:
- ANN Indexing: Use FAISS for fast retrieval
- Feature Caching: Cache user/item features
- Model Compression: Quantize models for faster inference
- Distributed Computing: Use Spark for batch processing
Common Mistakes
Tuning the ranking model while candidate recall is the bottleneck
Fix: Measure recall-at-100 per stage first: 0.80 candidate recall caps the whole funnel at 0.768 no matter how good the ranker is.
Serving user embeddings from a single node
Fix: Shard the embedding table by user ID or memory-map it, since 100M users at 128 dims is 51.2 GB before items.
Picking ANN parameters from a tutorial
Fix: Measure recall against exact search on your own query set and choose search width from that curve.
Best Practices
- Give candidate generation the fast simple model and the ranking stage the compute budget
- Track offline recall at each stage weekly, because a silent drop upstream never shows up in online CTR until it is large
- Always keep a popularity baseline in the experiment so every new model is measured against a floor, not a memory
Key Takeaways
- Funnel recall multiplies: 0.95 x 0.97 x 0.99 = 0.913, and weak candidates cap the result at 0.768
- Exact search over 10M items at 128 float32 dims moves 5.12 GB per query; HNSW with width 100 moves about 51 KB
- The stage budget is 20 ms retrieval + 1,000 x 0.04 ms scoring + 10 ms re-rank = 70 ms of a 100 ms target
- 100M users at 128 float32 dimensions is 51.2 GB of embeddings, so the table has to be sharded or memory-mapped
Frequently Asked Questions
How many candidates should stage one retrieve?
From the recall curve, not from habit. Score recall at 100, 500, 1,000, and 5,000 candidates against your labeled data and pick the smallest number that meets the recall target, because ranking cost grows linearly with candidate count. In the worked budget, going from 1,000 to 2,000 candidates costs 40 extra milliseconds while typically buying only a point or two of recall.
What is the actual difference between cold start for users and for items?
New users lack behavioral signal, so you fall back to context, onboarding preferences, and popularity, and you can explore because you have little to lose. New items lack interactions but have content features, so a content or attribute model can rank them immediately and the system should deliberately expose them to the right audience. Items usually self-heal within hours; users take days unless you ask them questions up front.
Do I need deep learning for recommendations?
Only after the funnel is healthy. Two-tower models shine when the catalog is large enough that retrieval must be learned, and gradient-boosted trees usually win the ranking stage on structured features. A collaborative filtering baseline plus a LightGBM ranker with good features is a strong, debuggable system that many teams never outgrow; the deep model earns its complexity when recall or personalization metrics say the baseline has plateaued.
Interview Questions
Q1: Where do you attack first when recommendation quality drops?
Decompose recall by stage. If recall-at-100 from candidate generation fell from 0.95 to 0.80, downstream metrics will fall by about 16 percent relative no matter what the ranker does. Check the index freshness, embedding model version, and traffic mix before touching the ranking model.
Q2: How do you serve 100M user embeddings without a single huge node?
Total size is 100M x 128 x 4 bytes = 51.2 GB, so shard by user ID with consistent hashing across pods, keeping item embeddings inside the ANN index at 5.1 GB for 10M items. Alternatively memory-map the table and budget 2 to 5 ms for lookup inside the retrieval stage.
Q3: How do you evaluate a recommender before shipping?
Offline, measure recall at each funnel stage, NDCG on held-out interactions, and coverage against a popularity baseline. Online, run an A/B test on the business metric that matters, with the popularity floor always in the experiment, and guardrail on latency and catalog coverage so a CTR win does not hide a diversity loss.
Quiz
Next Steps
- Module 8: Search Ranking System - Learn query understanding and ranking
- Module 9: Fraud Detection System - Apply ML to fraud detection
- Practice: Design a recommendation system for an e-commerce platform
Continue to Search Ranking System ->