StackMonkey
Home / Templates / Ride Sharing

Designing a Real-Time Geospatial Dispatch & Matching Engine

Matching riders with moving drivers within milliseconds requires processing continuous GPS ping streams, indexing geospatial coordinates into hexagonal spatial grids, and solving bipartite graph matching without race conditions.

Active Moving Drivers
1,000,000
Continuous GPS telemetry
Location Ingest Rate
250,000 / sec
4-second ping frequency
Peak Ride Dispatches
25,000 / min
Batch window matching
Matching Latency SLA
< 300 ms
p99 dispatch compute
Step 1 of 4

Geospatial Telemetry & In-Memory Footprint

Driver location coordinates change constantly. Traditional relational databases cannot survive 250k writes/sec of spatial indexing. The architecture must live entirely in partitioned in-memory spatial caches.

Ingress Throughput Calculation

  • 1. Ping Cadence: 1,000,000 active drivers stream an updated GPS packet every 4 seconds = 250,000 updates/second ingress.
  • 2. Packet Payload: {driver_id: uint64, lat: float64, lng: float64, bearing: uint16, speed: uint8, status: uint8} ≈ 48 bytes uncompressed, compressed to 28 bytes via Protocol Buffers.
  • 3. Ingress Bandwidth: 250,000 * 28 bytes = 7 MB/s (56 Mbps) network bandwidth. Modest network load, but massive state mutation rate.

Hexagonal Spatial Index (Uber H3)

  • 1. H3 Resolution: Resolution 8 cells have an edge length of ~461 meters and an area of 0.737 km², representing the exact walking distance radius for city pickups.
  • 2. Memory Allocation: Each driver's active location is stored in Redis Geo / In-Memory H3 Set: 1M drivers * 64 bytes index entry = 64 MB RAM. The entire world's live moving fleet fits inside a single Redis instance.
  • 3. Partitioning Key: Sharded horizontally across 16 Redis nodes using parent H3 Resolution 4 cells (~1,770 km² metro regions: NYC, London, Tokyo, SF) to avoid cross-cluster geospatial searches.
Step 2 of 4

Greedy Local Match vs. Batch Bipartite Matching

Why greedy matching causes globally terrible ETAs. Discover why Uber and Lyft batch rider demand into rolling 3-second matching windows.

Dispatch Pattern Algorithm Driver Idle Time Average Pickup ETA Concurrency Vulnerability
Greedy First-Come (Naive) k-Nearest Neighbor (KNN) High (sub-optimal assignments) 6.4 minutes Rider A takes the only driver 1 min away; Rider B who requested 100ms later must wait 12 mins.
Batch Optimization (Recommended) Hungarian / Min-Cost Flow Minimal (global optimum) 3.8 minutes (-40% wait) Requires 3-second demand buffer window, but completely eliminates race conditions.

The H3 Hexagonal Advantage

Unlike square Geohash grids where diagonal cells are $\sqrt{2} \times$ farther than orthogonal neighbors, every hexagon in an H3 grid has exactly six equidistant neighbors. Finding all drivers within a 2 km radius requires simply querying the central hexagon and its 2 concentric rings of neighboring hexagons (19 hexagons total) via constant-time index lookups.

Step 3 of 4

Double-Booking Races & Surge Pricing Storms

When high density demand hits a single cell (e.g. concert ends), multiple dispatchers attempt to assign the same 5 drivers simultaneously.

The Driver Race Collapse

Suppose Rider 1 and Rider 2 request rides at the exact same millisecond in downtown Manhattan. Driver D is the closest driver to both.

Dispatcher 1 checks D (status: IDLE) and dispatches ride offer. Dispatcher 2 checks D (status: IDLE) and dispatches ride offer. Both drivers tap "Accept" on their phone.

Without distributed state machine locks, both rides are confirmed. When D arrives, one customer is left stranded on the curb, generating an immediate customer support escalation.

Production Mitigations
  • Atomic Redis CAS State Transitions: Driver status transition from `IDLE` to `OFFERED` is executed via atomic Redis Lua script with a 15-second expiration lease.
  • Trip Finite State Machine: PostgreSQL trip status transitions follow strict monotonic states: `REQUESTED` → `MATCHED` → `ARRIVING` → `IN_PROGRESS` → `COMPLETED`.
  • Cell-Level Rate Limiting: Surge pricing algorithms cap local matching queue rates to match verified available driver capacity $\rho < 0.95$.
Step 4 of 4

Six-Component Dispatch Architecture

The distributed infrastructure linking driver GPS telemetry to real-time bipartite matching workers.

01 · Location Stream Gateway
Netty / Go Socket Cluster
Maintains lightweight UDP/TCP sessions with 1M driver apps. Ingests 250,000 pings/sec and forwards raw coordinates into Apache Kafka.
02 · Regional Kafka Ingestion Bus
Kafka Partitioned by H3 Region
Partitions location streams by metropolitan area H3 Resolution 4 cells. Decouples raw ingestion from downstream spatial indexing and ETA processing.
03 · Live Spatial Index Store
Redis Geo / In-Memory H3 Index
Maintains current coordinates and status (`IDLE`, `ON_TRIP`) for all active drivers. Responds to radius neighborhood queries in sub-2ms.
04 · Batch Matching Engine
Distributed Dispatch Worker Pods
Executes rolling 3-second batch matching rounds. Pulls rider demand and idle driver supply, solves min-weight bipartite match, and pushes driver offers.
05 · Trip Lifecycle DB (ACID)
CockroachDB / PostgreSQL
Source of truth for trip states, fare calculations, and payment tokens. Enforces serializable transactions for driver confirmations.
06 · Dynamic Surge & ETA Engine
Apache Flink Stream Processor
Aggregates supply-demand ratios per H3 cell over rolling 1-minute tumbling windows. Calculates dynamic surge multipliers and routing ETAs.
Interactive Discrete Event Simulation

Simulate the Ride Sharing Dispatch Live

Test greedy vs batch matching algorithms, trigger localized surge spikes, and observe driver idle time and rider wait latency live in your browser.