Designing a Restaurant Ranking System for a Food Delivery App
Machine LearningModel answerLast updated
Design an end-to-end personalized ranking system for a food delivery home feed, covering objectives, features, model architecture, evaluation, and feedback loops.
Background
You work on the machine learning team at a food delivery platform. The home screen shows users a ranked list of nearby restaurants. Your task is to design the ranking system that decides what order those restaurants appear in.
The platform connects three parties — customers, restaurants, and delivery couriers — so your system must account for all three, not just what the customer is most likely to click.
What You Need to Design
1. Objective Formulation
What is the system actually optimizing for? Define the prediction targets and explain how you combine them into a single ranking score. How do you balance short-term engagement (clicks and orders) against long-term outcomes like user retention and marketplace health?
2. Feature Engineering
Propose a concrete set of features across user, restaurant, and contextual dimensions. How do you handle new restaurants that have no engagement history? How do you avoid training-serving skew with real-time signals?
3. Model Architecture
The system must return results within 200ms end-to-end. Describe a multi-stage pipeline that fits within this budget. What model family would you use for each stage, and why?
4. Evaluation
How do you validate the system before shipping it? Define both offline metrics and online experiment metrics. Which metrics go beyond click-through rate, and why do they matter?
5. Deployment and Feedback Loops
How often do you retrain the model? How do you detect and correct position bias, where top-ranked items receive more orders simply because they appear first?
Constraints and Assumptions
- Results must be returned in under 200ms (p99).
- The candidate pool per request is roughly 500–5,000 open, in-range restaurants.
- The system must account for real-time signals: live delivery estimates, restaurant prep queues, and courier availability.
- Multi-objective optimization is required — driver availability, restaurant capacity, and user preferences all matter.
A strong answer will move through each section in order, attach approximate numbers where useful, and explicitly call out trade-offs rather than presenting one option as obviously correct.
Hints
Hint 1
Start by decomposing the problem into a funnel of separate predictions (P(click), P(order|click), P(good experience|order)) rather than collapsing everything into a single CTR target. This makes the objective more honest and easier to debug.
Hint 2
A two-stage pipeline (candidate retrieval → ranking) is standard, but explain *why* each stage exists — retrieval is about recall at low latency, ranking is about precision with richer features. Sketch a rough latency budget across the two stages.
Hint 3
Position bias is the central feedback-loop risk. Mention at least one concrete countermeasure: propensity-weighted training, randomized position experiments, or dedicated exploration traffic. Interviewers often probe here.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
This is a three-sided marketplace problem, not a standard recommender. A good solution makes that explicit early: optimizing purely for customer clicks can starve new restaurants of exposure, overwhelm a popular kitchen, or burn out couriers during surges. The ranking system needs to serve all three parties simultaneously.
Start by stating your scale assumptions out loud:
- ~20M daily active users, ~3 feed loads each, so around 60M requests/day (~700 QPS average, 5–10k QPS at peak meal times).
- ~500–5,000 open, in-range restaurants per request after hard geo/availability filters.
- 200ms p99 budget. A reasonable breakdown: 30ms retrieval, 40ms feature fetch, 50ms ranking model, 20ms re-ranking and business rules, remainder for network and slack.
1. Objective Formulation
Avoid a single CTR target. CTR alone rewards clickbait thumbnails and ignores whether the order actually goes well. Instead, model the funnel as three separate predictions:
- pCTR — probability of a click given an impression
- pCVR — probability of an order given a click
- pGood — probability of an on-time delivery, no cancellation, and a rating ≥ 4 given an order (a proxy for long-term retention)
Combine them into a per-item utility score:
U = pCTR · pCVR · (1 + α·pGood) · V − β·ETA_penalty − γ·capacity_penalty
- V is a value signal like normalized basket size or contribution margin. Keep its weight low or the feed drifts toward expensive restaurants.
- ETA_penalty comes from a separate predicted delivery-time model, not a static lookup.
- capacity_penalty activates when a restaurant's prep queue or local courier density is saturated.
Tune α, β, γ through online experiments against a north-star metric such as orders per user over 28 days. Diversity and fairness goals belong in the re-ranking stage rather than baked into this formula — that separation keeps the ranker interpretable and lets you adjust business rules without retraining.
2. Feature Engineering
| Category | Examples |
|---|---|
| User | Cuisine affinity vector, price sensitivity, reorder rate, recent sessions (last 1h / 24h / 30d), dietary filters, user embedding |
| Restaurant | Historical CTR/CVR (smoothed), rating, cuisine, price tier, menu and photo embeddings, prep-time distribution, cancellation rate, active promotion |
| Context | Hour and day of week, meal period, weather, home vs. work location, distance, live ETA, delivery fee, surge multiplier, courier supply/demand in the local geo cell |
| Cross features | User × cuisine affinity, has-ordered-here-before, days since last visit, distance × user's revealed distance tolerance |
Real-time features are critical. Live ETA, prep queue depth, and courier availability come from a streaming pipeline (something like Kafka → Flink → Redis). Log features at serving time and train on those logged values to avoid training-serving skew — this is a common failure mode.
Cold start for new restaurants: use content features (cuisine, menu embeddings, price tier) so the model can generalize from similar restaurants. Apply Bayesian smoothing to rate features: CVR_smoothed = (orders + k·prior) / (clicks + k), where the prior is the city × cuisine average. Reserve a small slice of traffic for exploration (see section 5).
Cold start for new users: fall back to context and location-based popularity until enough session signals accumulate.
3. Model Architecture
Stage 1 — Candidate retrieval (thousands → ~500)
Apply hard filters first: open now, within delivery range, not paused. Then merge several retrieval sources:
- Two-tower model (user tower + restaurant tower, ANN search within the geo shard)
- Reorder history
- Popular-nearby for the current time window
- Exploration and new-restaurant buckets
- Sponsored slots
Using multiple sources protects recall if any one source degrades.
Stage 2 — Ranker (~500 → scored)
A multi-task deep model (MMoE or a shared-bottom network with separate heads for pCTR, pCVR, pGood) handles the multi-objective setup naturally. Add a sequence attention layer over the user's recent order history for personalization. In v1, a well-tuned GBDT (e.g., LightGBM) is a strong and fast baseline worth running before investing in the deep model. Batch-score all 500 candidates in a single call, targeting ~50ms.
Stage 3 — Re-ranking and constraints
Assemble the utility score U, then apply:
- Diversity (e.g., MMR, or cap 2 restaurants of the same cuisine in the top 6)
- Capacity throttles
- Promotion and sponsored-slot insertion
- Carousel and layout logic
4. Evaluation
Offline: use time-based splits (train on weeks 1–4, evaluate on week 5). Metrics: per-head AUC, log-loss, and calibration (predicted vs. observed rate ratio). Calibration matters because the head outputs are multiplied together — an uncalibrated pCVR head inflates or deflates the final score systematically. Also track NDCG@10 and Recall@K (is the eventual order in the top 500 retrieved candidates?). Slice everything by city, new vs. returning users, new restaurants, and meal period.
Online: standard A/B test with user-level randomization, but note the leakage risk — couriers are a shared resource, so a test arm that drives more orders also affects delivery times in the control arm. For supply-sensitive changes, use switchback or geo-cluster experiments instead. Use interleaving for fast head-to-head ranker comparisons.
Metrics beyond CTR:
- Primary: orders per session, orders per user per week, GMV
- Experience: delivery time, late-delivery rate, cancellation rate, in-session time-to-first-order
- Long-term: D7/D28 retention, order frequency
- Marketplace health: restaurant exposure Gini coefficient, share of orders to new restaurants, courier utilization, prep-time overruns
- Guardrails: p99 latency, error rate, fallback rate
5. Deployment and Feedback Loops
Update cadence: retrain the ranker daily on a rolling window (e.g., last 30 days) to capture seasonal shifts. Refresh real-time features continuously. Use shadow scoring to validate new model versions before promoting them.
Position bias is the central feedback-loop risk: items shown at the top get more clicks, which generates more positive training signal, which pushes them further up, regardless of true quality. Countermeasures:
- Propensity-weighted training: log the serving position and model propensity at impression time, then downweight or correct labels using inverse propensity scoring during training.
- Randomized position experiments: occasionally shuffle the ranked list for a small traffic slice to collect unbiased signal.
- Exploration traffic: reserve ~5–10% of requests for exploration (ε-greedy or Thompson sampling) to give new restaurants a fair chance and generate off-policy data.
Common mistakes to avoid:
- Treating this as a single-objective CTR problem and ignoring restaurant or courier constraints.
- Using live ETAs at training time but static ETAs at serving time — a major source of skew.
- A/B testing supply-side changes with user-level randomization, which produces biased results due to shared courier pools.
- Optimizing calibration only at the aggregate level; a model can be well-calibrated overall but badly miscalibrated for new restaurants or sparse cuisines, which hurts cold-start behavior.