Build a Travel Time Prediction Service for Ride Applications
Machine LearningModel answerLast updated
Design a machine learning system that forecasts journey duration for ride-hailing trips, addressing data collection, feature design, model choice, and deployment.
Problem
You're building a travel time forecasting system for a ride-hailing platform. The system needs to predict how long a trip will take from the passenger's current location to their destination, measured in minutes.
Your design should address:
-
Data Collection: What information would you gather, both from past rides and in real-time, to build and operate this predictor?
-
Feature Design: Identify at least four distinct features that capture patterns related to time, location, and external conditions like weather or road congestion.
-
Model Architecture: Select an appropriate modeling approach. Explain whether you'd use linear regression, tree-based methods, or neural networks, and why.
-
Performance Measurement: Define how you'd assess prediction quality. How would you account for unusual delays caused by incidents or accidents?
-
Production Deployment: Outline how you'd meet low-latency requirements when handling millions of simultaneous prediction requests.
Context
- Historical GPS trajectories, road network topology, and weather data are available
- Predictions must complete within 100 milliseconds
- Your design should cover the data flow, modeling strategy, and quality metrics
Deliverable
Present a technical design covering data infrastructure, the machine learning approach, and evaluation methodology.
Hints
Hint 1
Think about separating the routing problem from the prediction problem—what if you use a baseline path calculator and have ML correct its mistakes?
Hint 2
Consider how traffic patterns vary by time of day, day of week, and location—which encoding techniques preserve these cyclic relationships?
Hint 3
Production latency matters: can you pre-compute or cache parts of the prediction to stay under 100ms at high query volumes?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Travel Time Prediction System
A strong approach treats this as two complementary systems: a graph-based path planner that computes baseline estimates, plus a machine learning layer that learns systematic corrections. This separation lets you leverage road network structure while adapting to real-world conditions.
1. Scope and Requirements
Begin by clarifying what you're predicting:
- Which duration? The time from starting the trip to reaching the destination. (Driver-to-pickup time is a separate problem.)
- When is it shown? Before booking and continuously during the ride, updating every 30-60 seconds.
- Output format: Primary estimate in minutes, optionally a conservative upper bound (e.g., 90th percentile) for user expectations.
- Scale: Assuming 15-20M daily trips with multiple predictions per trip (quote, dispatch, ongoing updates), expect 50k-300k queries per second during peak hours across all markets.
- Latency target: 100ms end-to-end at the 99th percentile.
- Data freshness: Traffic conditions change within minutes, so real-time signals need sub-2-minute latency.
2. Data Infrastructure
Historical data:
- Completed trips with pickup/dropoff coordinates, timestamps, and actual duration (your training label)
- GPS traces from those trips, map-matched to specific road segments
- Road network graph: intersections, segments with length, road type, speed limits, and turn constraints
- Historical weather records per geographic area and hour
Real-time streams:
- GPS updates from active vehicles, aggregated into current segment speeds (via stream processing like Kafka + Flink, 1-5 minute windows)
- Live weather conditions
- Traffic incident feeds and planned event calendars
Label preparation: Filter out noisy training examples—trips with GPS anomalies, driver detours, cancellations, or extended stops unrelated to traffic.
3. Feature Engineering
Baseline routing estimate (most important): Use a shortest-path algorithm over the road graph weighted by current and historical segment speeds. This serves as your strongest single feature—the ML model learns the residual (actual minus baseline).
Time patterns: Hour and day with sine/cosine encoding to capture cyclic nature (hour 23 is close to hour 0). Include interactions like "Monday morning" vs "Saturday morning." Add binary flags for holidays and major event days.
Geographic signals: Embed pickup and dropoff locations using learned geohash embeddings (roughly 100-200m cells). Add airport and stadium proximity flags since these have distinct pickup/dropoff friction.
Path characteristics: Total distance, turn count, traffic signal count, percentage on highways, mix of road types. These help differentiate between direct highway routes and complex urban paths.
Live traffic: Ratio of current segment speeds to historical averages along the planned route. Binary flag for incidents on or near the route.
External conditions: Rain intensity, visibility, snow presence, and proximity to large events ending (which cause sudden congestion).
Trip context: Product type (shared vs private), whether this is a pre-trip estimate or an in-progress update with remaining distance.
4. Model Selection
Gradient boosted trees (XGBoost/LightGBM):
- Excellent for tabular features with complex interactions
- Fast CPU inference (5-10ms)
- Handles missing data naturally
- Works well for initial deployment
Deep learning (embedding + feedforward or transformer):
- Better at learning spatial representations through geohash embeddings
- Can share patterns across cities more effectively
- Requires more infrastructure but scales with data volume
- Used by major platforms at scale
Recommended approach: Start with GBDT predicting the residual from your routing baseline. Graduate to deep learning as data and infrastructure mature.
Loss function: Use Huber loss or asymmetric loss functions. Underestimating journey time frustrates users more than overestimating, so penalize negative errors more heavily. Consider training quantile regressors if you need prediction intervals.
5. Evaluation Strategy
Offline metrics:
- Mean Absolute Error (MAE) and Mean Absolute Percentage Error (MAPE) for interpretability
- Median and 90th percentile absolute error
- Mean signed error to detect systematic bias (always over- or under-predicting)
- Critical: Segment by city, time of day, trip length, and weather. Global averages hide regional failures.
Online metrics:
- Percentage of trips where actual time falls within ±10% of prediction
- Impact on conversion rates and cancellations
- Support tickets mentioning inaccurate estimates
- Effects on downstream systems like driver dispatch
Handling unusual delays:
- Remove data quality issues (GPS errors, incomplete trips) from training
- Keep genuine accident delays—they happen in reality
- Use robust loss functions (Huber) so extreme outliers don't dominate training
- Capture accident impact through real-time incident features rather than memorizing specific past events
Validation strategy: Use time-based splits (train on weeks 1-8, validate on week 9) rather than random splits, which leak traffic patterns between train and test.
6. Production Architecture
Request → API Gateway
├─ Routing Engine (in-memory graph with live weights) 20-40ms
├─ Feature Store (Redis: segment speeds, weather) 5-10ms
└─ ML Inference (GBDT or quantized neural net) 5-15ms
→ Response with predicted duration
Streaming pipeline:
- Kafka ingests GPS pings from vehicles
- Flink map-matches them to road segments and computes rolling speed aggregates
- Results flow to both online feature store and routing engine every 1-2 minutes
Scalability:
- Shard by geographic region with auto-scaling replicas
- Cache predictions keyed by (origin area, destination area, 5-minute time bucket) to handle repeated quote requests
- Implement circuit breakers: if ML inference fails, fall back to routing baseline
Training/serving consistency: Generate features from shared code libraries. Log features used at inference time to detect drift and ensure training matches production.
Common Mistakes
- Treating coordinates as raw features: Latitude/longitude need spatial encoding (geohashes, embeddings) to capture neighborhood effects
- Ignoring the routing baseline: Trying to learn path structure from scratch is inefficient—use graph algorithms and have ML correct their errors
- Single global model: Traffic patterns differ drastically by city and time; segmentation or learned embeddings are essential
- Random validation splits: This leaks traffic conditions and inflates offline metrics
- No latency budget: Not measuring individual component latencies makes 100ms SLA impossible to meet
The key insight is that this isn't purely a machine learning problem—it combines graph algorithms, feature engineering, and ML in a tightly integrated system where each component plays to its strengths.