Designing a Ranked Product Recommender with Role and Context Rules
Machine LearningModel answerLast updated
Design an ML pipeline that builds personalized ranked product lists, using collaborative filtering and ranking models while respecting user role, context, and business constraints.
Scenario
Your team has decided to launch a product recommendation feature in a shopping app. Every user should see their own ranked list of products, and the list must reflect who the user is and what they are doing at that moment.
Question
- Which machine learning techniques would you use to produce a personalized, ranked list of products for each user? Explain why you chose each one.
- How would you account for the user's role (for example consumer vs. business buyer, or region and eligibility), the context of the request (device, time, session intent), and other constraints (stock, diversity, sponsored slots) when deciding which items to show?
What a good answer covers
- The overall pipeline and its stages, not just a single model
- How you would train, serve, and evaluate it
- How you would deal with new users and new items
- Trade-offs and failure modes
State your assumptions about scale and available data before you start.
Hints
Hint 1
Think in stages: a cheap step that narrows a huge catalog to a manageable candidate set, a richer model that scores those candidates, and a final step that adjusts the list as a whole.
Hint 2
Separate hard rules (eligibility, stock, legal restrictions) from soft signals (preferences, device, session intent). Decide which stage of the pipeline is the best home for each.
Hint 3
A model trained only on what it previously showed will keep reinforcing itself. Consider how exploration, logged propensities, and cold-start fallbacks address this.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing and assumptions
I would first clarify the setup, then state assumptions:
- Scale: about 10M users, about 1M products, and a p99 latency target of roughly 150 ms per request.
- Data: mostly implicit feedback (views, clicks, add-to-cart, purchases), not explicit ratings.
- Objective: purchases or revenue as the main metric, with guardrails on diversity, return rate, and complaints.
- Constraints: some are hard (eligibility by role or region, age gating, stock) and some are soft (preferences, diversity, sponsored placements).
The central point is that recommendation is a multi-stage funnel, not one model: retrieve, rank, then re-rank under constraints.
Stage 1: Candidate generation (recall)
Goal: cut about 1M items to about 1,000 cheaply.
Collaborative filtering with matrix factorization. Learn a vector per user and per item so that affinity is the dot product. For implicit data, use weighted ALS: observed interactions get target 1, everything else 0, and a confidence weight such as 1 + α·count makes heavy interactions matter more. It captures "people like you bought this" with no content features.
Two-tower retrieval generalizes this:
- The user tower takes ID, role, recent history (pooled or via a small transformer), and context.
- The item tower takes ID, category, text and image embeddings, and price.
- Train with in-batch or sampled negatives and correct for sampling bias toward popular items (log-Q correction).
- Because the item tower uses content, a brand-new item still gets an embedding.
Serving: precompute item embeddings into an ANN index (HNSW or IVF-PQ via FAISS or ScaNN). Compute the user embedding at request time and fetch the top K in a few milliseconds.
Extra sources merged into the pool: item-to-item co-visitation, trending in segment, recently viewed, and popular-in-role or popular-in-region for users with little history.
Stage 2: Ranking (precision)
Score the roughly 1,000 candidates with a richer model, either gradient-boosted trees or a deep model with feature crosses (DCN-v2, DeepFM, DLRM).
Features:
- User: role, tenure, spend tier, category affinities
- Item: price, margin, freshness, rating, stock
- User-item: retrieval score, past interactions with the brand or category
- Context: device, time of day, location, session intent, current page
Objective choices:
- Pointwise: calibrated P(click) or P(purchase) with logistic loss. Simple and gives usable probabilities.
- Pairwise (BPR, RankNet): optimizes order of positive over negative.
- Listwise (LambdaMART, softmax loss): targets NDCG directly.
In practice I would use a multi-task model with heads for click, add-to-cart, purchase, and return, then blend them, for example:
score = w1·P(click) + w2·P(purchase)·price − w3·P(return)
The weights are tuned through online experiments. Context enters as features, so the model can learn interactions such as "business buyers on desktop in working hours favor bulk SKUs."
Stage 3: Role, context, and constraints
Place each constraint where it is cheapest and most reliable.
| Constraint | Example | Where |
|---|---|---|
| Hard eligibility | Role-restricted items, regional legality, age gating, out of stock | Metadata filter at retrieval, re-checked after ranking |
| Soft preference | Role, device, session intent | Features in both towers and the ranker |
| List-level goals | Diversity, max per brand, sponsored slots, seller fairness | Re-ranking |
| Global allocation | Scarce inventory or promo budget | Constrained optimization |
Re-ranking: use MMR or a determinantal point process to trade relevance against redundancy, and apply business rules as slot constraints. Keep this layer configurable so product teams can change rules without retraining.
Scarce items: if many users all get the same limited-stock deal under per-user top-K, it is over-assigned. Solve an assignment problem (LP or min-cost flow), or add a penalty to an item's score that grows as its capacity fills.
Rule of thumb: never rely on a learned model for hard constraints. Compliance rules must be deterministic filters, applied at retrieval and again at the end.
Stage 4: Exploration
A ranker trained only on its own output underexplores new items and niche users. Mitigations:
- A contextual bandit (LinUCB or Thompson sampling) for a few exploration slots or new-item boosts.
- Log propensities with every impression so you can do off-policy evaluation (IPS, doubly robust) and debias training data.
Serving architecture
- Offline (daily/hourly): train two-tower and ranker, rebuild the ANN index, compute co-visitation tables, and precompute lists for low-traffic users into a key-value store.
- Nearline: a streaming pipeline (Kafka into Flink) refreshes the feature store with recent clicks, session embeddings, and inventory.
- Online path: features, then user tower, then ANN and other sources, then eligibility filter, then ranker, then re-ranker, then log impressions and propensities.
- Latency budget: retrieval about 20 ms, ranking about 50 ms, re-rank about 10 ms.
- Fallback: on timeout, serve cached or popular-in-segment lists.
Cold start
- New users: use role, region, and onboarding choices to serve popular-in-segment lists; session-based models adapt after a few clicks.
- New items: rely on content embeddings in the item tower, plus a short exploration boost through the bandit.
Evaluation
- Offline: Recall@K for retrieval; NDCG, MAP, and calibration (log loss) for ranking. Use time-based splits to avoid leakage, and slice by role, region, and new vs. returning users.
- Online: A/B test on conversion or revenue per session, with guardrails on diversity, return rate, latency, and complaints. Watch for novelty effects and run long enough to see repeat behavior.
Common mistakes
- Treating the system as one model rather than a funnel.
- Random train/test splits that leak future information.
- Enforcing hard constraints only through learned penalties.
- Ignoring popularity bias, so the list collapses to bestsellers.
- Optimizing clicks alone, which promotes clickbait items that get returned.
- No exploration or logged propensities, which creates a self-reinforcing feedback loop.
Trade-offs to mention
Matrix factorization is simple and strong but weak on cold start; two-tower models handle content and context at higher training cost. Pointwise ranking is easy to calibrate, listwise is better for ordering. Per-user greedy lists are fast but ignore global inventory; constrained optimization fixes that at added complexity.