Skip to main content
← CONCEPTS / SYSTEM-DESIGN
An end-to-end domain learning journey

H3 Hexagonal Spatial Indexing
& HMM Map-Matching.

H3 Hexagonal Spatial Indexing & HMM Map-Matching partitions the Earth into uniform hexagonal cells and uses a Viterbi Hidden Markov Model to snap noisy GPS pings onto exact OpenStreetMap road segments.
Start the journey7 sections· Last modified Nov 24, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, never snap GPS pings to the nearest Euclidean road; use H3 spatial indexing for O(1) partitioning and a Viterbi HMM that weighs road topology transitions.

TL;DR30-second simplified summary
▾

Real-time traffic engines pair H3 spatial indexing with 5-ping Viterbi HMM snapping.

Harmonic mean speeds update Customizable Contraction Hierarchies every second for <5ms congestion-aware ETAs.

Full walkthrough · 7 stages
01
foundation

Why Square Geohashes Fail & H3 Hexagons Win.

Why this matters: Understand uniform neighbor distances and hierarchical containment in Uber H3.

Think of Why Square Geohashes Fail & H3 Hexagons Win as the intuition layer for H3 Hexagonal Spatial Indexing & HMM Map-Matching: Understand uniform neighbor distances and hierarchical containment in Uber H3.

Square grids (Geohash/Quadtree) have 4 edge neighbors at distance 1 and 4 diagonal neighbors at distance sqrt(2), distorting spatial radius queries. Hexagons have 6 equidistant neighbors, minimal area distortion across the globe, and fast 64-bit integer k-ring lookups.

Spatial Grid

H3 Hexagonal Uniformity vs. Square Grid Distortion

GPS (lat, lon)Raw locationH3 64-Bit IndexDiscrete cell6 EquidistantNeighborsUniform radiusPartition & TileKeyLocality anchorExpands k-ring

1.Equidistant Rings: Every adjacent hexagon shares an edge at the exact same center-to-center distance.

2.Multi-Resolution: Bit-shifting a Res-9 cell yields its parent Res-6 cell in nanoseconds.

H3 hexagons provide uniform neighbor geometry and O(1) hierarchical parent/child bit operations.

02
foundation

Why Naive Nearest-Road Snapping Breaks.

Why this matters: Diagnose overpass, parallel-service-road, and U-turn snapping errors.

Think of Why Naive Nearest-Road Snapping Breaks as the intuition layer for H3 Hexagonal Spatial Indexing & HMM Map-Matching: Diagnose overpass, parallel-service-road, and U-turn snapping errors.

If a car drives on an elevated highway above a local street, a 15-meter GPS error can make the local street slightly closer. Nearest-neighbor snapping jumps the car onto the side street (25 km/h) and back to the highway (100 km/h), corrupting both speed analytics and ETAs.

Urban Canyon Error

Nearest-Neighbor Failure vs. Heading + Topology

Noisy GPS PingAmbiguous pointNaive Nearest RoadFalse speed jumpHeading & SpeedFilterDirection checkOSM Road TopologyPhysical constraintFilters wrong-way lanes

1.Heading Filter: Comparing GPS bearing against one-way OSM edge direction cuts candidate noise in half.

2.Topology Continuity: Cars cannot teleport through concrete dividers between highways and side streets.

Checking heading and physical road connectivity eliminates impossible overpass/frontage-road jumps.

Engineering Decision Framework
Problem
How to implement H3 Hexagonal Spatial Indexing & HMM Map-Matching without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, never snap GPS pings to the nearest Euclidean road; use H3 spatial indexing for O(1) partitioning and a Viterbi HMM that weighs road topology transitions.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When H3 Hexagonal Spatial Indexing & HMM Map-Matching experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
intermediate

Viterbi Hidden Markov Model (HMM) Map-Matching.

Why this matters: Snap a sequence of GPS pings to the most likely drivable path.

HMM treats true road segments as hidden states and noisy GPS pings as observations.

Emission probability models Gaussian GPS error exp(-d^2 / 2*sigma^2), while Transition probability penalizes paths whose driving route distance diverges from straight-line GPS distance.

Viterbi HMM

HMM Emission & Transition Lattice

H3 Res-9 CandidatesHidden statesEmission Prob P(z|s)Proximity scoreTransition ProbA_ijRouting realismViterbi BacktrackerSnapped pathComputes A* route dist

1.Newson-Krumm Formula: Exponential penalty on |d_gps - d_route| naturally rejects circuitous U-turns.

2.Sliding Viterbi: Maintain a 5-ping trailing window per vehicle in Flink for real-time snapping.

Viterbi HMM balances GPS proximity with realistic road-network routing transitions.

04
intermediate

Segment Speed Aggregation & Outlier Filtering.

