Real-Time Location-Based Recommendation System
Machine LearningModel answerLast updated
Design a machine learning system that delivers personalized, geographically relevant place recommendations with sub-200ms latency at scale.
You're building a recommendation engine that surfaces relevant nearby locations—restaurants, shops, parks, entertainment venues—to users based on their current position and preferences.
Your system should handle hundreds of millions of daily active users, each making several requests per session. The entire pipeline must complete within 200 milliseconds at the 99th percentile.
Address the following components in your design:
-
Business objectives and measurement: What outcomes define success? How do you measure whether recommendations are actually useful?
-
Data foundations: What information feeds the system? Consider both static attributes and dynamic signals.
-
Candidate retrieval: How do you quickly narrow down millions of locations to a manageable set worth scoring?
-
Feature design: What signals help predict relevance? Consider user preferences, venue characteristics, temporal patterns, and spatial relationships.
-
Scoring and ranking: How do you order candidates? What modeling approach balances accuracy and speed?
-
New user and new venue problems: How does the system perform when historical data is absent?
-
Balancing familiarity and discovery: How do you prevent showing users only what they already know?
-
Quality and safety: How do you prevent manipulation, spam, and low-quality recommendations?
-
Privacy constraints: What location data can you use, and how do you protect sensitive information?
-
Performance and evaluation: How do you deploy changes safely and monitor system health?
You may make reasonable assumptions about scale, but state them explicitly.
Hints
Hint 1
Start with a two-stage funnel: fast geographical filtering to get candidates, then a slower scoring model for final ranking
Hint 2
Think about what features are naturally sparse versus dense, and which ones need real-time computation versus batch preprocessing
Hint 3
Cold-start scenarios need content-based fallbacks—what can you infer about a brand-new venue from its category, photos, or description alone?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a latency-constrained recommendation problem with a geographical constraint. The core challenge is narrowing millions of venues to a relevant handful within strict time bounds while personalizing to diverse user preferences.
Strong solutions anchor on clear metrics, use geography to make retrieval tractable, build a context-rich ranker, and address operational concerns like new items and adversarial behavior.
1. Requirements and Scale
Functional scope:
- Accept user location (latitude/longitude) and return approximately 20 ranked venues
- Support optional category filters (e.g., "coffee," "dinner")
- Reflect real-time position
Performance targets:
- p99 latency ≤ 200ms for the full pipeline
- Handle scale: assume 200M daily active users, 3 sessions each = 600M requests/day, averaging ~7K QPS with peaks at 25K QPS
Data assumptions:
- Global venue catalog: ~200M points of interest
- Typical urban 2km radius contains 500–5,000 venues
2. Objectives and Metrics
The goal is meaningful engagement, not merely clicks. Optimize for actions that indicate genuine interest: saving the venue, requesting directions, calling, or—best of all—a verified visit (measured via location dwell time with user consent).
Metric hierarchy:
- North star: Verified visits per user; 7-day retention among users who engaged with recommendations
- Online proxies: Click-through rate, directions/call rate, save rate, time spent on venue detail page
- Guardrails: p99 latency, user-initiated hides/reports, category diversity in top results, fraction of recommendations showing new venues
- Offline: NDCG@10, AUC, calibration between predicted and observed engagement rates
Use a multi-objective learning target that weights downstream actions more heavily than raw clicks:
score = α·P(click) + β·P(directions | click) + γ·P(visit)
This prevents optimizing for clickbait images of distant famous landmarks.
3. Data Sources
- Venue catalog: Name, coordinates, category taxonomy, operating hours, price tier, photos, menu/description, sourced from map data providers, business profiles, and user contributions
- Behavioral logs: Impressions, clicks, saves, check-ins, reviews, search queries, historical visits (with consent)
- Social signals: Connections' visits, ratings, and recommendations
- Contextual streams: Current time, day of week, weather API (temperature, precipitation), local events, device motion state (stationary/walking/driving)
- Aggregated statistics: Hourly visit volume ("popular times"), aggregate ratings, recent trend direction
4. Candidate Retrieval via Geospatial Indexing
Goal: Reduce 200M venues to ~1,000–2,000 candidates in under 30ms.
Method:
-
Spatial index: Partition the world using S2 cells (level 13, ~1km² each) or H3 hexagons. Store a mapping from cell ID to venue list in a sharded in-memory key-value store.
-
Neighborhood lookup: Query the user's cell and immediate neighbors. Adaptively expand radius until retrieving at least N candidates (dense cities need 500m; rural areas may need 20km).
-
Parallel retrieval strategies, then union results:
- Popularity-based: Pre-computed top venues per cell, hour, and category
- Personalized vector search: Two-tower model (user embedding × venue embedding) with approximate nearest neighbor search (FAISS/ScaNN) restricted to the geographical region
- Social retrieval: Venues friends have visited nearby
- Exploration pool: Recent or under-exposed venues
-
Hard filters: Open now (or opening within 30 minutes), matches category filter if provided, excludes user-hidden venues
5. Feature Engineering
| Feature Group | Examples |
|---|---|
| Distance | Haversine distance, estimated travel time by mode, log(distance), whether venue lies along current heading |
| Popularity | Visits in last 7/30 days, Bayesian-smoothed rating, rating count, current busyness level, trend slope |
| Personalization | User's affinity for category, price preference, two-tower embedding dot product, prior visits to venue or chain, friend visits |
| Context | Hour of day, day of week, weather (rain → indoor boost), temperature, minutes until closing, nearby events |
| Interactions | Category × hour (coffee morning, bars evening), distance × movement state |
| Venue quality | Photo count, profile completeness, report rate |
Real-time features (current busyness, user's last 5 interactions) come from a streaming pipeline (Kafka → Flink → online feature store).
Batch features are precomputed daily via Spark and stored in a low-latency feature store.
To prevent training/serving skew, log feature values at serving time and train on those exact logs.
6. Ranking Model
Two-stage architecture:
Stage 1 (Light ranker):
- Gradient-boosted trees or shallow MLP scores ~1,500 candidates
- Keeps top 200
- Budget: ~20ms
Stage 2 (Heavy ranker):
- Multi-task deep neural network with shared layers and separate heads for click, directions, and visit
- Input: sparse embeddings (user ID, venue ID, category) + dense features
- Combine head outputs with learned or tuned weights
Final re-ranking:
- Apply diversity constraints (e.g., max 3 coffee shops in top 10) via maximal marginal relevance
- Deduplicate chain locations
- Apply business rules
Addressing position bias: Train on logged data but include position as a feature, then fix it to a neutral value at inference. Alternatively, use a separate shallow position tower.
7. Cold Start Strategies
New users:
- Fall back to popularity: top venues for the current cell, hour, and weather
- Use category preferences from onboarding
- Leverage demographics or locale-based priors
- Update session embedding rapidly from first few interactions
New venues:
- Use content features: category, price, photo embeddings (pretrained vision model), text embeddings of description
- Borrow embeddings from similar venues or same chain
- Reserve exploration budget: guarantee minimum impressions (e.g., until 100 impressions accumulated)
- Apply Bayesian priors so one 5-star review doesn't outrank 2,000 reviews at 4.6 stars
8. Exploration vs. Exploitation
Reserve 1–2 slots (~5% of traffic) for exploration:
- Thompson sampling or UCB: Boost items with high uncertainty in predicted engagement
- Epsilon-greedy with propensity logging: Enables unbiased off-policy evaluation via inverse propensity scoring
- Constrain exploration to candidates passing minimum quality and distance thresholds to limit downside risk
9. Spam and Fraud Prevention
Threats: Fake venues, review farms, GPS spoofing to inflate visit counts, keyword-stuffed names, duplicate listings.
Defenses:
- Venue integrity classifier (textual analysis, image embeddings, report rate, edit history)
- Graph-based fraud detection: cluster accounts with shared devices/IPs who coordinate reviews
- Anomaly detection on rating and visit velocity
- Device attestation for check-ins
- Filter venues with spam scores above threshold from recommendations
- Exclude suspicious engagement from training labels to prevent model poisoning
10. Privacy
- Require explicit user consent for location tracking and visit history
- Process location ephemerally: discard coordinates after retrieval, log only coarse cells
- Offer privacy controls: disable personalization, clear history
- Differential privacy on aggregated statistics (popular times) to prevent venue-level inference
- Comply with regional regulations (GDPR, CCPA)
11. Latency Budget
| Stage | Allocation |
|---|---|
| Geospatial retrieval | 30ms |
| Feature fetching (parallel) | 40ms |
| Light ranker | 20ms |
| Heavy ranker | 50ms |
| Re-rank + response | 20ms |
| Total | 160ms (buffer to p99) |
Optimize via caching (popular venues, user embeddings), feature store sharding, model quantization, and batching.
12. Evaluation and Deployment
Offline: Train/validation/test split by time. Evaluate NDCG@10, AUC, calibration.
Online A/B testing:
- Randomize at user level for 2–4 weeks
- Primary: visit rate, retention
- Secondary: CTR, directions rate, diversity
- Guardrails: latency, report rate
Monitoring:
- Real-time dashboards: QPS, p50/p99 latency, error rate
- Model performance: prediction distribution drift, feature null rates
- Business metrics: engagement drop alerts
Iteration loop: Weekly model retraining on fresh data; quarterly architecture reviews.
Complexity
- Candidate retrieval: O(k) where k = venues in nearby cells (~1,000–2,000)
- Ranking: O(k · f) where f = feature computation cost; heavy ranker operates on top 200
- End-to-end latency: Dominated by feature fetching and model inference; parallelization and caching are critical
Common Mistakes
- Ignoring position bias in training data
- Cold-start solutions that rely solely on popularity (poor personalization)
- Neglecting diversity, leading to repetitive recommendations
- Not filtering spam from training labels
- Underestimating the cost of real-time feature computation
- Using CTR as the sole metric, which rewards clickbait over utility