Design a Personalized Food Delivery Home Feed Ranker
Machine LearningModel answerLast updated
Design an end-to-end ML system that ranks restaurants on a food delivery app's home screen to maximize orders and long-term user satisfaction.
Scenario
You work as a senior ML engineer at a food delivery platform. Every time a user opens the app, they land on a home feed showing a ranked list of restaurants. The ranking decision happens in under 200 ms and directly drives revenue, retention, and courier utilization.
Your task is to design the full ML system behind that ranked feed — from raw signals to what gets shown at position 1.
What to cover
Walk through each of the following. Be concrete: name models, features, and trade-offs rather than speaking in vague generalities.
-
Objectives and metrics — What are you optimizing for, and how do you measure success both offline and in production? What guardrails prevent you from gaming a metric at the expense of the user or the marketplace?
-
Problem framing as a funnel — How do you go from every restaurant on the platform down to a ranked list of ~50 in under 200 ms? Describe each stage, its input/output size, and its latency budget.
-
Candidate generation (retrieval) — What sources of candidates do you use? How do you merge them? When and why would you use a two-tower embedding model vs. a simpler heuristic?
-
Ranking model — What model architecture do you choose, what target(s) does it predict, and how do you combine multiple predicted quantities into a single ranking score?
-
Feature engineering — What user, restaurant, contextual, and cross features matter most? Which ones need to be fresh in real time?
-
Training data and labels — How do you construct training examples, handle position bias, and avoid feedback loops that entrench already-popular restaurants?
-
Cold start and exploration — How does the system behave for a brand-new user with zero order history? For a restaurant that joined the platform yesterday? How do you balance exploitation of known preferences with exploration of new options?
-
Re-ranking and business rules — After the model scores, what post-processing happens before the feed is served? Think diversity, fairness, sponsored slots, and quality gates.
-
Online serving architecture — How does the system meet the latency budget? Where does each piece live (feature store, model server, cache)? How do you keep real-time signals like ETA and surge fresh?
-
Experimentation, monitoring, and failure modes — How do you run A/B tests safely? What signals tell you the system is silently degrading? Name two or three concrete failure modes and how you'd catch them.
-
Phased rollout / MVP — If you had to ship something useful in six weeks, what would it be? What comes in phase 2 and 3?
Constraints and realities to address
- A user can only order from restaurants that deliver to their address and are open right now — this eligible set is typically 200–2,000 restaurants, far smaller than the full catalog.
- ETA, delivery fee, restaurant busyness, and courier supply change in real time.
- Items can go out of stock mid-session.
- New restaurants need exposure even before they have order history.
- Concentrating demand on a small set of popular restaurants overloads couriers in that area and hurts marketplace health.
- Sponsored placements must coexist with organic results without destroying feed quality.
Expected output
A structured verbal walkthrough (no code required, though pseudocode or schema snippets are welcome). Prioritize depth on the ranking model, feature design, and serving architecture. Show that you understand the difference between what is technically elegant and what is actually practical to build.
Hints
Hint 1
Start with the eligible set, not the full catalog. Since only 200–2,000 restaurants are deliverable to any address at any moment, retrieval is less about recall against millions of items and more about ranking well within a small, hard-filtered set. That changes how much work you need to put into candidate generation vs. ranking.
Hint 2
For the ranking model, think about why a single target like click-through rate is dangerous. Clicks, orders, basket value, cancellations, and ratings each tell you something different. A multi-task model that jointly predicts several of these is more robust than optimizing one proxy — and it lets you tune the business trade-off at score combination time rather than baking it into the label.
Hint 3
Position bias is one of the most common mistakes candidates gloss over. An impression at position 1 converts at a much higher rate than one at position 10 — not because the restaurant is better, but because it was shown first. If you train naively on impression logs, your model learns to recommend whatever was already ranked highly, reinforcing the existing order. Name at least one concrete mitiga…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and scale
Before designing anything, anchor the numbers:
- ~100M MAU, ~20M DAU, with lunch and dinner peaks around 50k feed requests/second.
- ~1M restaurants globally, but only 200–2,000 are deliverable to any given address at any time. This is the most important constraint — it makes retrieval recall a non-issue and puts pressure on ranking quality instead.
- p99 latency target: 200 ms end-to-end. The ranker gets roughly 80 ms of that budget.
- Freshness requirements are asymmetric: ETA, surge, and availability need to be current within seconds; user cuisine preferences can tolerate hourly or daily staleness.
The API surface is simple:
GET /feed?user_id&lat&lng&session_id&ts
→ [{restaurant_id, score, eta, fee, reason, slot_type: organic|sponsored}]
2. Objectives and metrics
What we're optimizing for: long-term expected value per session. A useful factored form:
score ≈ P(order | impression) × expected basket value × satisfaction multiplier
where the satisfaction multiplier penalizes predicted cancellations, late deliveries, and poor ratings. Tuning the weights on these terms is a business decision, not an ML one — do it through A/B tests, not by baking it into labels.
Offline metrics
- Retrieval: recall@k, NDCG@k
- Ranker: AUC, log-loss, calibration (predicted vs. observed conversion). Calibration matters because scores feed into business formulas alongside GMV and bid prices.
Online success metrics: session conversion rate, orders per user per week, GMV, 28-day retention.
Guardrails — metrics that gate launch regardless of primary metric gains:
- Late delivery rate and ETA accuracy
- Cancellation rate
- Feed p99 latency
- Exposure share for new and small merchants (prevents the system from starving new entrants of traffic)
- Courier utilization distribution (concentrated demand overloads a few zones)
3. Multi-stage funnel
| Stage | Input → Output | Budget |
|---|---|---|
| Eligibility filter | full catalog → ~1k open, deliverable | 10 ms |
| Candidate generation | ~1k → ~300 | 20 ms |
| Ranking | ~300 → scored list | 60 ms |
| Re-ranking | scored → final feed of ~50 | 10 ms |
Eligibility is a hard filter, not a learned signal. Remove any restaurant that is outside the delivery polygon, currently closed, paused for fraud or quality reasons, or has an ETA above the user's feasibility threshold. Use H3 cell indexing with precomputed per-cell restaurant lists, updated by a streaming availability pipeline. This step should run in a few milliseconds with no model involved.
4. Candidate generation
Because the eligible set is already small, retrieval recall is less critical than in e-commerce. Still, use multiple sources and merge them:
- Reorder heuristic: past restaurants the user has ordered from. Often the single strongest precision source.
- Cell popularity: top restaurants by order volume in the user's H3 cell over the last 7 days.
- Item-to-item collaborative filtering: restaurants frequently co-ordered by users with similar history.
- Two-tower embedding retrieval: user tower encodes history, time of day, and location; restaurant tower encodes cuisine, menu text, price, and ID. Train with in-batch negatives plus geo-local hard negatives (restaurants in the same cell that were not ordered). At serving time, do ANN search restricted to the eligible ID set.
- Trending pool: restaurants with spiking order velocity in the cell over the last hour.
- Exploration pool: new restaurants needing bootstrapped exposure.
- Sponsored candidates: from the ads auction.
Merge by taking the union, deduplicating, applying per-source caps so no single source dominates, and carrying source_id forward as a ranking feature. The ranker arbitrates the final order.
5. Ranking model
MVP: LightGBM on a single P(order | impression) target. Strong on tabular features, fast to train and serve, easy to debug. This is what you ship in week 6.
Target state: a multi-task deep model (shared-bottom or MMoE) with heads for:
- P(click)
- P(order | click)
- Expected basket value
- P(cancellation or late delivery)
- P(high rating)
Clicks are dense and regularize the sparse order signal. The multi-task setup also lets you detect when a change improves orders but tanks ratings — a failure mode a single-target model hides.
Score combination:
final_score = P(order) × GMV^α − λ × P(bad_outcome)
Tune α and λ via A/B tests; don't bake them into labels. This keeps the ML model's job clean (predict probabilities) and the business policy explicit.
Architecture details: learned embeddings for user and restaurant IDs; a sequence encoder (GRU or Transformer) over the last N orders; DCN layers for feature crosses. Real-time features are concatenated in at serving time, not baked into embeddings.
6. Features
User: order frequency and recency, cuisine and price affinity, typical basket size, reorder propensity, embedding of recent N orders.
Restaurant: rating, order volume, cuisine, price tier, prep-time distribution, cancellation/refund rate, platform age, photo quality score.
Context: hour of day, day of week, weather, home vs. work address, device type, local events and holidays.
Real-time (must be fresh within seconds): current ETA and delivery fee, surge multiplier, busy flag and queue depth, out-of-stock fraction of top items, order velocity in the cell over the last 30 minutes, in-session clicks and searches.
Cross features: user cuisine affinity × restaurant cuisine match, recency of last order at this restaurant, distance relative to the user's historical radius, price tier relative to usual spend, ETA relative to inferred ETA tolerance.
Critical practice: log the exact features served at inference time and train on those logs. Training on recomputed features causes training/serving skew that is especially bad for fast-moving signals like ETA.
7. Training data, labels, and bias
Label construction: impressions joined to orders within a session or a 1-hour attribution window. Use viewport logging — only impressions the user actually scrolled past count as negatives. Impressions that never entered the viewport are excluded.
Position bias is the most common mistake: position 1 gets more clicks than position 10 regardless of quality. Three mitigations:
- Include position as a training feature and set it to a fixed constant (e.g., position 3) at serving time.
- Inverse propensity weighting using propensity estimates from a small randomized traffic slice (1–5% of requests where ranking is randomized).
- Use both — IPS for unbiased gradients, position-as-feature as a fallback signal.
Feedback loop: popular restaurants accumulate more impressions → more orders → higher estimated P(order) → more impressions. Break it with: exploration traffic, exposure-normalized popularity features (orders per impression, not raw orders), and periodic evaluation on the randomized slice.
Training cadence: daily full retrains; near-real-time counter and embedding updates via streaming.
8. Cold start and exploration
New users: serve geo-cell popularity filtered by time of day. Use onboarding cuisine preferences and device/locale priors. In-session clicks and searches are the primary personalization signal until order history accumulates. The two-tower model's content features generalize to users with no ID embedding — fall back to zero-vector for the ID component.
New restaurants: build content embeddings from menu text and images. Borrow priors from similar restaurants nearby. Guarantee minimum exposure — reserve positions 4–6 for new entrants during the bootstrapping window, then let organic ranking take over once sufficient impression data exists.
Exploration vs. exploitation: dedicate 5–10% of feed traffic to epsilon-greedy or Thompson-sampling-driven exploration. This also serves as the randomized slice for debiasing. Track exploration separately in metrics so it doesn't pollute online evaluation of the main ranker.
9. Serving architecture
Request → Eligibility service (H3 index, streaming state) →
Retrieval service (ANN + heuristic sources) →
Feature assembly (online store + real-time joins) →
Model server (TF Serving / Triton) →
Re-ranker →
Response
- Feature store: Feast or Redis for low-latency reads of precomputed user and restaurant features. Real-time signals (ETA, surge) come from a streaming pipeline (Kafka → Flink) into a separate low-latency cache.
- Model serving: ONNX export + Triton for the deep ranker. LightGBM is served directly. Both are batched across the ~300 candidates in a single forward pass.
- Caching: eligibility lists cached per H3 cell, refreshed on availability events. User feature vectors cached with a short TTL (60 seconds). Never cache the final ranked list — session context and real-time signals make it stale immediately.
- Latency budget allocation: eligibility 10 ms, retrieval 20 ms, feature assembly 30 ms, model inference 60 ms, re-ranking 10 ms, serialization 10 ms = ~140 ms, leaving headroom for p99.
10. Re-ranking and business rules
Post-processing happens after scoring and before the response:
- Diversity: cap consecutive same-cuisine restaurants (e.g., no more than 2 in a row). Use a sliding window penalty.
- Fairness/exposure: guarantee minimum impression share for new and small merchants via a soft slot reservation.
- Quality gates: hard-filter restaurants below a quality floor (e.g., rating < 3.5 with sufficient volume) or with elevated recent refund rates.
- Sponsored slots: inject at fixed positions (e.g., position 2, 5) from the ads auction, subject to a relevance floor so a clearly irrelevant paid listing doesn't appear.
- Business boosts: temporary boosts for promotional partnerships, applied as a multiplicative modifier to the score, auditable and time-bounded.
11. Experimentation and monitoring
A/B testing: randomize at the user level. Measure primary metrics (conversion, GMV) and all guardrails simultaneously. Use CUPED or stratified assignment to reduce variance. Gate launches on guardrail non-regression, not just primary metric improvement.
Monitoring signals:
- Model score distribution drift (sudden shift often means a feature pipeline broke)
- Predicted vs. observed conversion rate (calibration drift)
- Feed latency by percentile
- Exposure share by merchant cohort (new, small, large)
- ETA accuracy vs. actuals
Common failure modes:
| Failure | Signal | Mitigation |
|---|---|---|
| Feature pipeline outage | Score distribution spike, stale timestamps in logs | Fallback to cached features + staleness flag |
| Feedback loop entrenchment | Gini coefficient of impressions rising | Exploration traffic, IPS reweighting |
| ETA/surge staleness | Predicted ETA vs. actual ETA diverging | Circuit breaker that reverts to heuristic ranking if streaming lag exceeds threshold |
| Position bias leaking into training | Ranker reproduces prior order regardless of features | Evaluate on randomized-slot holdout weekly |
12. Phased rollout
Phase 1 (weeks 1–6): Eligibility filter, reorder + popularity retrieval, LightGBM ranker on P(order) with hand-engineered tabular features, basic position-as-feature debiasing, hard quality gates. Ship this and measure.
Phase 2 (months 2–4): Add two-tower retrieval. Replace LightGBM with multi-task deep model (click + order + cancel heads). Add real-time feature joins for ETA and surge. Implement exploration slot and new-restaurant bootstrapping.
Phase 3 (months 5–8): Full IPS debiasing pipeline. Sequence encoder over order history. Fairness-aware re-ranking with exposure guarantees. Dish-level ranking within restaurant cards. Automated calibration monitoring.
Common mistakes to avoid
- Optimizing CTR instead of orders. Clicks are cheap to game — a photo of a meal can drive a click with no intent to purchase.
- Skipping position bias correction. The single most common source of silent model degradation in feed systems.
- Using recomputed features for training. ETA at training time ≠ ETA at serving time. Always log and train on served features.
- Ignoring marketplace effects. A system that recommends perfectly for individual users but concentrates all demand in two neighborhoods will break the courier supply side and cause late deliveries, which eventually destroy the metric you were optimizing.
- Launching diversity and fairness as an afterthought. These are much harder to retrofit than to build into the re-ranking layer from day one.