Why this matters: Convert snapped vehicle trajectories into accurate road-segment speeds.

A parked delivery truck or a stopped bus still emits GPS pings.

Aggregating raw pings without filtering stationary vehicles pulls road speed down to 0 km/h.

Speed Telemetry

Outlier Scrubbing & Harmonic Mean Speed

Snapped VehiclePingsMatched telemetryParked/Bus FilterOutlier guardHarmonic Mean (60s)Space-mean speedRouting Edge WeightETA graph inputComputes space-mean

1.Harmonic vs Arithmetic: Harmonic mean equals true space-mean speed, preventing fast outliers from skewing ETAs.

2.Confidence Weight: Blend live speed with historical time-of-day prior when sample count < 3.

Scrubbing parked outliers and using harmonic mean yields unbiased travel-time edge weights.

05
intermediate

Dynamic Graph Edge Updates & Contraction Hierarchies.

Why this matters: Recompute shortest-time ETAs across millions of road edges in milliseconds.

Think of Dynamic Graph Edge Updates & Contraction Hierarchies as the intuition layer for H3 Hexagonal Spatial Indexing & HMM Map-Matching: Recompute shortest-time ETAs across millions of road edges in milliseconds.

Standard Dijkstra over a 50M-edge continental OSM graph takes seconds. Contraction Hierarchies (CH) pre-compute highway shortcut edges for <5ms queries, while Customizable Contraction Hierarchies (CCH) allow updating live edge weights in ~1 second without rebuilding topology.

Live Routing

Customizable Contraction Hierarchies (CCH)

Static OSM TopologyBase graphCCH CustomizationDynamic shortcutsBi-DirectionalDijkstraRouting engineNavigation & ETAAPIUser responseRefreshes edge weights

1.1-Second Refresh: CCH separates slow topology ordering from fast 1-second weight customization.

2.Sub-5ms Queries: Bi-directional search over shortcuts answers continental routes in milliseconds.

Customizable Contraction Hierarchies combine sub-5ms routing queries with 1-second live traffic updates.

06
advanced

Handling H3 Boundary Crossings in Partitioned Streams.

Why this matters: Prevent vehicles crossing H3 Resolution-6 borders from splitting HMM state.

Think of Handling H3 Boundary Crossings in Partitioned Streams as the intuition layer for H3 Hexagonal Spatial Indexing & HMM Map-Matching: Prevent vehicles crossing H3 Resolution-6 borders from splitting HMM state.

If Kafka partitions GPS streams by H3 Res-6 cell, a car driving across a hex boundary suddenly lands on a different Flink worker, losing its 5-ping HMM history. Partitioning Kafka by vehicle_id (while caching Res-9 OSM tiles locally) keeps each car's HMM state contiguous.

Stream Partitioning

Vehicle-Keyed HMM vs. H3-Keyed Aggregation

Raw GPS StreamContiguous stateFlink HMM OperatorZero border lossSnapped SegmentStreamSpatial shuffle60s SpeedAggregatorHeatmap emitterRe-keys by H3 cell

1.Two-Stage Keying: Key by vehicle_id for map-matching, then re-key by H3_cell for speed aggregation.

2.Zero Border Jumps: Vehicles crossing city hex borders never lose their Viterbi trajectory context.

Two-stage stream keying preserves continuous vehicle HMM state before spatial H3 aggregation.

07
advanced

Short-Term Congestion Prediction (15–60m Horizon).

Why this matters: Predict future bottlenecks using Spatio-Temporal Graph Neural Networks (ST-GNN).

Think of Short-Term Congestion Prediction (15–60m Horizon) as the intuition layer for H3 Hexagonal Spatial Indexing & HMM Map-Matching: Predict future bottlenecks using Spatio-Temporal Graph Neural Networks (ST-GNN).

For a 45-minute drive, current traffic at the destination is stale by the time you arrive. An ST-GNN models upstream/downstream OSM road dependencies across H3 neighborhoods, predicting segment speeds at t+15m, t+30m, and t+60m for time-dependent routing.

Predictive Routing

Spatio-Temporal GNN Congestion Horizon

Live H3 Speeds(t=0)Real-time inputTime-of-Day PriorHistorical patternST-GNN ForecasterPropagation modelTime-Dependent ETAAccurate arrivalSupplies rush-hour curve

1.Shockwave Propagation: ST-GNNs learn how a highway bottleneck propagates backward over 30 minutes.

2.Time-Dependent Dijkstra: Evaluate each downstream edge at the predicted arrival timestamp, not t=0.

ST-GNNs forecast congestion propagation so long trips route around future bottlenecks.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is Uber H3 hexagonal indexing preferred over square Geohashes for spatial congestion analytics?

Recommended Learning Flow