Building a Ranking System for E-Commerce Search
Machine LearningModel answerLast updated
Design an ML system that orders products by relevance for marketplace search, covering objective definition, training data, features, model architecture, and evaluation.
You're designing a machine learning system for an online marketplace that needs to order products by relevance when users search.
Given a search query, user information, and several hundred candidate products (already retrieved from the catalog), your system must produce a ranked list where the best matches appear at the top.
Walk through your end-to-end approach:
- How would you frame this as an ML problem, and what objective would you optimize?
- What training data would you collect, and how would you construct labels from user behavior?
- What features would you extract, and how would you handle new products with no interaction history?
- Which model architectures would you consider, and what are the trade-offs?
- How would you train the model while avoiding common pitfalls like position bias?
- How would you measure success both before and after deployment?
Focus on practical considerations: data quality issues, computational constraints at serving time, and connecting offline metrics to business outcomes.
Hints
Hint 1
User clicks are biased toward higher positions—how can you separate true relevance from placement effects?
Hint 2
Purchases are sparse but valuable; clicks are common but noisy. Consider combining multiple signals into your training objective.
Hint 3
New products have no click history. What other signals can predict their relevance, and how would you encourage the system to explore them?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: E-Commerce Ranking System Design
This problem tests whether you can translate a business goal into a trainable ML system while navigating real-world data issues. A strong response covers problem formulation, label construction, feature engineering, model selection, training strategy, and evaluation—with specific attention to bias correction and cold-start handling.
1. Problem Formulation and Scope
Begin by clarifying what "relevant" means and understanding constraints:
Business objective: Maximize long-term value—gross merchandise volume (GMV), repeat purchases, and customer satisfaction—while maintaining a healthy merchant ecosystem. Optimizing only for immediate clicks can surface clickbait or low-quality items.
Ranking context: Assume we're ranking search results (query-driven). The upstream retrieval system (typically BM25 plus neural retrieval) has already narrowed millions of products down to 500–1000 candidates. Our ranker must score these in under 50ms at the 99th percentile.
Scale assumptions: ~100M products in catalog, ~50M daily active users, peak traffic around 50k queries per second. State these numbers to show you're thinking about feasibility.
2. Training Data and Label Construction
Data sources:
- Impression logs: query text, user ID, session context, list of products shown with their positions, timestamp, and device type
- User interactions: clicks, dwell time after click, add-to-cart events, purchases, and post-purchase signals like returns or reviews
- Catalog metadata: product titles, descriptions, images, category hierarchy, price, inventory status, merchant info, historical ratings
- User profiles: purchase and browsing history, location, language, inferred preferences
Label strategy (critical part):
Raw clicks are misleading—items at the top get clicked more regardless of quality. Build graded relevance scores from implicit feedback:
| User Action | Relevance Score |
|---|---|
| Impression, no click | 0 |
| Click with brief visit (<10 sec) | 0.5 |
| Click with extended engagement | 1 |
| Added to cart | 2 |
| Completed purchase | 3 |
| Purchase followed by return | 1 (downgrade) |
Handling position bias: Items shown first receive inflated click rates even when less relevant. Three approaches:
-
Inverse propensity scoring (IPS): Estimate the probability that an item at position k gets examined, then reweight training examples by 1/propensity. Estimate propensities from a small stream of randomized rankings.
-
Position as training-time feature: Include rank position as a model input during training but set it to a neutral value (e.g., position 5) at serving time. The model learns to discount position effects.
-
Negative sampling strategy: Use "skip-above" negatives—products ranked above a clicked item that the user scrolled past. Don't treat unseen products (below the fold) as hard negatives.
Addressing data sparsity: Purchases are rare. Use multi-task learning with separate prediction heads:
- P(click | impression)
- P(purchase | click)
- P(add-to-cart | impression)
Combine them into a composite score: final_score = P(click) × P(purchase|click) × price^α, where α balances conversion rate against revenue.
3. Feature Engineering
Query-product matching features:
- Text similarity: BM25 score, embedding cosine similarity between query and product title/description
- Exact and partial token matches
- Category alignment (query intent → product category)
- Attribute match (if query mentions "red" or "large," does the product match?)
Product quality and popularity:
- Historical CTR and conversion rate, aggregated over multiple time windows (1 day, 7 days, 30 days) and smoothed with Bayesian priors
- Price, discount percentage, and price competitiveness within category
- Review rating, review count, and recent rating trend
- Inventory level and shipping speed
- Product age (recency bonus for new items)
- Image quality score (derived from a separate model)
User features:
- Affinity to product category, brand, and price tier (learned from history)
- Embedding similarity between user profile and product
- Count of prior impressions for this specific product (diminishing returns)
- Recent session behavior: last 5 clicked categories, average dwell time
Contextual features:
- Device type, time of day, day of week
- Geographic location and locale
- Seasonal signals (e.g., winter clothing in December)
Merchant features:
- Fulfillment reliability and return rate
- Merchant tenure (helps with cold start for new sellers)
Cross features:
- User's typical price range × product price (capturing affordability)
- User's past brand engagement × product brand
Avoiding leakage: Engagement statistics must be computed from data that existed before the current impression timestamp. Use point-in-time feature stores to enforce temporal consistency.
4. Model Architecture
Use a staged progression:
Stage 1: Baseline heuristic
Combine text relevance score (BM25) with popularity (smoothed CTR). This establishes a floor and provides a production fallback.
Stage 2: Gradient-boosted decision trees (GBDT)
LightGBM with LambdaMART loss. Advantages:
- Strong performance on tabular features
- Fast inference (critical for latency)
- Interpretable feature importance
- Directly optimizes ranking metrics like NDCG
This is often the first production model.
Stage 3: Deep neural ranking model
Architecture like Deep & Cross Network (DCN-v2) or DLRM, with multi-task output heads (using Multi-gate Mixture-of-Experts, MMoE, to share representations):
- Handles high-cardinality categorical features (product IDs, user IDs) via embeddings
- Incorporates sequence features (transformer over recent user clicks)
- Fuses text and image embeddings from pretrained encoders
Use pointwise losses (cross-entropy) for each task head to maintain calibrated probabilities, plus a listwise ranking loss (LambdaRank or ListMLE) computed over entire result sets.
Stage 4: Optional re-ranking layer
A small transformer that takes the top 50 candidates from the main ranker and reorders them considering:
- Diversity (don't show five similar items consecutively)
- Merchant fairness (avoid monopolizing results with one seller)
- Business rules (remove out-of-stock items, blend in sponsored ads)
5. Training Strategy
Data split: Split by time, not randomly. Train on weeks 1–4, validate on week 5, test on week 6. Random splits leak future popularity into training and overestimate performance.
Sampling and weighting:
- Downsample frequent negative examples (impressions with no engagement)
- Apply IPS weights to correct position bias
- Downweight power users and filter bot traffic
- Group examples by query or session for listwise loss computation
Retraining frequency: Retrain the model daily to capture trend shifts. Update fast-moving features (recent CTR) in near real-time via streaming aggregation. Consider online learning for extremely time-sensitive signals.
Cold-start handling:
- For new products: rely on content features (text, images, category), use category-level CTR priors, and add an exploration bonus (e.g., Thompson sampling or upper confidence bound boost) to encourage exposure.
- For new users: use collaborative filtering based on coarse demographics or location, and emphasize popular items until behavior data accumulates.
6. Offline Evaluation
Primary metrics:
- NDCG@10 with graded relevance labels (the most important metric for ranking quality)
- MRR (Mean Reciprocal Rank) of the first purchased item
- Recall@20 of eventually-purchased products
Evaluation dataset: Use held-out data from the time-split test period. Crucially, include a randomized exploration set where rankings were perturbed during serving—this provides unbiased labels for counterfactual evaluation.
Slice analysis: Compute metrics separately for:
- Head vs. tail queries (by frequency)
- New vs. returning users
- New vs. established products
- Mobile vs. desktop
- Small vs. large merchants
An overall gain can mask regressions in important subgroups.
Calibration checks: For probabilistic heads, plot predicted vs. observed rates. Miscalibration breaks the multi-task score combination.
Human evaluation: Maintain a curated set of query-product pairs labeled by human raters or an LLM judge for relevance. This catches when the model is gaming biased engagement metrics (e.g., boosting clickbait).
7. Online Evaluation (A/B Testing)
Experiment design: User-level randomization. Run for at least one week to capture weekly seasonality. Ensure even distribution across user cohorts.
Primary business metrics:
- GMV per session
- Conversion rate (purchases / searches)
- Revenue per user
Secondary engagement metrics:
- Click-through rate
- Add-to-cart rate
- Zero-result rate (searches with no clicks)
Guardrail metrics (prevent unintended harm):
- Latency at p50, p95, p99
- Product return rate (quality check)
- Query reformulation rate (are users unsatisfied and refining searches?)
- Merchant concentration (Gini coefficient—don't monopolize exposure)
- Revenue distribution to new/small merchants
- User complaint rate
Advanced technique: Interleaving—blend results from two models in the same session and measure which items get more engagement. More sensitive than A/B testing for detecting ranking improvements.
8. Common Pitfalls and Mitigations
Pitfall: Training on biased logged data makes the model replicate the old ranker's mistakes.
Mitigation: Continuous exploration traffic (1–5% randomized), IPS weighting, and human relevance labels.
Pitfall: Overfitting to short-term clicks at the expense of purchases or satisfaction.
Mitigation: Multi-task learning with purchase and long-term retention signals, plus guardrail metrics in online tests.
Pitfall: New products get stuck at the bottom (rich-get-richer dynamics).
Mitigation: Explicit exploration bonuses, content-based features, and merchant fairness constraints.
Pitfall: Model complexity causes p99 latency spikes.
Mitigation: Cascade architecture (fast first-pass ranker, expensive re-ranker for top-k), model quantization, and precomputed embeddings cached in serving infrastructure.
Summary
A production-grade e-commerce ranking system requires:
- Careful label design to extract relevance from noisy implicit feedback while correcting position bias
- Rich feature engineering spanning text, user history, product attributes, and context, with temporal consistency
- Multi-stage modeling starting with GBDT and evolving to deep multi-task architectures as data and infrastructure mature
- Robust offline evaluation on time-split, unbiased held-out data with slice-level analysis
- Comprehensive online testing measuring business outcomes and guarding against unintended consequences
The key insight: ranking is not just about predicting clicks—it's about balancing short-term engagement, long-term business value, and ecosystem health, all under strict latency constraints.