The Geospatial Matching Problem
When a passenger taps "Request Ride", the dispatch server must:
- Find all active, unoccupied drivers within a 3-kilometer radius.
- Sort drivers by estimated arrival time (accounting for one-way street topology).
- Sequentially dispatch the ride offer with a 15-second acceptance countdown timer.
Sub-Millisecond Radius Lookups with Redis GEO
Querying a relational SQL database with WHERE ST_DWithin(...) on every driver's 3-second GPS ping will saturate disk I/O. Instead, we stream high-frequency coordinate updates into Redis in-memory spatial sorted sets:
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
def update_driver_location(driver_id: str, longitude: float, latitude: float):
'''Records driver position in Redis GEO sorted set.'''
# GEOADD key longitude latitude member
r.geoadd("active_drivers_geo", (longitude, latitude, driver_id))
# Keep 60-second expiration heartbeat to clear offline drivers
r.setex(f"driver_heartbeat:{driver_id}", 60, "online")
def find_nearby_drivers(passenger_lon: float, passenger_lat: float, radius_km: float = 3.0) -> list:
'''Finds nearest active drivers within radius sorted by ascending distance.'''
# GEORADIUS key longitude latitude radius unit WITHDIST WITHCOORD ASC
results = r.geosearch(
"active_drivers_geo",
longitude=passenger_lon,
latitude=passenger_lat,
radius=radius_km,
unit="km",
withdist=True,
withcoord=True,
sort="ASC"
)
nearby = []
for member, distance, coords in results:
driver_id = member.decode('utf-8') if isinstance(member, bytes) else member
# Verify driver is not in a ghost state
if r.exists(f"driver_heartbeat:{driver_id}"):
nearby.append({
"driver_id": driver_id,
"distance_km": round(distance, 2),
"coordinates": (coords[0], coords[1])
})
return nearby