Build a Nearby-Restaurant Ranking Pipeline for an App Homepage
Machine LearningModel answerLast updated
Design a sub-100ms ML pipeline that picks and ranks open, deliverable restaurants for each user's homepage carousel, covering retrieval, ranking, cold start, and evaluation.
You are building the personalized carousel at the top of a meal-delivery app's home screen. For each user, it should show the restaurants they are most likely to order from right now.
Requirements
- Latency: the whole request must finish in under 100 ms (p99).
- Eligibility: every restaurant shown must be currently open and accepting orders, and a courier must be able to reach the user's location (inside the delivery zone or radius).
- Scale: millions of daily active users, tens of thousands of restaurants, and heavy request throughput with a dinner-time peak.
- Business goals: relevance alone is not enough. The ranking should also consider delivery fees, delivery-time estimates, and the capacity of the courier fleet.
What to cover
- End-to-end architecture: how a request flows to a final ranked list, including a latency budget per stage.
- Candidate generation: how you use the spatial constraint to shrink the restaurant pool, and which retrieval strategies you combine.
- Ranking: model choice, training labels, features (user history, restaurant popularity, time of day, logistics), and how you handle new users and new restaurants.
- Evaluation: offline and online metrics, plus guardrails.
State your scale assumptions, discuss the main trade-offs, and be explicit about what you would ship first versus later.
Hints
Hint 1
Start with the constraint: after filtering by delivery zone and open status, a user typically has only hundreds to a couple thousand eligible restaurants. How does that change your retrieval design (do you even need a global ANN index)?
Hint 2
Treat eligibility as a hard filter before any model runs, and split the 100 ms budget across stages (filter, retrieval, feature fetch, ranking, re-ranking, headroom) so each component has a number to hit.
Hint 3
Think about what the ranker should optimize: expected orders and value per impression minus a logistics cost, not just CTR. Then think about position bias in logged data, cold start for new users and new restaurants, and marketplace guardrails such as ETA and courier utilization.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The difficulty is not "build a recommender" but doing so under three marketplace-specific pressures:
- Hard constraints: a great restaurant that is closed or out of range is worth nothing.
- A tight latency budget.
- Two-sided effects: recommendations move demand onto a shared courier fleet.
So I would build a constrained multi-stage funnel and optimize expected orders and value, not clicks.
Assumptions and scale
- About 30M DAU, ~3 homepage loads each: ~90M requests/day, ~1K QPS average, ~10K QPS at dinner peak.
- About 100K restaurants nationally, but a user's delivery radius (roughly 3-8 km) leaves only ~200-2,000 eligible ones. Geography does most of the pruning for us.
- Output: 10-20 ranked restaurants.
Architecture and latency budget
Request -> Eligibility filter (~1K) -> Multi-retriever union (~300)
-> Feature hydration -> Ranker -> Re-ranker/rules -> Top 20 + impression log
| Stage | Budget |
|---|---|
| Geo + open/ETA filter | ~10 ms |
| Retrieval | ~15 ms |
| Feature fetch | ~15 ms |
| Ranking | ~30 ms |
| Re-rank + rules | ~10 ms |
| Network/serialization headroom | ~20 ms |
Every response carries a request_id that is logged with each impression, so impressions can be joined to clicks and orders for training.
Eligibility and candidate generation
Eligibility is a hard filter, not a feature.
- Convert the user's coordinates to a hexagonal grid cell (for example H3 at resolution 8). Look up a precomputed list of restaurants that deliver to that cell. This is a key-value lookup, refreshed when zones change.
- Intersect with the real-time "open and accepting orders" set held in a fast store such as Redis.
- Drop restaurants whose estimated delivery time exceeds a cap (say 60 minutes).
Hexagonal cells have uniform neighbor distances, which makes expanding the radius by rings clean, unlike geohash.
Retrievers, run in parallel and unioned (cap ~300):
- Two-tower embeddings: user and restaurant towers trained on orders. With only ~1K eligible restaurants, brute-force dot products take a few milliseconds, so no global ANN index (and no geo-mismatch issue) is needed.
- Reorder retriever: the user's previous restaurants that are open now. Repeat orders are a large share of volume.
- Local popularity: top restaurants in the cell for this hour and weekday.
- Exploration pool: new or under-exposed restaurants.
Ranking
Model. Ship a gradient-boosted tree baseline first: fast, strong on tabular data, easy to debug. Later move to a multi-task neural network with shared layers and heads for P(click), P(order | click), and expected order value. Combine:
score = P(click) * P(order | click) * E[value] - lambda * cost(distance, ETA)
Tune the weights through online experiments.
Features
| Group | Examples |
|---|---|
| User long-term | embedding, cuisine affinities, price tier, order frequency |
| User real-time | session clicks/searches, cart state, recent app opens |
| Restaurant | rating, conversion rate, popularity by hour, prep time, price tier |
| User x restaurant | past orders, days since last order, cuisine match, tower similarity |
| Context | hour, weekday, weather, holidays, device |
| Logistics | distance, predicted ETA, fee, cell courier supply/demand ratio |
Serving. Batch the feature-store fetch into one call, use streaming aggregates (Kafka to Flink) for real-time signals, and score all ~300 candidates in one batched inference. A ~500-tree GBDT or a small MLP on CPU fits the 30 ms budget.
Training data and bias. Labels come from logged impressions with clicks and orders. Position bias is real: handle it with a position feature fixed to a constant at serving time, or inverse propensity weighting.
Cold start
- New user: local popularity, time-of-day priors, onboarding cuisine picks; session signals personalize quickly.
- New restaurant: the tower uses content features (cuisine, menu text embedding, price, location) rather than an ID embedding. Apply a Bayesian prior to conversion rate and reserve a few exploration slots.
Re-ranking
Apply diversity (cuisine and price spread), exploration slots, and fleet-aware adjustments such as demoting restaurants in cells with inflated ETAs or low courier supply, plus any merchant-fairness rules.
Evaluation
Offline
- Retrieval: Recall@300 of restaurants the user actually ordered from.
- Ranker: AUC and log-loss per head, calibration, NDCG@10 on order labels.
- Slice by new vs tenured users, new restaurants, and urban vs suburban areas.
Online (A/B test)
- Primary: orders per session from the carousel and gross order value.
- Secondary: CTR and longer-term retention.
- Guardrails: delivery ETA, late-delivery rate, courier utilization, cancellations, p99 latency.
Because users and couriers interact, watch for interference between arms; consider geo-based or time-sliced experiments for fleet-related changes.
Trade-offs
- GBDT vs DNN: simplicity and speed against better use of embeddings and multi-task learning.
- Precomputed per-cell lists vs dynamic radius queries: speed against freshness when zones change.
- Pure relevance vs marketplace-aware scoring: short-term conversion against fleet stability and merchant fairness.
Common mistakes
- Using a global ANN index over all restaurants and filtering by location afterward, which wastes recall and latency.
- Treating open/deliverable status as a soft feature, so ineligible items occasionally leak through.
- Optimizing CTR only, which can push demand into congested areas and hurt delivery times.
- Ignoring position bias in logged training data.
- Giving no latency budget, or evaluating only offline.