AI System DesignAI System Design Case StudiesGeospatial and Real-Time Prediction
How to Design Uber’s Real-Time Driver ETA Prediction System
Question 5 of 47 · Updated
On this page
- 1. Define the ETA precisely
- 2. Requirements and success criteria
- 3. Capacity planning
- 4. High-level architecture
- 5. Collect and process high-quality geospatial data
- Event contracts
- Spatial indexing
- Privacy and access control
- 6. Routing baseline: the road network comes first
- Algorithms and trade-offs
- 7. Real-time traffic ingestion and segment features
- 8. Feature engineering for the ETA model
- 9. Training data and sampling strategy
- 10. Model selection: baseline plus learned correction
- Residual regression
- More advanced models
- 11. Uncertainty estimation and rider experience
- 12. Practical Python example: routing and conformal calibration
- 13. Low-latency serving and assignment consistency
- 14. Storage, caching and scalability
- 15. Evaluation metrics and worked example
- 16. Failure handling and reliability
- 17. Model governance and continuous learning
- 18. Interview trade-offs and follow-up questions
- 19. Interview-ready answer
- References and research transparency
I would combine a time-dependent road-routing baseline with a supervised travel-time correction model and calibrated uncertainty estimates. A routing engine provides a physically plausible path from the assigned driver's current position to the pickup location; live traffic, historical segment travel times and contextual features allow an ML model to correct the baseline. A low-latency ETA service returns a point estimate and an uncertainty range, with a safe routing-only fallback when model or feature dependencies are unavailable.
The source interview question is: Describe how you would build a model to predict Uber driver ETAs after a rider requests a ride.
This is a proposed ride-hailing system design, not an assertion about Uber's private production models, current traffic or operational guarantees. All workload, latency, model-output and evaluation examples are hypothetical.
1. Define the ETA precisely#
Before choosing a model, establish what the arrival time means. Three related quantities must not be conflated:
- Pre-assignment pickup wait: elapsed time from the ride request until a driver reaches the pickup point. It includes dispatch and driver approach, and can include reassignment.
- Assigned-driver pickup ETA: remaining time from a specific prediction timestamp until the assigned driver reaches the agreed pickup point.
- Trip duration: elapsed time from pickup to drop-off.
The primary target in this design is the second quantity. After a rider requests a ride, the dispatch system identifies a driver, and the ETA service estimates that driver's remaining time to pickup. Before assignment, present a separate approximate wait estimate or indicate that matching is in progress. The pre-assignment estimator needs a model of dispatch latency and driver availability; simply displaying a nearby driver's route time does not account for acceptance or assignment.
Define arrival using an operational event with consistent semantics, such as a verified driver-arrival event associated with the correct assignment and pickup location. Passenger boarding may happen later; do not inadvertently train on trip-start timestamps when the target is vehicle arrival.
At prediction time t, the supervised label for a completed, still-valid assignment is:
remaining_seconds = arrival_timestamp - prediction_timestampExclude predictions made after arrival. Detect inconsistent timestamps and label quality problems explicitly rather than clipping every negative label to zero. Cancelled and reassigned cases do not provide ordinary completed-arrival labels for the original assignment. They require censoring-aware analysis, separate outcome prediction or clear conditioning on completion.
2. Requirements and success criteria#
The ETA must be timely, credible and robust enough to be used by both dispatch and rider-facing systems. A wrong prediction can cause avoidable cancellations, inefficient allocation and missed pickups.
| Dimension | Illustrative design requirement |
|---|---|
| Prediction unit | Assignment ID, pickup revision and prediction timestamp |
| Inputs | Current driver position, pickup coordinates, road topology, traffic and time context |
| Outputs | Remaining seconds, prediction time, freshness, model version and optional calibrated interval |
| Latency | p95 under 150 ms inside the ETA service boundary, to be benchmarked |
| Freshness | Explicit maximum age for each traffic and location feature |
| Availability | Route-only fallback or honest unavailable status when ML inference fails |
| Consistency | Never apply an estimate from a previous assignment to a newly assigned driver |
| Quality | Compare against routing baseline using temporal and regional holdouts |
| Privacy | Minimize location retention, enforce authorization and protect raw traces |
Functional requirements include computing an initial ETA immediately after assignment, updating it as meaningful position or traffic changes arrive, handling pickup edits and reassignments, and invalidating the estimate after arrival or cancellation.
A rider-facing estimate and a dispatch-time estimate may share a model but have different service contracts. Dispatch may need a batched origin-to-destination matrix for many candidate drivers. The rider-facing API needs a single current assignment. Do not let candidate-matrix computation overload the live ride-update path.
3. Capacity planning#
Assume a synthetic service receives 5 million ride requests per day, of which 4 million yield assignments that each generate an average of 20 ETA evaluations. Assume one million concurrently connected drivers at a hypothetical peak, each sending a location update every five seconds.
- Initial requests average about 58 requests per second before traffic concentration and dispatch fan-out.
- Eighty million ETA evaluations per day average about 926 evaluations per second. If peak load is five times that daily average, plan for approximately 4,630 evaluations per second plus retry and failover headroom.
- One million drivers reporting every five seconds create 200,000 location events per second at the assumed peak.
- At 200 bytes per compact location event, this is approximately 40 MB per second of payload before protocol, replication and indexing overhead. Sustaining that peak for a full day would generate about 3.46 TB; it is not a forecast of daily volume.
- If a routing call consumes substantial CPU, one per location event would be wasteful. Ingest location separately, coalesce updates and recompute only where the active ride state or feature freshness warrants it.
Separate the much higher-rate telemetry ingestion workload from ETA prediction requests. Estimate the number of workers from measured sustainable throughput, p99 latency, traffic by city, graph complexity, feature reads and maximum dependency fan-out. A capacity figure based only on average throughput hides short urban bursts and regional hotspots.
For dispatch, 58 requests per second with 20 candidate drivers each would imply approximately 1,160 candidate evaluations per second at the illustrative daily average. This is additional to the rider-facing workload if not already included in its accounting. In practice, use spatial candidate pruning and batch routing instead of independently querying every driver in the city.
4. High-level architecture#
Use independent ingestion, feature generation, routing, online serving and offline training paths. This allows the traffic pipeline and prediction model to evolve without coupling the ride-request API to expensive training jobs.
The event log decouples producers from downstream consumers. Stream processing maintains fresh spatial and segment-level statistics; the historical lake supports reproducible training. The routing engine computes the travel-time baseline on a versioned road graph. The ETA service obtains the latest authorized assignment, retrieves only the required features, executes routing and model inference within a deadline, and produces a validated response.
The model predicts travel time; it does not choose the driver or decide whether a driver will accept a ride. Driver acceptance is a separate prediction problem, even though an ETA estimate is useful to dispatch.
5. Collect and process high-quality geospatial data#
Event contracts#
A location event can include a pseudonymous driver identifier, event ID, event timestamp, ingestion timestamp, coordinates, reported positional accuracy, heading and optional speed information. The assignment stream includes ride and assignment IDs, assignment time, pickup revision and status changes. Arrival events identify the relevant assignment and timestamp.
Raw GPS is noisy. Signals can be delayed, duplicated, irregularly sampled or affected by tall buildings, tunnels and temporary loss of connectivity. A straight line between two observed points may cross a river or an inaccessible road. Directly converting every GPS coordinate into a road-segment speed observation is not reliable.
The processing pipeline should:
- Validate coordinate ranges, timestamps, accuracy indicators and event schemas.
- Deduplicate using stable IDs and handle out-of-order events through event-time processing.
- Match noisy locations to plausible road segments using topology and observation uncertainty.
- Reject or downweight invalid measurements and record data-quality indicators.
- Aggregate travel-time and traffic observations by directed segment and time window.
- Maintain event watermarks and expiry policies for features.
For example, a sequence of observations can be map-matched using a Hidden Markov Model, with emissions representing positional plausibility and transitions representing feasible movement on the road network. A simpler nearest-road approach can serve as a baseline, but adjacent roads, flyovers and intersections often make it unreliable. Use confidence indicators rather than forcing every trace onto a segment.
Map matching and speed aggregation must consider stopped vehicles. A driver waiting for a rider or parked at a destination should not automatically be interpreted as a congested road segment. Distinguish movement-related observations from service lifecycle events where permitted and reliable.
Spatial indexing#
H3-style hierarchical hexagonal indexing or a comparable spatial index groups coordinates into cells at configurable resolutions. Use coarse cells to summarize regional demand and traffic and finer cells for local feature lookups. Resolution is a tunable design parameter: fine cells can be sparse and noisy, while coarse cells may merge unrelated roads.
A spatial cell is not a routing node. Neighboring cells may be separated by a barrier, one-way roads or limited crossings. Use a directed road graph for route feasibility and distance. Spatial indexes are valuable for aggregation, candidate lookup and partitioning, not a substitute for network topology.
Privacy and access control#
Exact driver and rider coordinates are sensitive. Process them only for authorized ride-related purposes, restrict access to active assignments, pseudonymize historical training identifiers and apply documented retention and deletion policies. Keep raw coordinates out of general-purpose application logs. Model evaluation should not expose individual trajectories. Prefer aggregate regional measurements where precise traces are unnecessary.
6. Routing baseline: the road network comes first#
Represent the road network as a directed weighted graph G = (V, E). Vertices represent routing states or intersections; edges represent traversable directed connections with distance, estimated traversal time and relevant restrictions. Turn penalties and restrictions may require edge-based or expanded-state graph representations rather than a naive intersection-only graph.
For a route containing directed segments e1, e2, ..., en, a simple fixed-snapshot time estimate is:
baseline_seconds = sum(segment_travel_time_seconds)
+ applicable_turn_and_pickup_approach_delaysIf an edge has length L meters and effective speed v meters per second, L/v is a simple traversal-time estimate when v is positive. Do not use an instantaneous near-zero GPS speed as the denominator: infer representative traversal times from validated historical and live observations, and handle inaccessible segments separately.
Algorithms and trade-offs#
| Algorithm | Use | Limitation |
|---|---|---|
| Dijkstra | Correct shortest path on a static graph with nonnegative costs | Can explore many vertices on a large road network |
| A* | Focuses search using an admissible lower-bound heuristic | Heuristic must be compatible with the objective; consistency helps efficient graph search |
| Bidirectional search | Can reduce explored nodes for suitable static routing problems | Time-dependent costs and directionality require careful treatment |
| Contraction hierarchies or related hierarchical routing | Fast repeated queries with preprocessing | Dynamic weights and topology changes require compatible customization or rebuild strategies |
| Batched or many-to-many routing | Efficient dispatch evaluation for candidate drivers | Memory and latency depend on matrix size and graph implementation |
For A* with travel time as the objective, straight-line distance divided by a defensible upper bound on feasible speed may serve as a lower bound. The heuristic must never overestimate the true remaining cost if optimality is required. An arbitrary average speed is not necessarily admissible.
Road travel time is time-dependent. Entering a segment ten minutes later can encounter a different traffic condition than entering it now. In a time-dependent formulation, compute the next edge's arrival time using the expected departure time at that edge. Efficient label-setting shortest-path approaches generally require a FIFO property: departing later on the same edge cannot lead to an earlier arrival than departing earlier, under the defined edge travel-time function. If the model violates FIFO, standard static shortest-path correctness arguments do not directly apply.
Start with a consistent traffic snapshot for a short pickup horizon, then evaluate time-dependent routing where horizon and traffic variability warrant it. Respect road direction, current closures and relevant access restrictions. A geographic distance-only estimate is an emergency approximation at best, not equivalent to driving time.
7. Real-time traffic ingestion and segment features#
Use both historical and live traffic information where authorized. Historical travel-time profiles provide a stable prior by segment, weekday and local time. Recent segment traversals provide evidence about current congestion.
A simple conceptual shrinkage estimator is:
estimated_segment_time =
w * recent_robust_travel_time + (1 - w) * historical_timeChoose w according to validated recency, sample count and confidence, not a universal constant. Sparse or stale observations receive less weight. Use robust aggregates to reduce outlier influence. Where appropriate, learn the blending function and evaluate it against future traversals.
Stream processing can maintain rolling windows of observations, aggregate by directed road segment and materialize feature records containing estimate, observation count, event-time watermark, data-quality flag and graph version. A routing engine should consume compatible graph and traffic versions; mapping travel times to obsolete edge IDs can produce invalid paths.
Store an immutable event history for reproducibility and a fast online representation for inference. Processing-time freshness alone is insufficient if the upstream source has stopped producing current data. Compare feature timestamps with the inference timestamp and identify both pipeline lag and source staleness.
When a road closure or routing-relevant restriction changes, invalidate affected route results according to the graph-update contract. A previously cached route must not be reused blindly if the underlying graph has changed.
8. Feature engineering for the ETA model#
Use a route-level ML model after baseline routing. The feature vector should represent the journey and context actually known at prediction time.
| Feature family | Examples | Engineering considerations |
|---|---|---|
| Routing baseline | Predicted travel seconds, path length, segment count | Pin graph and traffic versions |
| Route composition | Road types, turns, intersections, segment travel-time summaries | Derive from actual feasible route |
| Traffic | Recent travel times, congestion summaries, observation counts | Track freshness and uncertainty |
| Time | Local time, day of week, holiday or known event context | Handle time zones and daylight-saving transitions |
| Spatial | Origin and pickup cells, market, region embeddings | Avoid assuming neighboring cells imply road access |
| Location quality | Accuracy, age, map-match confidence | Avoid treating missing as zero |
| Pickup context | Authorized pickup geometry, legal approach and historical arrival-delay aggregates | Do not confuse arrival with passenger boarding |
| Ride context | Assignment age, permitted ride type and pickup revision | Never include future assignment outcomes |
Do not use actual future route segments or post-arrival signals as inference features. The route actually taken is not known at prediction time. It is useful for analysis and training target construction, but input features should be derived from the planned route or other information available when the estimate was generated.
Similarly, do not include completed trip duration or the eventual traffic observed after prediction in an initial ETA model. Offline joins must be point-in-time correct. Preserve the timestamp at which every online feature was available, not merely when the underlying real-world observation occurred.
Avoid using driver identity as an unrestricted predictive shortcut. If personalized or behavioral signals are ever considered, they require a legitimate purpose, fairness review, adequate data and explicit governance; an engineering baseline can use route, traffic, location quality and non-sensitive context instead.
9. Training data and sampling strategy#
Each training example corresponds to a valid prediction opportunity for a particular assignment and prediction timestamp. Record the input snapshot, route baseline, relevant versions, and later adjudicated arrival outcome.
A single assignment can generate many updates. Treating all updates as independent samples can overweight long journeys and cause the same assignment to appear in both training and testing. Split by time and group related snapshots by assignment. Weight examples or stratify by remaining-time horizon according to the intended production objective.
Use a training period, later validation period, separate calibration period and untouched final evaluation period. Add regional holdouts to test generalization and investigate whether a global model transfers to new cities.
Cancellations create informative censoring: a rider may cancel because the ETA is too long or inaccurate. A model trained only on completed rides estimates travel time conditional on observed completion, potentially creating selection bias. Track cancellation and reassignment outcomes separately. Consider survival analysis or censoring-aware methods when the business needs unconditional time-to-arrival or probability of successful pickup. Never label a cancelled ride's cancellation time as if the driver arrived.
Track label delay, missing arrival events, clock skew, repeated arrival events and inconsistency between location and trip state. Compare training coverage to the actual online request population, including poor GPS conditions and low-data markets.
10. Model selection: baseline plus learned correction#
Start with the routing engine's travel time as a measurable baseline. Do not begin with a deep network that receives only latitude and longitude and is expected to rediscover road topology from data.
Residual regression#
Let b(x) be the routing baseline in seconds and y be actual remaining time. Define the residual r = y - b(x). A model f(x) predicts the correction:
predicted_seconds = max(0, baseline_seconds + predicted_residual)The final nonnegative guard prevents an impossible duration, but repeated clipping indicates a model or feature problem. Handle already-arrived assignments in the ride-state service rather than relying on regression clipping.
A gradient-boosted tree model is a strong initial choice for tabular route, traffic and context features. Compare it with a regularized linear residual model. Train directly against a loss aligned with the objective: absolute error targets a conditional median, squared error targets a conditional mean, and Huber loss offers a compromise between sensitivity to large errors and robustness. Be explicit about which point estimate the product returns.
An alternative predicts a multiplicative correction in log space. This can be useful when residual variability grows with route length, but transforming back from log space does not generally recover the conditional mean without a correction. Evaluate bias after transformation and ensure predictions remain calibrated in seconds.
More advanced models#
A segment-sequence model can encode ordered route segments and their traffic attributes. Graph neural networks may model spatial interactions between road segments. Temporal models can learn how congestion propagates. These may improve challenging routes but introduce greater data requirements, inference cost and operational complexity.
Do not assume travel times on adjacent segments are independent. A traffic incident can delay many segments simultaneously. Simply summing independent segment uncertainty estimates may understate route-level uncertainty. A route-level correction and route-level calibration can capture some correlated effects.
Use a simple routing-plus-residual model as the launch candidate. Add more complex architectures only after analyzing systematic errors and benchmarking actual improvement in quality, latency and operating cost.
11. Uncertainty estimation and rider experience#
A prediction such as 360 seconds does not mean the driver will arrive exactly six minutes later. Traffic, route changes and observation noise make travel time uncertain.
A quantile model can predict the median and lower/upper travel-time quantiles using pinball loss. Validate the ordering of quantiles and their empirical coverage. Quantile crossing may require a monotone parameterization, constrained training or an evaluated postprocessing step.
Split conformal prediction provides another useful approach. Train a point predictor on a training set, then compute absolute residuals on a separate calibration set. For n calibration scores and desired miscoverage alpha, use the order statistic at rank ceil((n + 1) × (1 - alpha)). If that rank exceeds n, an unbounded radius is the conservative formal result; the product should not present an apparently precise finite interval in that case.
For a finite calibrated radius q, the interval is [max(0, estimate - q), estimate + q]. Under exchangeability of calibration and new examples, standard split conformal methods provide finite-sample marginal coverage for the specified target, not per-city or per-rider conditional coverage. Traffic drift, correlated repeated predictions and changes in assignment policy can undermine the assumptions. Recalibrate and audit coverage by horizon and market, and avoid claiming a guaranteed arrival time.
Use uncertainty to improve communication and decisions. A rider may see an approximate range when uncertainty is high, according to product design. Dispatch can account for uncertainty when comparing eligible candidates. A wide interval should trigger investigation or an approved conservative response, not be silently narrowed to make the UI look better.
12. Practical Python example: routing and conformal calibration#
The following standard-library code demonstrates a fixed-weight directed graph baseline and split-conformal radius calculation. Nodes are string IDs and edge weights are seconds. It is a pedagogical example, not a production road-routing engine or a trained ML model.
PYTHONfrom heapq import heappush, heappop from math import isfinite, ceil def route_seconds(graph, start, goal): if start not in graph or goal not in graph: raise ValueError('unknown endpoint') for u, edges in graph.items(): for v, seconds in edges: if v not in graph or not isfinite(seconds) or seconds < 0: raise ValueError('invalid edge') best = {start: 0.0} heap = [(0.0, start)] while heap: cost, u = heappop(heap) if cost != best[u]: continue if u == goal: return cost for v, seconds in graph[u]: new = cost + seconds if new < best.get(v, float('inf')): best[v] = new heappush(heap, (new, v)) return None def conformal_radius(errors, alpha=.1): if not 0 < alpha < 1 or not errors or any( not isfinite(e) or e < 0 for e in errors ): raise ValueError('invalid calibration data') rank = ceil((len(errors) + 1) * (1 - alpha)) return sorted(errors)[rank - 1] if rank <= len(errors) else float('inf') g = {'A': [('B', 60), ('C', 180)], 'B': [('C', 70)], 'C': [], 'D': []} assert route_seconds(g, 'A', 'C') == 130 assert route_seconds(g, 'A', 'A') == 0 assert route_seconds(g, 'C', 'A') is None assert route_seconds(g, 'A', 'D') is None assert route_seconds({'A': [('B', 0)], 'B': []}, 'A', 'B') == 0 assert conformal_radius([10, 20, 30, 40], .4) == 30 assert conformal_radius([10, 20], .1) == float('inf') assert conformal_radius([0, 0, 0, 0], .4) == 0 for graph in [ {'A': [('B', -1)], 'B': []}, {'A': [('B', float('nan'))], 'B': []} ]: try: route_seconds(graph, 'A', 'B') except ValueError: pass else: raise AssertionError('invalid edge accepted') try: conformal_radius([], .1) except ValueError: pass else: raise AssertionError('empty calibration accepted') print('11 checks passed')
Output from local execution: 11 checks passed.
The shortest feasible A-to-C route is A-to-B-to-C, taking 130 seconds instead of the direct edge's 180 seconds. A reverse route is unavailable because the graph is directed. The calibration example intentionally uses a small illustrative sample; alpha = 0.4 yields rank 3 of four errors and a radius of 30 seconds. It does not demonstrate that a production ETA system achieves 60% coverage. Real calibration requires sufficiently large, representative, appropriately separated data.
With a binary heap allowing duplicate entries, the routing implementation has worst-case O((V + E) log(V + E)) time and O(V + E) auxiliary space; the initial graph validation adds O(V + E) time. Production engines validate graph artifacts during construction rather than scanning every edge on each request. Sorting calibration residuals requires O(n log n) time and O(n) memory. The radius is calculated offline and stored with its compatible model version.
This example excludes turn restrictions, map matching, departure-time-dependent costs, route geometry, feature serving, learned residuals and distributed operations. Tests establish the demonstrated algorithmic behavior only.
13. Low-latency serving and assignment consistency#
The initial assigned-driver ETA should be requested after the dispatch service commits an assignment. Position and traffic updates subsequently trigger coalesced refreshes.
For a request budget of 150 ms, an illustrative internal planning allocation might be 15 ms for validation and assignment lookup, 25 ms for feature access, 55 ms for routing, 25 ms for inference and 30 ms for serialization and overhead. This is a budgeting example, not a measured latency result. Per-stage p95 values cannot simply be added to prove an end-to-end p95; test the entire dependency chain under load. Apply a common deadline and account for retries, queueing and parallel feature reads.
Use a typed response contract containing assignment_id, pickup_revision, prediction_id, generated_at, estimated_seconds, interval fields when available, input freshness, model_version and source (model, routing fallback or unavailable). The app can compute a displayed arrival timestamp from generated_at plus estimated_seconds, while subsequent updates replace the old estimate.
Keep the estimate separate from authoritative ride lifecycle state. A late prediction from assignment A must not overwrite assignment B after reassignment. Require the expected assignment ID and pickup revision at publication, and reject older prediction sequence numbers.
Refresh based on meaningful motion, route deviations, traffic changes and a bounded freshness policy. Coalescing protects inference resources during high-rate updates. Avoid excessive display jitter, but do not enforce an artificially monotonically decreasing ETA: a legitimate road delay may increase the estimate. If using smoothing, evaluate whether it delays recognition of genuine changes.
14. Storage, caching and scalability#
A possible storage design:
| Entity | Key | Purpose |
|---|---|---|
| assignment state | ride_id, assignment_id | Current assignment, pickup revision and status |
| latest location | authorized driver ID | Position, timestamp and quality |
| traffic feature | graph_version, directed_edge_id, time window | Live estimates and historical priors |
| route artifact | route request fingerprint | Compatible route summary and graph/traffic version |
| prediction event | prediction_id | Input snapshot references, output, model version and latency |
| historical event lake | date, region | Training and evaluation events |
| model registry | model_version | Model, preprocessing, calibration and release metadata |
Partition location and traffic processing by workload-appropriate keys. Driver-centric telemetry can be partitioned by pseudonymous driver ID; segment aggregates may be partitioned by road-segment ID or region. Plan for skew in dense city centers. Regional routing services can keep graph data local, with a defined strategy for journeys crossing region boundaries.
Cache static graph structures and shared traffic features. A route cache key must account for origin/pickup representation, travel mode, graph version, traffic freshness and relevant restrictions. Do not reuse an exact previous ETA indefinitely after the driver moves. Avoid sharing personalized or location-sensitive responses across unrelated users.
Use batched feature lookups and vectorized inference for dispatch candidates. Restrict candidate selection to eligible drivers and use spatial indexes to prune the search; compute actual network travel times for finalists. Batch sizing trades throughput against queue delay. For the rider-facing path, isolate capacity from bulk experiments, model training and replay jobs.
At scale, a routing service can dominate cost rather than model inference. Benchmark a routing-only baseline first, then measure incremental costs for feature access and residual inference. Use autoscaling based on queue age, CPU or accelerator utilization and tail latency, not a single average request-rate metric.
15. Evaluation metrics and worked example#
Evaluate the prediction on completed, valid assignments, with the target and exclusions stated. Report cancellation and reassignment coverage separately. Let actual times be y and predictions be p, measured in seconds.
| Metric | Interpretation |
|---|---|
| MAE | Mean absolute error, easily understood in seconds |
| RMSE | Root mean squared error, more sensitive to large misses |
| Median absolute error | Typical error, less sensitive to extreme values |
| P90 absolute error | Tail reliability |
| Mean signed error | Detects systematic over- or underprediction; define sign convention |
| Within-tolerance rate | Fraction of estimates within a chosen error band |
| Interval coverage and width | Whether uncertainty estimates are calibrated and useful |
| Freshness and fallback rate | Operational quality and degraded-mode prevalence |
Use MAPE carefully: a near-zero remaining ETA can make percentage error unstable. Evaluate by time-to-arrival bucket, road distance, region, traffic regime, GPS quality, pickup type and initial versus update predictions. Track sample sizes and confidence intervals. The average of all frequent updates may be dominated by long rides; report assignment-level metrics as well.
Worked synthetic example: actual remaining times [120, 300, 600] seconds; routing predictions [150, 240, 720]; corrected predictions [135, 280, 660]. Routing absolute errors are [30, 60, 120] and MAE is 70 seconds. Corrected absolute errors are [15, 20, 60] and MAE is 31.67 seconds. With error defined as predicted minus actual, signed mean error changes from +30 seconds to approximately +18.33 seconds. This tiny fabricated example illustrates metric calculation only; it is not evidence of real-world uplift.
Offline evaluation is necessary but not sufficient. Run time-based backtests and compare the complete model-plus-routing system to the same compatible routing baseline. In shadow mode, log candidate predictions without changing what riders see. Assess differences through delayed outcome joins.
An online experiment should examine pickup wait, cancellation, perceived ETA reliability, support contacts and dispatch efficiency, with latency and safety guardrails. Assignment policies can affect which trips are observed, so changing ETA in dispatch is not merely a display experiment. Use an appropriate randomization unit, account for market interference, prespecify outcomes, and wait for label maturity. Avoid evaluating only users who completed rides when estimating the overall impact on riders.
16. Failure handling and reliability#
| Failure mode | Expected behavior |
|---|---|
| Stale driver location | Mark prediction degraded; obtain a fresh authorized location or return an appropriately qualified estimate |
| GPS uncertainty or map-match failure | Use validated fallback when feasible; avoid falsely precise routing |
| Live traffic feed delayed | Use compatible historical traffic priors, widen uncertainty where validated |
| Model unavailable or deadline exceeded | Use a tested routing-only estimate and identify its source |
| No feasible route | Return unavailable and trigger authorized operational handling; do not invent a travel time |
| Assignment or pickup changes | Invalidate old estimates; compute for the new revision |
| Queue duplicate or out-of-order telemetry | Deduplicate, use event-time and version checks |
| Graph and feature version mismatch | Reject incompatible data; use a compatible bundle or degrade |
| Regional service outage | Use approved failover with compatible graph data or an unavailable response |
| Severe drift or bad model release | Halt rollout, restore validated model bundle and monitor recovery |
Do not silently substitute zero seconds for unknown data. A route-only fallback has a different error distribution; calibrate it separately if it returns uncertainty bounds. If the last known estimate is too old, display uncertainty or unavailable rather than presenting it as current.
Use bounded retries, deadline propagation, circuit breakers and backpressure. Keep event reprocessing separate from real-time inference. At-least-once delivery is acceptable when consumers are idempotent and state transitions are revision-aware. Monitor prediction drop rates and explicitly test dependency outages, reordered events, routing failures and stale assignment writes.
Operational metrics include request p50/p95/p99, timeout and fallback rates, event lag, location age, graph-version mismatches, routing failures, prediction publication lag, stale-update rejection and model error by region. A rise in MAE may come from an upstream map or label issue rather than the ML model. Diagnose layers independently.
17. Model governance and continuous learning#
Store the complete compatible model bundle: feature definitions, training data cutoff, graph and routing assumptions, calibration artifact, model weights, code version and evaluation report. Shadow-test new bundles, compare quality and latency, then roll out by controlled cohorts with a rollback owner. Do not roll back only model weights while leaving incompatible preprocessing or calibration in place.
Retrain according to observed evidence: seasonal patterns, road-network changes, systematic regional error and traffic regime drift. Continuous telemetry does not mean continuous unvalidated model deployment. Recompute traffic features frequently while releasing models through controlled evaluation gates.
Analyze error disparities across neighborhoods and service conditions using appropriately governed data. Poor coverage in low-data areas is not solved by excluding those areas from evaluation. Provide conservative fallbacks, monitor quality and invest in representative data. Avoid collecting or inferring unrelated sensitive attributes for prediction.
Location access must be limited to legitimate operational and training purposes. Audit who accessed sensitive traces, enforce retention, protect model and feature endpoints, and prevent a rider or unauthorized service from requesting arbitrary drivers' private locations. Legal and privacy requirements vary by jurisdiction and need current expert review; the design does not assert compliance with any specific law.
18. Interview trade-offs and follow-up questions#
Why not use Haversine distance divided by average speed? It ignores network connectivity, one-way restrictions, traffic, turns and pickup approach. It is useful for approximate candidate pruning or a weak baseline, not as a reliable primary ETA.
Why not use only a neural network? Road topology and routing supply strong domain constraints. A learned correction can improve a robust baseline while keeping a usable fallback and making error analysis easier.
Why not recalculate on every GPS event? Telemetry can be orders of magnitude higher than actual useful ETA updates. Coalesce events, enforce freshness and recompute when information materially changes.
What if the driver hasn't accepted yet? The arrival estimate conditional on an assigned driver is not the same as the total pre-assignment wait. Model dispatch and acceptance separately; do not label an unaccepted candidate as an active assignment.
How do you handle a new city? Initialize with a verified road graph and historical or pooled traffic priors where available, use conservative uncertainty, monitor quality, and adapt only after sufficient representative observations.
What if the offline model improves but riders cancel more? Investigate calibration, systematic underestimation, display update behavior, assignment-policy changes and cohort effects. A lower aggregate MAE does not guarantee better marketplace outcomes.
19. Interview-ready answer#
I would first define pickup ETA as the remaining time from the assigned driver's current position to the agreed pickup location, separate from the time spent finding a driver and the subsequent trip duration. I would stream authorized GPS and traffic events into a map-matching and segment aggregation pipeline, use a versioned directed road network to compute a travel-time baseline, and train a supervised residual model on point-in-time route, traffic and contextual features.
The online ETA service would retrieve fresh features, route to the pickup, apply the learned correction and return calibrated uncertainty. It would use batched routing for dispatch candidates and coalesced updates for active assignments. Version-aware publication prevents stale estimates from previous assignments, while validated routing-only fallbacks preserve useful behavior during model outages.
I would evaluate MAE, tail error, signed bias and interval coverage on temporal and regional holdouts, account for cancelled rides and repeated observations, and monitor downstream pickup and cancellation outcomes in controlled experiments. The main trade-off is balancing prediction accuracy and freshness against routing cost, low-latency serving, uncertainty and reliable, privacy-preserving operation.
References and research transparency#
This article uses the authorized offline research exception. The following established research and documentation links support the general algorithms and engineering methods. Current link availability and contents were not live-verified in this session. The two Mermaid diagrams use standard fenced Mermaid syntax; live frontend rendering and local parser execution were not available for verification. No reference is presented as proof of Uber's current internal architecture.
- Dijkstra (1959) — A Note on Two Problems in Connexion with Graphs
- Hart, Nilsson and Raphael (1968) — A Formal Basis for the Heuristic Determination of Minimum Cost Paths
- H3 — Geospatial Indexing Documentation
- OSRM — Routing API Documentation
- Chen and Guestrin — XGBoost: A Scalable Tree Boosting System
- Angelopoulos and Bates — A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification
- Apache Kafka — Documentation
- Google — Rules of Machine Learning: Best Practices for ML Engineering
- Hyndman and Athanasopoulos — Forecasting: Principles and Practice
- NIST — AI Risk Management Framework
References
- 1.
- 2.
- 3.
- 4.OSRM — Routing API Documentationproject-osrm.org
- 5.
- 6.
- 7.Apache Kafka — Documentationkafka.apache.org
- 8.Google — Rules of Machine Learning: Best Practices for ML Engineeringdevelopers.google.com
- 9.
- 10.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython