Streaming ETA System with GPS Signal Processing
Machine LearningModel answerLast updated
Build a low-latency pipeline that continuously updates driver ETAs using only GPS pings and trip events, handling noisy location data and grid transitions.
You're building a system that maintains up-to-date estimated time of arrival (ETA) for active drivers, organized by spatial grid cells covering a city. The system must process streaming location data and predict how much time remains until each driver reaches their next destination.
Available data sources:
- GPS location pings from driver devices (latitude, longitude, timestamp, accuracy, optional speed and heading)
- Trip lifecycle events (trip accepted, passenger picked up, passenger dropped off, trip cancelled)
Requirements: Your design must address:
- Data ingestion: How do you ingest, partition, and join the two data streams efficiently?
- Signal quality: GPS data contains measurement errors, drift, and outliers. How do you clean and correct location data to accurately place drivers in grid cells?
- ETA computation: How do you calculate and continuously refresh the remaining travel time for each active driver?
- Model design: What modeling approach fits the latency and throughput constraints? How do you train it?
- Feature engineering: All features must derive strictly from the provided streams. What features do you compute, and how?
- Performance: The system must handle tens of thousands of concurrent drivers with sub-second update latency. How do you achieve this?
- Operations: How do you monitor model quality, detect degradation, and safely deploy updates?
- Evaluation: How do you validate the system works correctly, both offline and after launch?
Provide concrete technical choices: algorithms for location correction, data schemas, state management strategy, update frequency, and your approach to handling failures.
Constraint: You may not use external data sources (traffic APIs, weather, road segment features). Every signal must be derived from the GPS pings and trip events you receive.
Hints
Hint 1
Start by clarifying scale assumptions and latency targets—numbers drive architectural decisions.
Hint 2
GPS measurements are noisy; you'll need filtering (like Kalman) and a method to snap corrected positions to valid locations using patterns learned from historical data.
Hint 3
Think about stateful stream processing keyed by driver—this lets you maintain context (position history, current trip phase, feature windows) without expensive joins.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Streaming ETA System
Overview
This problem tests your ability to integrate three challenging domains: streaming data architecture, signal processing for noisy sensors, and low-latency machine learning. The core constraint—deriving all features from only two raw streams—forces you to build learned representations of the environment rather than relying on external enrichment.
1. Requirements and Scale
Begin by establishing scope and quantifying the workload.
Scale assumptions for a major metropolitan area:
- 40,000 active drivers during peak hours
- GPS pings arrive every 4 seconds → ~10,000 pings/second
- Trip state transitions (accept, pickup, dropoff) → ~1,500 events/second
- System must support multiple cities; partition by geography
Spatial partitioning:
- Divide the city into hexagonal grid cells using H3 at resolution 9 (~0.1 km² per cell)
- Hexagons provide uniform neighbor topology, simplifying transition modeling
Service level objectives:
- End-to-end latency: ping received → ETA updated in under 1 second (p99)
- API response time: under 20ms for driver or cell queries (p99)
- Freshness: no ETA older than 10 seconds for active drivers
- Availability: 99.9%
Output:
- Per-driver: remaining seconds to next waypoint (pickup or dropoff), with confidence bounds
- Per-cell: aggregate statistics (median ETA, count of drivers currently in that cell)
2. High-Level Architecture
Mobile devices → API Gateway → Kafka topics (gps_pings, trip_events)
↓
Flink stateful streaming job (keyed by driver_id):
• Deduplication and ordering
• Kalman filtering for position smoothing
• Matching to learned spatial graph
• Grid cell assignment with hysteresis
• Feature computation from windows
• Model inference (embedded predictor)
↓
Output topics → Redis (driver state, cell aggregates) + Data lake (Parquet)
↓
Offline: Spark batch training → Model registry → Canary deployment to stream processors
3. Data Ingestion and Stream Processing
Kafka topics:
gps_pings: keyed bydriver_id, contains{driver_id, trip_id, device_ts, server_ts, lat, lon, accuracy_meters, speed, heading, sequence_number}trip_events: keyed bydriver_id, contains{trip_id, driver_id, event_type, timestamp, pickup_location, dropoff_location}
Partitioning strategy:
- Partition both topics by
driver_idusing consistent hashing - Co-locate geographically nearby drivers when possible to optimize cell aggregation
- Use ~50 partitions per city to balance parallelism and state size
Flink job structure:
- Key both streams by
driver_idso pings and trip events co-locate in the same task - Maintain keyed state per driver: position history, Kalman filter state, current trip context
- Use event-time processing with 5-second watermark for late arrivals
- Deduplicate on
sequence_number; discard pings with timestamps older than 30 seconds
4. GPS Signal Cleaning and Location Correction
Raw GPS contains systematic errors: multipath interference near buildings, atmospheric delays, and device clock drift. A multi-stage pipeline improves accuracy.
Stage 1: Outlier rejection
Drop a ping if:
- Reported accuracy exceeds 50 meters
- Implied velocity from previous accepted point exceeds 40 m/s (144 km/h)
- Timestamp is non-monotonic or duplicated
Stage 2: Kalman filter
Apply a constant-velocity motion model in a local coordinate frame (convert lat/lon to East-North-Up meters).
- State vector:
[x, y, velocity_x, velocity_y] - Measurement noise R derived from reported accuracy²
- Process noise Q tuned on historical traces to balance responsiveness vs. smoothing
- Update state on each accepted ping; prediction step uses elapsed time
This produces a smoothed trajectory that reduces high-frequency jitter.
Stage 3: Matching to learned spatial structure
Without access to external road networks, build a transition graph from historical data:
- Aggregate past filtered trajectories into H3 cells at resolution 10 (~0.015 km²)
- Create directed edges between cells that drivers frequently traverse consecutively
- Store transition counts and median traversal times per edge
- This graph implicitly captures road connectivity and typical speeds
Apply hidden Markov model matching:
- Emission probability: Gaussian centered on filtered position with variance = Kalman covariance
- Transition probability: penalize large deviations from learned cell-to-cell patterns
- Use online Viterbi with a sliding window of 8 recent points for low-latency, mostly-causal output
Stage 4: Grid cell assignment
- Assign driver to the most likely cell from the HMM matcher
- Apply hysteresis: change cell assignment only after 2 consecutive points fall in the new cell, preventing rapid boundary oscillations
- Emit
(driver_id, old_cell, new_cell, timestamp)to downstream cell aggregators
5. Feature Engineering (Derived from Approved Streams Only)
All features must trace back to GPS pings or trip events. No external enrichment.
Driver-level features:
- Current speed (from Kalman filter)
- Exponentially weighted moving average speed over 1-minute and 5-minute windows
- Heading change rate (angular acceleration proxy)
- Time elapsed since trip accepted / since passenger pickup
- Straight-line distance remaining to destination
- Graph path distance (sum of learned edge traversal times along shortest path on the transition graph)
- Fraction of route completed (current progress / estimated total)
- Number of cells remaining on path
Congestion proxy (cell-level, learned from collective behavior):
- Compute rolling median speed of all drivers in each cell over a 5-minute tumbling window
- Compare current driver speed to cell median → relative speed feature
- Count of drivers currently in cell (proxy for density)
- This captures local traffic conditions without external data
Temporal features:
- Hour of day, day of week (from ping timestamp)
- Time since last ping (staleness indicator)
Trip phase indicator:
- Binary flags:
is_enroute_to_pickup,is_on_trip_to_dropoff
Features are computed incrementally in Flink keyed state using efficient ring buffers and streaming quantile sketches (t-digest) for aggregates.
6. Model Selection and Training
Model choice: Gradient boosted decision trees (LightGBM)
Reasoning:
- Sub-millisecond inference on CPU (critical for inline serving)
- Handles mixed feature types and missing values gracefully
- Embeds easily in JVM-based streaming runtime
- Interpretable for debugging
Target variable:
- Predict the residual:
(actual_arrival_time - current_time) - baseline_graph_eta - Baseline is the sum of learned edge traversal times along the shortest path
- Predicting the residual stabilizes training and allows fallback to the baseline during model failures
- Train quantile regressors for p10, p50, p90 to provide confidence intervals
Training pipeline:
- Labels: ground truth arrival times from
PICKUPandDROPOFFtrip events, joined offline to historical GPS pings - Sample one ping every 30 seconds per trip to reduce autocorrelation
- Train on 6 weeks of data with time-based split (no shuffling)
- Retrain daily; store models in a versioned registry (MLflow or similar)
Critical: training-serving parity
- Implement feature computation logic once in a shared library
- Run the same code in Flink for online serving and in Spark for offline label generation
- This prevents the most common source of production ML failures
7. Low-Latency Serving
Embedded inference:
- Serialize LightGBM model to a compact format
- Load model into Flink task JVM memory
- Invoke prediction synchronously in the keyed state processing function
- Latency budget: feature computation (0.3ms) + inference (0.8ms) + state write (0.4ms) ≈ 1.5ms
State management:
- Flink RocksDB state backend for durability and large state
- Mirror driver state to Redis for external API queries (async fire-and-forget writes)
- Redis key:
driver:{driver_id}→{current_cell, eta_seconds, eta_p10, eta_p90, last_update_ts, model_version}
Cell aggregates:
- Separate Flink operator keyed by
cell_id - Receives
(driver_id, old_cell, new_cell, eta)messages - Maintains count and t-digest sketch per cell
- Flushes to Redis every 2 seconds:
cell:{h3_id}→{driver_count, median_eta, p90_eta}
Fallback and staleness handling:
- If no ping arrives within 10 seconds, dead-reckon ETA by subtracting elapsed time
- Mark ETA as
staleafter 30 seconds without updates - If model inference fails, return baseline graph ETA
8. Monitoring and Model Management
Metrics to track:
- Prediction error: absolute difference between predicted ETA and actual arrival (computed post-hoc when trips complete)
- Calibration: do 90% of actuals fall within the p10–p90 prediction interval?
- Latency: ping-to-update duration at p50, p95, p99
- Throughput: pings processed per second per task
- GPS quality: distribution of reported accuracy, percentage of pings rejected
Alerting:
- Fire alert if median absolute error exceeds baseline by >20% for 10 minutes
- Alert if p99 latency exceeds 1 second
- Alert if Kalman filter divergence rate spikes (indicates systematic GPS issues)
Safe deployment:
- Shadow mode: run new model alongside production, log predictions without serving
- Canary: route 5% of drivers to new model, compare error distributions
- Promote if no statistically significant degradation after 24 hours
- Automated rollback if error rate exceeds threshold
9. Offline and Online Evaluation
Offline:
- Replay historical ping and trip streams through the Flink job in a test environment
- Compare predicted ETAs to actual arrival times on a holdout time period
- Compute mean absolute error, root mean squared error, and calibration metrics
- Ensure training-serving parity by validating that offline feature computation matches online feature logs
Online A/B test:
- Randomly assign drivers to model variants
- Wait until trips complete, then compute actual error
- Compare distributions using Mann-Whitney U test
- Run for at least 3 days to account for day-of-week effects
- Validate that cell aggregate distributions remain stable (check for unintended side effects)
Common failure modes to check:
- Spatial bias: is the model worse in certain neighborhoods? (could indicate insufficient training data coverage)
- Temporal drift: does performance degrade during unusual events (holidays, weather)?
- Cold start: how does the model perform in the first minute after trip acceptance, when feature windows are incomplete?
10. Key Design Tradeoffs
Accuracy vs. latency:
- A deeper smoothing window or RTS backward pass improves position accuracy but adds delay
- Online Viterbi with a small window (8 points) balances these constraints
Model complexity:
- Gradient boosting is a pragmatic choice; a sequence model (LSTM, Transformer) could capture temporal dependencies better but increases inference latency to 5–10ms
- Mention this as a future iteration if the interviewer pushes
State size:
- Storing per-driver feature windows consumes memory; ring buffers and approximate sketches keep this manageable
- RocksDB spills to disk, but this adds latency; tune checkpoint intervals carefully
Feature richness vs. constraint compliance:
- Many powerful features (weather, events, detailed road attributes) are off-limits
- The learned transition graph and collective speed aggregates are clever workarounds that respect the constraint
Summary
This design balances signal processing rigor (Kalman filtering, HMM matching) with pragmatic ML engineering (embedded GBDT, shared feature code, canary deployments). The hardest part is deriving meaningful features without external enrichment—learned spatial structure from historical patterns is the key insight. A strong answer demonstrates end-to-end thinking: from noisy sensor data through feature computation to safe production deployment.