Design a Context-Aware Restaurant Recommendation Engine
System DesignModel answerLast updated
Design an end-to-end personalized restaurant discovery and search service balancing geo-constraints, low-latency ranking, real-time context, and hybrid search architectures.
Context
You are building the personalized recommendation and search engine for a large-scale food delivery application. When users launch the application, they expect an instantaneously loaded, personalized home feed featuring local restaurants tailored to their historical preferences, current time of day, weather, and physical location.
Requirements
- Functional:
- Deliver a personalized recommendation feed updated in real time based on user context (current delivery location, temporal signals, order history).
- Provide hybrid search functionality matching text queries (e.g., "spicy ramen", "vegan breakfast") constrained by localized delivery boundaries.
- Non-Functional:
- Latency: Latency for the home feed recommendation must remain strictly below 200 ms (p99).
- Scale: Support peak load (lunch/dinner rushes) reaching up to 12,000 queries per second (QPS) across tens of millions of active users.
- Freshness: Dynamic factors such as store open/closed state, current estimated delivery time (ETA), and overload status must reflect changes within seconds.
Deliverables
Provide a detailed structural design covering:
- Scale Estimation & System Constraints: Throughput, latency budget, and domain data characteristics.
- Data Modeling & Storage Strategy: Entities, indexing techniques (especially spatial filtering), and online/offline data separation.
- Retrieval & Ranking Architecture: Multi-stage pipeline (candidate retrieval, feature retrieval, ranking, and post-ranking business rules).
- Machine Learning & Personalization Strategy: Feature engineering, offline training vs. real-time feature updating, and cold-start mitigations.
- Hybrid Search Architecture: Semantic/vector search integration alongside traditional keyword retrieval.
- System Evaluation: Offline validation metrics and online A/B testing methodologies.
Hints
Hint 1
Spatial constraints reduce the active candidate pool drastically before any ML ranking takes place. Leverage geospatial indexing (like Uber H3 or S2) to pre-filter.
Hint 2
Split the architecture into multi-stage pipelines: cheap candidate generation (recall-oriented) followed by heavy scoring (precision-oriented).
Hint 3
Never run large LLMs directly on the critical serving path for feed generation. Precompute embeddings and use lightweight online models.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture: Context-Aware Restaurant Recommendation System
1. Requirements & System Constraints
Traffic and Volume Assumptions
- Active Base: 30 Million Daily Active Users (DAU).
- Daily Feed Requests: ~90M feed loads/day (avg 3 sessions/user).
- Average Load: $\approx 1,040\ \text{QPS}$.
- Peak Load: Planning for 10x peak multiplier during lunch/dinner hours $\rightarrow \mathbf{10,000\ \text{QPS}}$ for feed recommendations, plus $\mathbf{3,000\ \text{QPS}}$ for search.
- Catalog Scale: ~1 Million registered merchant locations globally.
- Geospatial Constraint: Only 200 to 2,000 stores are within feasible delivery range of any single user location at a given time.
Latency SLA Budget (p99 $\le$ 200ms)
| Pipeline Stage | Latency Budget | Operations |
|---|---|---|
| API Gateway & Context Resolution | 15 ms | Parse tokens, fetch geo-location, determine time/weather context |
| Candidate Retrieval (Parallel) | 40 ms | Geo-boundary lookup, Vector ANN, Item-Item CF, Recent history |
| Feature Hydration | 30 ms | Multi-get key-value store fetch (User, Merchant, Context features) |
| ML Scoring & Ranking | 50 ms | Lightweight Neural Net / GBDT scoring over ~500 candidates |
| Business Rules & Reranking | 20 ms | Deduplication, promotion insertion, active delivery checks |
| Buffer / Network Overhead | 45 ms | Network transit, JSON serialization |
2. Data Modeling & Storage Layer
┌───────────────────────────────┐
│ Client Application │
└───────────────┬───────────────┘
│
▼
┌───────────────────────────────┐
│ API Gateway / Router │
└───────────────┬───────────────┘
│
┌──────────────────────┴──────────────────────┐
▼ ▼
┌──────────────────────────────┐ ┌──────────────────────────────┐
│ Feed Service │ │ Search Service │
└──────────────┬───────────────┘ └──────────────┬───────────────┘
│ │
┌─────────────┼──────────────────────────────┬──────────────┼──────────────┐
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
┌──────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────┐ ┌──────────────┐
│ User │ │ Vector Index│ │ Search Index│ │ Feature │ │ Store Status │
│ Store│ │ (HNSW/FAISS)│ │(OpenSearch) │ │ Store │ │ (Redis) │
└──────┘ └─────────────┘ └─────────────┘ └─────────┘ └──────────────┘
(KV/PG) Dense Vectors Text/BM25 & Geo (Online) Real-time State
Storage Engines by Domain Entity
- User Profile & Preference Engine (KV Store - ScyllaDB / DynamoDB)
- Keys:
user_id - Attributes: Saved addresses, preferred dietary tags, historical spending tier, long-term cuisine affinity vectors.
- Keys:
- Merchant Entity Store (Relational SQL + Spatial Index)
- Source of Truth: PostgreSQL with PostGIS extension.
- Attributes:
store_id,name,cuisine_types,price_tier,operational_hours,h3_index_res7,menu_json.
- Real-time Merchant State Store (Redis Cluster)
- Keys:
store_id - Attributes:
is_open(boolean),current_prep_time_mins,courier_availability_ratio,is_overloaded. Updates published via streaming infrastructure (Kafka $\rightarrow$ Flink).
- Keys:
- Online Feature Store (Feast / Redis Engine)
- Low-latency lookup (<10ms) for serving features computed offline or near-real-time (e.g., user order count in last 30 days, merchant 7-day conversion rate).
Geospatial Filtering Architecture
Instead of expensive polygon intersection queries at runtime, we index all merchants using Uber H3 spatial index at Resolution 7 (edge length $\approx 1.2\text{ km}$).
- Precomputed Mapping: A Redis set maps
h3_cell_id -> List[store_id]. - When a user requests a feed at coordinates $(lat, lng)$, the service converts coordinates to the local H3 cell and its immediate $k$-ring neighbors. This reduces the search space from $1,000,000$ global merchants to $\approx 800$ local deliverable candidates in single-digit milliseconds.
3. Multi-Stage Retrieval & Ranking Architecture
[ All Merchants (~1M) ]
│
▼ Stage 1: Candidate Generation (Parallel)
┌─────────────────────────────────────────────────────────────┐
│ • Geospatial Filter (H3 Cells): ~800 candidates │
│ • Vector Similarity (Two-Tower ANN): ~200 candidates │
│ • Collaborative Filtering / History: ~100 candidates │
│ • Popular / Trending in Area: ~100 candidates │
└──────────────────────────────┬──────────────────────────────┘
│ (~500 unique candidates)
▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 2: Hard Filtering (Open hours, delivery range, ETA) │
└──────────────────────────────┬──────────────────────────────┘
│ (~400 valid candidates)
▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 3: Feature Hydration (User, Store, Context Features) │
└──────────────────────────────┬──────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 4: Heavy ML Ranking Model (GBDT / Deep Learning) │
└──────────────────────────────┬──────────────────────────────┘
│ (Top 50 scored merchants)
▼
┌─────────────────────────────────────────────────────────────┐
│ Stage 5: Business Rules, Diversity & Carousel Layout │
└─────────────────────────────────────────────────────────────┘
Stage 1: Parallel Candidate Generation (Recall Stage)
To achieve high recall within strict latency bounds, several lightweight strategies run concurrently with per-source timeouts (~30ms):
- Geo-Popularity Source: Returns top-performing merchants within the user's H3 cell group based on 7-day order volume.
- Personalized History Source: Fetches stores the user has ordered from in the last 90 days ("Order Again").
- Two-Tower Neural Retrieval: Performs Approximate Nearest Neighbor (ANN) search over user embeddings and store embeddings (pre-indexed via HNSW), constrained strictly to the local deliverable store IDs.
- Collaborative Filtering Source: Item-Item similarity based on past ordering co-occurrences.
Outputs are deduplicated into a candidate pool of approximately 500 stores.
Stage 2: Hard Constraints Filtering
Filter candidates based on real-time operational availability:
- Remove stores marked as
is_open = falseor currently paused by store manager. - Remove stores where estimated courier dispatch + prep time exceeds acceptable SLA (e.g., total ETA > 60 minutes).
- Exclude stores whose hard delivery radius polygon does not cover the precise $(lat, lng)$.
Stage 3: Feature Hydration
The remaining ~400 stores are enriched with features retrieved in batch (MGET) from the Feature Store:
- User Features: Historical cuisine preference scores, average cart size, sensitivity to delivery fees.
- Store Features: Historic completion rate, average rating, historical prep times for the current hour.
- Cross Features: Distance from user, user's previous order count from this store.
- Real-time Context: Current time-of-day bucket (e.g., late-night, lunch), weather state (e.g., raining), current dynamic ETA.
Stage 4: Machine Learning Ranking (Precision Stage)
Candidates are scored via a unified machine learning model predicting the probability of user order placement: $$\text{Score} = P(\text{Order} \mid \text{User}, \text{Store}, \text{Context}) \times \text{Expected Order Value} - \lambda \cdot (\text{ETA})$$
- Model Framework: LightGBM / XGBoost or a multi-task deep neural network (e.g., Shared-Bottom Architecture predicting both $P(\text{Click})$ and $P(\text{Order} \mid \text{Click})$).
- Compute budget: ~400 candidates $\times$ 50 features scored in $<40\text{ ms}$ using standard C++ optimized inferencing engines (e.g., ONNX Runtime or TensorRT).
Stage 5: Business Rules & Diversity Re-ranking
- De-duplication & Diversity: Ensure the top 10 positions do not feature 10 merchants of the exact same cuisine type (e.g., maximal marginal relevance or category cap rules).
- Sponsored Slot Injection: Inject promoted merchant cards while ensuring ad transparency tags and pacing budgets are maintained.
- Carousel Grouping: Route recommendations into thematic carousels (e.g., "Fastest Near You", "Popular Local Spots", "Order Again").
4. Machine Learning & Feature Strategy
Feature Taxonomy
| Feature Category | Feature Name | Source / Type | Update Frequency |
|---|---|---|---|
| User | user_preferred_cuisines | Vector / Sparse | Daily (Batch) |
| User | user_order_frequency_breakfast | Float | Daily (Batch) |
| Merchant | store_7d_conversion_rate | Float | Hourly (Streaming) |
| Merchant | store_current_backlog_orders | Integer | Real-time (Flink) |
| Context | is_weekend, time_of_day_bucket | Categorical | Request Runtime |
| User $\times$ Merchant | days_since_last_user_order | Integer | Real-time / Daily |
| User $\times$ Context | distance_user_to_store_km | Float | Request Runtime |
Training Pipeline & Position Bias Mitigation
- Offline Training Dataset: Generated from implicit feedback logs (impressions, clicks, add-to-carts, orders) collected via Kafka streams and dumped to a Parquet-based data lake (S3/Delta Lake).
- Position Bias Correction: In a feed, users naturally click higher items. To prevent the model from learning to favor higher slots unconditionally:
- Add
impression_positionas an explicit feature during offline training. - During online inference, set
impression_position = 0(or constant average) for all candidate scoring.
- Add
- Model Freshness: Retrain GBDT ranking models daily on a rolling window (e.g., past 30 days) of interaction data. Two-tower embeddings are updated weekly. Model weights are not updated online in real-time to avoid instability and unrecoverable feedback loops; instead, real-time context is introduced strictly via updated feature values (e.g., Flink stream aggregating click counts within the current active session).
5. Hybrid Search Architecture
For explicit search queries (e.g., "spicy chicken wings"), search combines traditional keyword retrieval with semantic understanding:
┌──────────────────────────┐
│ Search Query Input │
│ "spicy chicken under $15"│
└────────────┬─────────────┘
│
▼
┌──────────────────────────┐
│ Query Understanding │
│ (Intent, NER, Filters) │
└────────────┬─────────────┘
│
┌─────────────────────┴─────────────────────┐
│ │
▼ ▼
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ Lexical Branch (BM25) │ │ Vector Branch (ANN) │
│ Matches text in store titles, │ │ Embeds query via MiniLM model │
│ menu item names, and categories │ │ Matches vs offline menu vectors │
└────────────────┬────────────────┘ └────────────────┬────────────────┘
│ │
└─────────────────────┬─────────────────────┘
│
▼
┌──────────────────────────┐
│ Reciprocal Rank Fusion │
│ (RRF / Merge) │
└────────────┬─────────────┘
│ (Geo-Filtered Set)
▼
┌──────────────────────────┐
│ Personalized Ranker │
│ (Same architecture as │
│ recommendation feed) │
└──────────────────────────┘
- Query Parsing / NER: Extract entity tokens (Cuisine: "Chicken", Attribute: "Spicy", Constraint: "< $15").
- Lexical Indexing (OpenSearch): BM25 text match on indexed store titles, menu item names, and tags, hard-filtered by the user's deliverable H3 cells.
- Vector/Semantic Branch: Query text is converted to a dense vector via a lightweight embedding model (e.g., Sentence-BERT variant running on CPU or dedicated inferencing pool). Compute cosine similarity against pre-computed menu/restaurant text embeddings.
- Hybrid Merging: Combined score via Reciprocal Rank Fusion (RRF): $$\text{RRF_Score}(d \in D) = \sum_{m \in M} \frac{1}{k + r_m(d)}$$
- The top merged results are fed into the standard Personalized ML Ranker with additional match-quality features (e.g.,
bm25_score,embedding_similarity_score).
Large Language Model (LLM) Integration Strategy
To maintain strict latency constraints (<200ms), LLMs are strictly excluded from the critical serving path:
- Offline Tagging & Semantic Structuring: LLMs digest unstructured restaurant menus, customer review text, and uploaded photos to auto-generate taxonomy tags (e.g., "keto-friendly", "spicy level 3", "cozy atmosphere") and rich semantic text embeddings stored in the vector database.
- Cached Query Expansion: Popular head queries are processed through an LLM offline to create synonym dictionaries (e.g., mapping "hangover food" $\rightarrow$ "greasy burgers", "ramen", "pho").
6. Cold Start Strategy
-
New Merchants:
- Zero Interaction Data: Collaborative filtering and historical conversion models fail on brand-new listings.
- Content-Based Initialization: An offline job processes the new merchant's menu using text embeddings and tags generated via LLM extraction, placing it near similar existing merchants in vector space.
- Exploration Boost: Allocate an explicit "New on App" carousel slot or inject new merchants into the ranking pipeline with a temporary score bonus (Upper Confidence Bound approach) for their first $N$ impressions to quickly gather interaction data.
-
New Users:
- Zero Historical Orders: Lack of personal taste profile.
- Contextual & Demographic Fallback: Rely heavily on geo-popularity (what people in this neighborhood order), temporal context (breakfast vs. dinner), and onboarding preference selections (e.g., selected dietary restrictions during signup).
7. System Evaluation & Metrics
Offline Metrics (Model Validation)
- NDCG@K (Normalized Discounted Cumulative Gain): Evaluates whether stores the user actually ordered from are placed near the top of the recommended list.
- MRR (Mean Reciprocal Rank): Measures the average rank position of the first clicked or ordered store.
- AUC-ROC / Log-Loss: Validates calibration of the click-through-rate (CTR) and conversion-rate (CVR) point-prediction models.
Online A/B Testing Metrics
- Primary Business Metric: Gross Merchandise Value (GMV) per user session and overall Conversion Rate (Completed Orders / Feed Visits).
- Engagement Metrics: Feed Click-Through Rate (CTR), Time-to-Order (duration from app opening to checkout completion).
- Ecosystem Health Metrics: Merchant coverage (percentage of active merchants receiving at least 1 order per day), user retention rate (30-day repeat order rate).